version 0.3.21
[fms.git] / libs / sqlite3 / sqlite3.c
1 /******************************************************************************
2 ** This file is an amalgamation of many separate C source files from SQLite
3 ** version 3.6.3.  By combining all the individual C code files into this 
4 ** single large file, the entire code can be compiled as a one 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% are 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 in the first
14 ** 6364 lines past this header comment.)  Additional code files may be
15 ** needed if you want a wrapper to interface SQLite with your choice of
16 ** programming language.  The code for the "sqlite3" command-line shell
17 ** is also in a separate file.  This file contains only code for the core
18 ** SQLite library.
19 **
20 ** This amalgamation was generated on 2008-09-22 10:45:10 UTC.
21 */
22 #define SQLITE_CORE 1
23 #define SQLITE_AMALGAMATION 1
24 #ifndef SQLITE_PRIVATE
25 # define SQLITE_PRIVATE static
26 #endif
27 #ifndef SQLITE_API
28 # define SQLITE_API
29 #endif
30 /************** Begin file sqliteInt.h ***************************************/
31 /*
32 ** 2001 September 15
33 **
34 ** The author disclaims copyright to this source code.  In place of
35 ** a legal notice, here is a blessing:
36 **
37 **    May you do good and not evil.
38 **    May you find forgiveness for yourself and forgive others.
39 **    May you share freely, never taking more than you give.
40 **
41 *************************************************************************
42 ** Internal interface definitions for SQLite.
43 **
44 ** @(#) $Id: sqliteInt.h,v 1.772 2008/09/12 16:03:48 drh Exp $
45 */
46 #ifndef _SQLITEINT_H_
47 #define _SQLITEINT_H_
48
49 /*
50 ** Include the configuration header output by 'configure' if we're using the
51 ** autoconf-based build
52 */
53 #ifdef _HAVE_SQLITE_CONFIG_H
54 #include "config.h"
55 #endif
56
57 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
58 /************** Begin file sqliteLimit.h *************************************/
59 /*
60 ** 2007 May 7
61 **
62 ** The author disclaims copyright to this source code.  In place of
63 ** a legal notice, here is a blessing:
64 **
65 **    May you do good and not evil.
66 **    May you find forgiveness for yourself and forgive others.
67 **    May you share freely, never taking more than you give.
68 **
69 *************************************************************************
70 ** 
71 ** This file defines various limits of what SQLite can process.
72 **
73 ** @(#) $Id: sqliteLimit.h,v 1.8 2008/03/26 15:56:22 drh Exp $
74 */
75
76 /*
77 ** The maximum length of a TEXT or BLOB in bytes.   This also
78 ** limits the size of a row in a table or index.
79 **
80 ** The hard limit is the ability of a 32-bit signed integer
81 ** to count the size: 2^31-1 or 2147483647.
82 */
83 #ifndef SQLITE_MAX_LENGTH
84 # define SQLITE_MAX_LENGTH 1000000000
85 #endif
86
87 /*
88 ** This is the maximum number of
89 **
90 **    * Columns in a table
91 **    * Columns in an index
92 **    * Columns in a view
93 **    * Terms in the SET clause of an UPDATE statement
94 **    * Terms in the result set of a SELECT statement
95 **    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
96 **    * Terms in the VALUES clause of an INSERT statement
97 **
98 ** The hard upper limit here is 32676.  Most database people will
99 ** tell you that in a well-normalized database, you usually should
100 ** not have more than a dozen or so columns in any table.  And if
101 ** that is the case, there is no point in having more than a few
102 ** dozen values in any of the other situations described above.
103 */
104 #ifndef SQLITE_MAX_COLUMN
105 # define SQLITE_MAX_COLUMN 2000
106 #endif
107
108 /*
109 ** The maximum length of a single SQL statement in bytes.
110 **
111 ** It used to be the case that setting this value to zero would
112 ** turn the limit off.  That is no longer true.  It is not possible
113 ** to turn this limit off.
114 */
115 #ifndef SQLITE_MAX_SQL_LENGTH
116 # define SQLITE_MAX_SQL_LENGTH 1000000000
117 #endif
118
119 /*
120 ** The maximum depth of an expression tree. This is limited to 
121 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might 
122 ** want to place more severe limits on the complexity of an 
123 ** expression.
124 **
125 ** A value of 0 used to mean that the limit was not enforced.
126 ** But that is no longer true.  The limit is now strictly enforced
127 ** at all times.
128 */
129 #ifndef SQLITE_MAX_EXPR_DEPTH
130 # define SQLITE_MAX_EXPR_DEPTH 1000
131 #endif
132
133 /*
134 ** The maximum number of terms in a compound SELECT statement.
135 ** The code generator for compound SELECT statements does one
136 ** level of recursion for each term.  A stack overflow can result
137 ** if the number of terms is too large.  In practice, most SQL
138 ** never has more than 3 or 4 terms.  Use a value of 0 to disable
139 ** any limit on the number of terms in a compount SELECT.
140 */
141 #ifndef SQLITE_MAX_COMPOUND_SELECT
142 # define SQLITE_MAX_COMPOUND_SELECT 500
143 #endif
144
145 /*
146 ** The maximum number of opcodes in a VDBE program.
147 ** Not currently enforced.
148 */
149 #ifndef SQLITE_MAX_VDBE_OP
150 # define SQLITE_MAX_VDBE_OP 25000
151 #endif
152
153 /*
154 ** The maximum number of arguments to an SQL function.
155 */
156 #ifndef SQLITE_MAX_FUNCTION_ARG
157 # define SQLITE_MAX_FUNCTION_ARG 100
158 #endif
159
160 /*
161 ** The maximum number of in-memory pages to use for the main database
162 ** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
163 */
164 #ifndef SQLITE_DEFAULT_CACHE_SIZE
165 # define SQLITE_DEFAULT_CACHE_SIZE  2000
166 #endif
167 #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
168 # define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
169 #endif
170
171 /*
172 ** The maximum number of attached databases.  This must be between 0
173 ** and 30.  The upper bound on 30 is because a 32-bit integer bitmap
174 ** is used internally to track attached databases.
175 */
176 #ifndef SQLITE_MAX_ATTACHED
177 # define SQLITE_MAX_ATTACHED 10
178 #endif
179
180
181 /*
182 ** The maximum value of a ?nnn wildcard that the parser will accept.
183 */
184 #ifndef SQLITE_MAX_VARIABLE_NUMBER
185 # define SQLITE_MAX_VARIABLE_NUMBER 999
186 #endif
187
188 /* Maximum page size.  The upper bound on this value is 32768.  This a limit
189 ** imposed by the necessity of storing the value in a 2-byte unsigned integer
190 ** and the fact that the page size must be a power of 2.
191 */
192 #ifndef SQLITE_MAX_PAGE_SIZE
193 # define SQLITE_MAX_PAGE_SIZE 32768
194 #endif
195
196
197 /*
198 ** The default size of a database page.
199 */
200 #ifndef SQLITE_DEFAULT_PAGE_SIZE
201 # define SQLITE_DEFAULT_PAGE_SIZE 1024
202 #endif
203 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
204 # undef SQLITE_DEFAULT_PAGE_SIZE
205 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
206 #endif
207
208 /*
209 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
210 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
211 ** device characteristics (sector-size and atomic write() support),
212 ** SQLite may choose a larger value. This constant is the maximum value
213 ** SQLite will choose on its own.
214 */
215 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
216 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
217 #endif
218 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
219 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
220 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
221 #endif
222
223
224 /*
225 ** Maximum number of pages in one database file.
226 **
227 ** This is really just the default value for the max_page_count pragma.
228 ** This value can be lowered (or raised) at run-time using that the
229 ** max_page_count macro.
230 */
231 #ifndef SQLITE_MAX_PAGE_COUNT
232 # define SQLITE_MAX_PAGE_COUNT 1073741823
233 #endif
234
235 /*
236 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
237 ** operator.
238 */
239 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
240 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
241 #endif
242
243 /************** End of sqliteLimit.h *****************************************/
244 /************** Continuing where we left off in sqliteInt.h ******************/
245
246 /* Disable nuisance warnings on Borland compilers */
247 #if defined(__BORLANDC__)
248 #pragma warn -rch /* unreachable code */
249 #pragma warn -ccc /* Condition is always true or false */
250 #pragma warn -aus /* Assigned value is never used */
251 #pragma warn -csu /* Comparing signed and unsigned */
252 #pragma warn -spa /* Suspicous pointer arithmetic */
253 #endif
254
255 /* Needed for various definitions... */
256 #ifndef _GNU_SOURCE
257 # define _GNU_SOURCE
258 #endif
259
260 /*
261 ** Include standard header files as necessary
262 */
263 #ifdef HAVE_STDINT_H
264 #include <stdint.h>
265 #endif
266 #ifdef HAVE_INTTYPES_H
267 #include <inttypes.h>
268 #endif
269
270 /*
271 ** A macro used to aid in coverage testing.  When doing coverage
272 ** testing, the condition inside the argument must be evaluated 
273 ** both true and false in order to get full branch coverage.
274 ** This macro can be inserted to ensure adequate test coverage
275 ** in places where simple condition/decision coverage is inadequate.
276 */
277 #ifdef SQLITE_COVERAGE_TEST
278 SQLITE_PRIVATE   void sqlite3Coverage(int);
279 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
280 #else
281 # define testcase(X)
282 #endif
283
284 /*
285 ** The ALWAYS and NEVER macros surround boolean expressions which 
286 ** are intended to always be true or false, respectively.  Such
287 ** expressions could be omitted from the code completely.  But they
288 ** are included in a few cases in order to enhance the resilience
289 ** of SQLite to unexpected behavior - to make the code "self-healing"
290 ** or "ductile" rather than being "brittle" and crashing at the first
291 ** hint of unplanned behavior.
292 **
293 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
294 ** be true and false so that the unreachable code then specify will
295 ** not be counted as untested code.
296 */
297 #ifdef SQLITE_COVERAGE_TEST
298 # define ALWAYS(X)      (1)
299 # define NEVER(X)       (0)
300 #else
301 # define ALWAYS(X)      (X)
302 # define NEVER(X)       (X)
303 #endif
304
305 /*
306 ** The macro unlikely() is a hint that surrounds a boolean
307 ** expression that is usually false.  Macro likely() surrounds
308 ** a boolean expression that is usually true.  GCC is able to
309 ** use these hints to generate better code, sometimes.
310 */
311 #if defined(__GNUC__) && 0
312 # define likely(X)    __builtin_expect((X),1)
313 # define unlikely(X)  __builtin_expect((X),0)
314 #else
315 # define likely(X)    !!(X)
316 # define unlikely(X)  !!(X)
317 #endif
318
319 /*
320  * This macro is used to "hide" some ugliness in casting an int
321  * value to a ptr value under the MSVC 64-bit compiler.   Casting
322  * non 64-bit values to ptr types results in a "hard" error with 
323  * the MSVC 64-bit compiler which this attempts to avoid.  
324  *
325  * A simple compiler pragma or casting sequence could not be found
326  * to correct this in all situations, so this macro was introduced.
327  *
328  * It could be argued that the intptr_t type could be used in this
329  * case, but that type is not available on all compilers, or 
330  * requires the #include of specific headers which differs between
331  * platforms.
332  */
333 #define SQLITE_INT_TO_PTR(X)   ((void*)&((char*)0)[X])
334 #define SQLITE_PTR_TO_INT(X)   ((int)(((char*)X)-(char*)0))
335
336 /*
337 ** These #defines should enable >2GB file support on Posix if the
338 ** underlying operating system supports it.  If the OS lacks
339 ** large file support, or if the OS is windows, these should be no-ops.
340 **
341 ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
342 ** system #includes.  Hence, this block of code must be the very first
343 ** code in all source files.
344 **
345 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
346 ** on the compiler command line.  This is necessary if you are compiling
347 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
348 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
349 ** without this option, LFS is enable.  But LFS does not exist in the kernel
350 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
351 ** portability you should omit LFS.
352 **
353 ** Similar is true for MacOS.  LFS is only supported on MacOS 9 and later.
354 */
355 #ifndef SQLITE_DISABLE_LFS
356 # define _LARGE_FILE       1
357 # ifndef _FILE_OFFSET_BITS
358 #   define _FILE_OFFSET_BITS 64
359 # endif
360 # define _LARGEFILE_SOURCE 1
361 #endif
362
363
364 /*
365 ** The SQLITE_THREADSAFE macro must be defined as either 0 or 1.
366 ** Older versions of SQLite used an optional THREADSAFE macro.
367 ** We support that for legacy
368 */
369 #if !defined(SQLITE_THREADSAFE)
370 #if defined(THREADSAFE)
371 # define SQLITE_THREADSAFE THREADSAFE
372 #else
373 # define SQLITE_THREADSAFE 1
374 #endif
375 #endif
376
377 /*
378 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
379 ** It determines whether or not the features related to 
380 ** SQLITE_CONFIG_MEMSTATUS are availabe by default or not. This value can
381 ** be overridden at runtime using the sqlite3_config() API.
382 */
383 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
384 # define SQLITE_DEFAULT_MEMSTATUS 1
385 #endif
386
387 /*
388 ** Exactly one of the following macros must be defined in order to
389 ** specify which memory allocation subsystem to use.
390 **
391 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
392 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
393 **     SQLITE_MEMORY_SIZE            // internal allocator #1
394 **     SQLITE_MMAP_HEAP_SIZE         // internal mmap() allocator
395 **     SQLITE_POW2_MEMORY_SIZE       // internal power-of-two allocator
396 **
397 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
398 ** the default.
399 */
400 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
401     defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
402     defined(SQLITE_POW2_MEMORY_SIZE)>1
403 # error "At most one of the following compile-time configuration options\
404  is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG, SQLITE_MEMORY_SIZE,\
405  SQLITE_MMAP_HEAP_SIZE, SQLITE_POW2_MEMORY_SIZE"
406 #endif
407 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
408     defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
409     defined(SQLITE_POW2_MEMORY_SIZE)==0
410 # define SQLITE_SYSTEM_MALLOC 1
411 #endif
412
413 /*
414 ** If SQLITE_MALLOC_SOFT_LIMIT is defined, then try to keep the
415 ** sizes of memory allocations below this value where possible.
416 */
417 #if defined(SQLITE_POW2_MEMORY_SIZE) && !defined(SQLITE_MALLOC_SOFT_LIMIT)
418 # define SQLITE_MALLOC_SOFT_LIMIT 1024
419 #endif
420
421 /*
422 ** We need to define _XOPEN_SOURCE as follows in order to enable
423 ** recursive mutexes on most unix systems.  But Mac OS X is different.
424 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
425 ** so it is omitted there.  See ticket #2673.
426 **
427 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
428 ** implemented on some systems.  So we avoid defining it at all
429 ** if it is already defined or if it is unneeded because we are
430 ** not doing a threadsafe build.  Ticket #2681.
431 **
432 ** See also ticket #2741.
433 */
434 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
435 #  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
436 #endif
437
438 /*
439 ** The TCL headers are only needed when compiling the TCL bindings.
440 */
441 #if defined(SQLITE_TCL) || defined(TCLSH)
442 # include <tcl.h>
443 #endif
444
445 /*
446 ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
447 ** Setting NDEBUG makes the code smaller and run faster.  So the following
448 ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
449 ** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
450 ** feature.
451 */
452 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
453 # define NDEBUG 1
454 #endif
455
456 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
457 /************** Begin file sqlite3.h *****************************************/
458 /*
459 ** 2001 September 15
460 **
461 ** The author disclaims copyright to this source code.  In place of
462 ** a legal notice, here is a blessing:
463 **
464 **    May you do good and not evil.
465 **    May you find forgiveness for yourself and forgive others.
466 **    May you share freely, never taking more than you give.
467 **
468 *************************************************************************
469 ** This header file defines the interface that the SQLite library
470 ** presents to client programs.  If a C-function, structure, datatype,
471 ** or constant definition does not appear in this file, then it is
472 ** not a published API of SQLite, is subject to change without
473 ** notice, and should not be referenced by programs that use SQLite.
474 **
475 ** Some of the definitions that are in this file are marked as
476 ** "experimental".  Experimental interfaces are normally new
477 ** features recently added to SQLite.  We do not anticipate changes
478 ** to experimental interfaces but reserve to make minor changes if
479 ** experience from use "in the wild" suggest such changes are prudent.
480 **
481 ** The official C-language API documentation for SQLite is derived
482 ** from comments in this file.  This file is the authoritative source
483 ** on how SQLite interfaces are suppose to operate.
484 **
485 ** The name of this file under configuration management is "sqlite.h.in".
486 ** The makefile makes some minor changes to this file (such as inserting
487 ** the version number) and changes its name to "sqlite3.h" as
488 ** part of the build process.
489 **
490 ** @(#) $Id: sqlite.h.in,v 1.398 2008/09/10 13:09:24 drh Exp $
491 */
492 #ifndef _SQLITE3_H_
493 #define _SQLITE3_H_
494 #include <stdarg.h>     /* Needed for the definition of va_list */
495
496 /*
497 ** Make sure we can call this stuff from C++.
498 */
499 #if 0
500 extern "C" {
501 #endif
502
503
504 /*
505 ** Add the ability to override 'extern'
506 */
507 #ifndef SQLITE_EXTERN
508 # define SQLITE_EXTERN extern
509 #endif
510
511 /*
512 ** Add the ability to mark interfaces as deprecated.
513 */
514 #if (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
515   /* GCC added the deprecated attribute in version 3.1 */
516   #define SQLITE_DEPRECATED __attribute__ ((deprecated))
517 #elif defined(_MSC_VER) && (_MSC_VER>1200) 
518   #define SQLITE_DEPRECATED __declspec(deprecated)
519 #else
520   #define SQLITE_DEPRECATED
521 #endif
522
523 /*
524 ** Add the ability to mark interfaces as experimental.
525 */
526 #if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
527   /* I can confirm that it does not work on version 4.1.0... */
528   /* First appears in GCC docs for version 4.3.0 */
529   #define SQLITE_EXPERIMENTAL __attribute__ ((warning ("is experimental")))
530 #elif defined(_MSC_VER) && (_MSC_VER>1200) 
531   #define SQLITE_EXPERIMENTAL __declspec(deprecated("was declared experimental"))
532 #else
533   #define SQLITE_EXPERIMENTAL
534 #endif
535
536 /*
537 ** Ensure these symbols were not defined by some previous header file.
538 */
539 #ifdef SQLITE_VERSION
540 # undef SQLITE_VERSION
541 #endif
542 #ifdef SQLITE_VERSION_NUMBER
543 # undef SQLITE_VERSION_NUMBER
544 #endif
545
546 /*
547 ** CAPI3REF: Compile-Time Library Version Numbers {H10010} <S60100>
548 **
549 ** The SQLITE_VERSION and SQLITE_VERSION_NUMBER #defines in
550 ** the sqlite3.h file specify the version of SQLite with which
551 ** that header file is associated.
552 **
553 ** The "version" of SQLite is a string of the form "X.Y.Z".
554 ** The phrase "alpha" or "beta" might be appended after the Z.
555 ** The X value is major version number always 3 in SQLite3.
556 ** The X value only changes when backwards compatibility is
557 ** broken and we intend to never break backwards compatibility.
558 ** The Y value is the minor version number and only changes when
559 ** there are major feature enhancements that are forwards compatible
560 ** but not backwards compatible.
561 ** The Z value is the release number and is incremented with
562 ** each release but resets back to 0 whenever Y is incremented.
563 **
564 ** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()].
565 **
566 ** INVARIANTS:
567 **
568 ** {H10011} The SQLITE_VERSION #define in the sqlite3.h header file shall
569 **          evaluate to a string literal that is the SQLite version
570 **          with which the header file is associated.
571 **
572 ** {H10014} The SQLITE_VERSION_NUMBER #define shall resolve to an integer
573 **          with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z
574 **          are the major version, minor version, and release number.
575 */
576 #define SQLITE_VERSION         "3.6.3"
577 #define SQLITE_VERSION_NUMBER  3006003
578
579 /*
580 ** CAPI3REF: Run-Time Library Version Numbers {H10020} <S60100>
581 ** KEYWORDS: sqlite3_version
582 **
583 ** These features provide the same information as the [SQLITE_VERSION]
584 ** and [SQLITE_VERSION_NUMBER] #defines in the header, but are associated
585 ** with the library instead of the header file.  Cautious programmers might
586 ** include a check in their application to verify that
587 ** sqlite3_libversion_number() always returns the value
588 ** [SQLITE_VERSION_NUMBER].
589 **
590 ** The sqlite3_libversion() function returns the same information as is
591 ** in the sqlite3_version[] string constant.  The function is provided
592 ** for use in DLLs since DLL users usually do not have direct access to string
593 ** constants within the DLL.
594 **
595 ** INVARIANTS:
596 **
597 ** {H10021} The [sqlite3_libversion_number()] interface shall return
598 **          an integer equal to [SQLITE_VERSION_NUMBER].
599 **
600 ** {H10022} The [sqlite3_version] string constant shall contain
601 **          the text of the [SQLITE_VERSION] string.
602 **
603 ** {H10023} The [sqlite3_libversion()] function shall return
604 **          a pointer to the [sqlite3_version] string constant.
605 */
606 SQLITE_API const char sqlite3_version[];
607 SQLITE_API const char *sqlite3_libversion(void);
608 SQLITE_API int sqlite3_libversion_number(void);
609
610 /*
611 ** CAPI3REF: Test To See If The Library Is Threadsafe {H10100} <S60100>
612 **
613 ** SQLite can be compiled with or without mutexes.  When
614 ** the [SQLITE_THREADSAFE] C preprocessor macro 1 or 2, mutexes
615 ** are enabled and SQLite is threadsafe.  When the
616 ** [SQLITE_THREADSAFE] macro is 0, 
617 ** the mutexes are omitted.  Without the mutexes, it is not safe
618 ** to use SQLite concurrently from more than one thread.
619 **
620 ** Enabling mutexes incurs a measurable performance penalty.
621 ** So if speed is of utmost importance, it makes sense to disable
622 ** the mutexes.  But for maximum safety, mutexes should be enabled.
623 ** The default behavior is for mutexes to be enabled.
624 **
625 ** This interface can be used by a program to make sure that the
626 ** version of SQLite that it is linking against was compiled with
627 ** the desired setting of the [SQLITE_THREADSAFE] macro.
628 **
629 ** This interface only reports on the compile-time mutex setting
630 ** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
631 ** SQLITE_THREADSAFE=1 then mutexes are enabled by default but
632 ** can be fully or partially disabled using a call to [sqlite3_config()]
633 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
634 ** or [SQLITE_CONFIG_MUTEX].  The return value of this function shows
635 ** only the default compile-time setting, not any run-time changes
636 ** to that setting.
637 **
638 ** See the [threading mode] documentation for additional information.
639 **
640 ** INVARIANTS:
641 **
642 ** {H10101} The [sqlite3_threadsafe()] function shall return nonzero if
643 **          and only if
644 **          SQLite was compiled with the its mutexes enabled by default.
645 **
646 ** {H10102} The value returned by the [sqlite3_threadsafe()] function
647 **          shall not change when mutex setting are modified at
648 **          runtime using the [sqlite3_config()] interface and 
649 **          especially the [SQLITE_CONFIG_SINGLETHREAD],
650 **          [SQLITE_CONFIG_MULTITHREAD], [SQLITE_CONFIG_SERIALIZED],
651 **          and [SQLITE_CONFIG_MUTEX] verbs.
652 */
653 SQLITE_API int sqlite3_threadsafe(void);
654
655 /*
656 ** CAPI3REF: Database Connection Handle {H12000} <S40200>
657 ** KEYWORDS: {database connection} {database connections}
658 **
659 ** Each open SQLite database is represented by a pointer to an instance of
660 ** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
661 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
662 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
663 ** is its destructor.  There are many other interfaces (such as
664 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
665 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
666 ** sqlite3 object.
667 */
668 typedef struct sqlite3 sqlite3;
669
670 /*
671 ** CAPI3REF: 64-Bit Integer Types {H10200} <S10110>
672 ** KEYWORDS: sqlite_int64 sqlite_uint64
673 **
674 ** Because there is no cross-platform way to specify 64-bit integer types
675 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
676 **
677 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
678 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
679 ** compatibility only.
680 **
681 ** INVARIANTS:
682 **
683 ** {H10201} The [sqlite_int64] and [sqlite3_int64] type shall specify
684 **          a 64-bit signed integer.
685 **
686 ** {H10202} The [sqlite_uint64] and [sqlite3_uint64] type shall specify
687 **          a 64-bit unsigned integer.
688 */
689 #ifdef SQLITE_INT64_TYPE
690   typedef SQLITE_INT64_TYPE sqlite_int64;
691   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
692 #elif defined(_MSC_VER) || defined(__BORLANDC__)
693   typedef __int64 sqlite_int64;
694   typedef unsigned __int64 sqlite_uint64;
695 #else
696   typedef long long int sqlite_int64;
697   typedef unsigned long long int sqlite_uint64;
698 #endif
699 typedef sqlite_int64 sqlite3_int64;
700 typedef sqlite_uint64 sqlite3_uint64;
701
702 /*
703 ** If compiling for a processor that lacks floating point support,
704 ** substitute integer for floating-point.
705 */
706 #ifdef SQLITE_OMIT_FLOATING_POINT
707 # define double sqlite3_int64
708 #endif
709
710 /*
711 ** CAPI3REF: Closing A Database Connection {H12010} <S30100><S40200>
712 **
713 ** This routine is the destructor for the [sqlite3] object.
714 **
715 ** Applications should [sqlite3_finalize | finalize] all [prepared statements]
716 ** and [sqlite3_blob_close | close] all [BLOB handles] associated with
717 ** the [sqlite3] object prior to attempting to close the object.
718 ** The [sqlite3_next_stmt()] interface can be used to locate all
719 ** [prepared statements] associated with a [database connection] if desired.
720 ** Typical code might look like this:
721 **
722 ** <blockquote><pre>
723 ** sqlite3_stmt *pStmt;
724 ** while( (pStmt = sqlite3_next_stmt(db, 0))!=0 ){
725 ** &nbsp;   sqlite3_finalize(pStmt);
726 ** }
727 ** </pre></blockquote>
728 **
729 ** If [sqlite3_close()] is invoked while a transaction is open,
730 ** the transaction is automatically rolled back.
731 **
732 ** INVARIANTS:
733 **
734 ** {H12011} A successful call to [sqlite3_close(C)] shall destroy the
735 **          [database connection] object C.
736 **
737 ** {H12012} A successful call to [sqlite3_close(C)] shall return SQLITE_OK.
738 **
739 ** {H12013} A successful call to [sqlite3_close(C)] shall release all
740 **          memory and system resources associated with [database connection]
741 **          C.
742 **
743 ** {H12014} A call to [sqlite3_close(C)] on a [database connection] C that
744 **          has one or more open [prepared statements] shall fail with
745 **          an [SQLITE_BUSY] error code.
746 **
747 ** {H12015} A call to [sqlite3_close(C)] where C is a NULL pointer shall
748 **          return SQLITE_OK.
749 **
750 ** {H12019} When [sqlite3_close(C)] is invoked on a [database connection] C
751 **          that has a pending transaction, the transaction shall be
752 **          rolled back.
753 **
754 ** ASSUMPTIONS:
755 **
756 ** {A12016} The C parameter to [sqlite3_close(C)] must be either a NULL
757 **          pointer or an [sqlite3] object pointer obtained
758 **          from [sqlite3_open()], [sqlite3_open16()], or
759 **          [sqlite3_open_v2()], and not previously closed.
760 */
761 SQLITE_API int sqlite3_close(sqlite3 *);
762
763 /*
764 ** The type for a callback function.
765 ** This is legacy and deprecated.  It is included for historical
766 ** compatibility and is not documented.
767 */
768 typedef int (*sqlite3_callback)(void*,int,char**, char**);
769
770 /*
771 ** CAPI3REF: One-Step Query Execution Interface {H12100} <S10000>
772 **
773 ** The sqlite3_exec() interface is a convenient way of running one or more
774 ** SQL statements without having to write a lot of C code.  The UTF-8 encoded
775 ** SQL statements are passed in as the second parameter to sqlite3_exec().
776 ** The statements are evaluated one by one until either an error or
777 ** an interrupt is encountered, or until they are all done.  The 3rd parameter
778 ** is an optional callback that is invoked once for each row of any query
779 ** results produced by the SQL statements.  The 5th parameter tells where
780 ** to write any error messages.
781 **
782 ** The error message passed back through the 5th parameter is held
783 ** in memory obtained from [sqlite3_malloc()].  To avoid a memory leak,
784 ** the calling application should call [sqlite3_free()] on any error
785 ** message returned through the 5th parameter when it has finished using
786 ** the error message.
787 **
788 ** If the SQL statement in the 2nd parameter is NULL or an empty string
789 ** or a string containing only whitespace and comments, then no SQL
790 ** statements are evaluated and the database is not changed.
791 **
792 ** The sqlite3_exec() interface is implemented in terms of
793 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()].
794 ** The sqlite3_exec() routine does nothing to the database that cannot be done
795 ** by [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()].
796 **
797 ** INVARIANTS:
798 **
799 ** {H12101} A successful invocation of [sqlite3_exec(D,S,C,A,E)]
800 **          shall sequentially evaluate all of the UTF-8 encoded,
801 **          semicolon-separated SQL statements in the zero-terminated
802 **          string S within the context of the [database connection] D.
803 **
804 ** {H12102} If the S parameter to [sqlite3_exec(D,S,C,A,E)] is NULL then
805 **          the actions of the interface shall be the same as if the
806 **          S parameter were an empty string.
807 **
808 ** {H12104} The return value of [sqlite3_exec()] shall be [SQLITE_OK] if all
809 **          SQL statements run successfully and to completion.
810 **
811 ** {H12105} The return value of [sqlite3_exec()] shall be an appropriate
812 **          non-zero [error code] if any SQL statement fails.
813 **
814 ** {H12107} If one or more of the SQL statements handed to [sqlite3_exec()]
815 **          return results and the 3rd parameter is not NULL, then
816 **          the callback function specified by the 3rd parameter shall be
817 **          invoked once for each row of result.
818 **
819 ** {H12110} If the callback returns a non-zero value then [sqlite3_exec()]
820 **          shall abort the SQL statement it is currently evaluating,
821 **          skip all subsequent SQL statements, and return [SQLITE_ABORT].
822 **
823 ** {H12113} The [sqlite3_exec()] routine shall pass its 4th parameter through
824 **          as the 1st parameter of the callback.
825 **
826 ** {H12116} The [sqlite3_exec()] routine shall set the 2nd parameter of its
827 **          callback to be the number of columns in the current row of
828 **          result.
829 **
830 ** {H12119} The [sqlite3_exec()] routine shall set the 3rd parameter of its
831 **          callback to be an array of pointers to strings holding the
832 **          values for each column in the current result set row as
833 **          obtained from [sqlite3_column_text()].
834 **
835 ** {H12122} The [sqlite3_exec()] routine shall set the 4th parameter of its
836 **          callback to be an array of pointers to strings holding the
837 **          names of result columns as obtained from [sqlite3_column_name()].
838 **
839 ** {H12125} If the 3rd parameter to [sqlite3_exec()] is NULL then
840 **          [sqlite3_exec()] shall silently discard query results.
841 **
842 ** {H12131} If an error occurs while parsing or evaluating any of the SQL
843 **          statements in the S parameter of [sqlite3_exec(D,S,C,A,E)] and if
844 **          the E parameter is not NULL, then [sqlite3_exec()] shall store
845 **          in *E an appropriate error message written into memory obtained
846 **          from [sqlite3_malloc()].
847 **
848 ** {H12134} The [sqlite3_exec(D,S,C,A,E)] routine shall set the value of
849 **          *E to NULL if E is not NULL and there are no errors.
850 **
851 ** {H12137} The [sqlite3_exec(D,S,C,A,E)] function shall set the [error code]
852 **          and message accessible via [sqlite3_errcode()],
853 **          [sqlite3_errmsg()], and [sqlite3_errmsg16()].
854 **
855 ** {H12138} If the S parameter to [sqlite3_exec(D,S,C,A,E)] is NULL or an
856 **          empty string or contains nothing other than whitespace, comments,
857 **          and/or semicolons, then results of [sqlite3_errcode()],
858 **          [sqlite3_errmsg()], and [sqlite3_errmsg16()]
859 **          shall reset to indicate no errors.
860 **
861 ** ASSUMPTIONS:
862 **
863 ** {A12141} The first parameter to [sqlite3_exec()] must be an valid and open
864 **          [database connection].
865 **
866 ** {A12142} The database connection must not be closed while
867 **          [sqlite3_exec()] is running.
868 **
869 ** {A12143} The calling function should use [sqlite3_free()] to free
870 **          the memory that *errmsg is left pointing at once the error
871 **          message is no longer needed.
872 **
873 ** {A12145} The SQL statement text in the 2nd parameter to [sqlite3_exec()]
874 **          must remain unchanged while [sqlite3_exec()] is running.
875 */
876 SQLITE_API int sqlite3_exec(
877   sqlite3*,                                  /* An open database */
878   const char *sql,                           /* SQL to be evaluated */
879   int (*callback)(void*,int,char**,char**),  /* Callback function */
880   void *,                                    /* 1st argument to callback */
881   char **errmsg                              /* Error msg written here */
882 );
883
884 /*
885 ** CAPI3REF: Result Codes {H10210} <S10700>
886 ** KEYWORDS: SQLITE_OK {error code} {error codes}
887 ** KEYWORDS: {result code} {result codes}
888 **
889 ** Many SQLite functions return an integer result code from the set shown
890 ** here in order to indicates success or failure.
891 **
892 ** New error codes may be added in future versions of SQLite.
893 **
894 ** See also: [SQLITE_IOERR_READ | extended result codes]
895 */
896 #define SQLITE_OK           0   /* Successful result */
897 /* beginning-of-error-codes */
898 #define SQLITE_ERROR        1   /* SQL error or missing database */
899 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
900 #define SQLITE_PERM         3   /* Access permission denied */
901 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
902 #define SQLITE_BUSY         5   /* The database file is locked */
903 #define SQLITE_LOCKED       6   /* A table in the database is locked */
904 #define SQLITE_NOMEM        7   /* A malloc() failed */
905 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
906 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
907 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
908 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
909 #define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
910 #define SQLITE_FULL        13   /* Insertion failed because database is full */
911 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
912 #define SQLITE_PROTOCOL    15   /* NOT USED. Database lock protocol error */
913 #define SQLITE_EMPTY       16   /* Database is empty */
914 #define SQLITE_SCHEMA      17   /* The database schema changed */
915 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
916 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
917 #define SQLITE_MISMATCH    20   /* Data type mismatch */
918 #define SQLITE_MISUSE      21   /* Library used incorrectly */
919 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
920 #define SQLITE_AUTH        23   /* Authorization denied */
921 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
922 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
923 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
924 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
925 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
926 /* end-of-error-codes */
927
928 /*
929 ** CAPI3REF: Extended Result Codes {H10220} <S10700>
930 ** KEYWORDS: {extended error code} {extended error codes}
931 ** KEYWORDS: {extended result code} {extended result codes}
932 **
933 ** In its default configuration, SQLite API routines return one of 26 integer
934 ** [SQLITE_OK | result codes].  However, experience has shown that many of
935 ** these result codes are too coarse-grained.  They do not provide as
936 ** much information about problems as programmers might like.  In an effort to
937 ** address this, newer versions of SQLite (version 3.3.8 and later) include
938 ** support for additional result codes that provide more detailed information
939 ** about errors. The extended result codes are enabled or disabled
940 ** on a per database connection basis using the
941 ** [sqlite3_extended_result_codes()] API.
942 **
943 ** Some of the available extended result codes are listed here.
944 ** One may expect the number of extended result codes will be expand
945 ** over time.  Software that uses extended result codes should expect
946 ** to see new result codes in future releases of SQLite.
947 **
948 ** The SQLITE_OK result code will never be extended.  It will always
949 ** be exactly zero.
950 **
951 ** INVARIANTS:
952 **
953 ** {H10223} The symbolic name for an extended result code shall contains
954 **          a related primary result code as a prefix.
955 **
956 ** {H10224} Primary result code names shall contain a single "_" character.
957 **
958 ** {H10225} Extended result code names shall contain two or more "_" characters.
959 **
960 ** {H10226} The numeric value of an extended result code shall contain the
961 **          numeric value of its corresponding primary result code in
962 **          its least significant 8 bits.
963 */
964 #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
965 #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
966 #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
967 #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
968 #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
969 #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
970 #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
971 #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
972 #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
973 #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
974 #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
975 #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
976 #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
977 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
978 #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
979
980 /*
981 ** CAPI3REF: Flags For File Open Operations {H10230} <H11120> <H12700>
982 **
983 ** These bit values are intended for use in the
984 ** 3rd parameter to the [sqlite3_open_v2()] interface and
985 ** in the 4th parameter to the xOpen method of the
986 ** [sqlite3_vfs] object.
987 */
988 #define SQLITE_OPEN_READONLY         0x00000001
989 #define SQLITE_OPEN_READWRITE        0x00000002
990 #define SQLITE_OPEN_CREATE           0x00000004
991 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008
992 #define SQLITE_OPEN_EXCLUSIVE        0x00000010
993 #define SQLITE_OPEN_MAIN_DB          0x00000100
994 #define SQLITE_OPEN_TEMP_DB          0x00000200
995 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400
996 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800
997 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000
998 #define SQLITE_OPEN_SUBJOURNAL       0x00002000
999 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000
1000 #define SQLITE_OPEN_NOMUTEX          0x00008000
1001 #define SQLITE_OPEN_FULLMUTEX        0x00010000
1002
1003 /*
1004 ** CAPI3REF: Device Characteristics {H10240} <H11120>
1005 **
1006 ** The xDeviceCapabilities method of the [sqlite3_io_methods]
1007 ** object returns an integer which is a vector of the these
1008 ** bit values expressing I/O characteristics of the mass storage
1009 ** device that holds the file that the [sqlite3_io_methods]
1010 ** refers to.
1011 **
1012 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1013 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1014 ** mean that writes of blocks that are nnn bytes in size and
1015 ** are aligned to an address which is an integer multiple of
1016 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1017 ** that when data is appended to a file, the data is appended
1018 ** first then the size of the file is extended, never the other
1019 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1020 ** information is written to disk in the same order as calls
1021 ** to xWrite().
1022 */
1023 #define SQLITE_IOCAP_ATOMIC          0x00000001
1024 #define SQLITE_IOCAP_ATOMIC512       0x00000002
1025 #define SQLITE_IOCAP_ATOMIC1K        0x00000004
1026 #define SQLITE_IOCAP_ATOMIC2K        0x00000008
1027 #define SQLITE_IOCAP_ATOMIC4K        0x00000010
1028 #define SQLITE_IOCAP_ATOMIC8K        0x00000020
1029 #define SQLITE_IOCAP_ATOMIC16K       0x00000040
1030 #define SQLITE_IOCAP_ATOMIC32K       0x00000080
1031 #define SQLITE_IOCAP_ATOMIC64K       0x00000100
1032 #define SQLITE_IOCAP_SAFE_APPEND     0x00000200
1033 #define SQLITE_IOCAP_SEQUENTIAL      0x00000400
1034
1035 /*
1036 ** CAPI3REF: File Locking Levels {H10250} <H11120> <H11310>
1037 **
1038 ** SQLite uses one of these integer values as the second
1039 ** argument to calls it makes to the xLock() and xUnlock() methods
1040 ** of an [sqlite3_io_methods] object.
1041 */
1042 #define SQLITE_LOCK_NONE          0
1043 #define SQLITE_LOCK_SHARED        1
1044 #define SQLITE_LOCK_RESERVED      2
1045 #define SQLITE_LOCK_PENDING       3
1046 #define SQLITE_LOCK_EXCLUSIVE     4
1047
1048 /*
1049 ** CAPI3REF: Synchronization Type Flags {H10260} <H11120>
1050 **
1051 ** When SQLite invokes the xSync() method of an
1052 ** [sqlite3_io_methods] object it uses a combination of
1053 ** these integer values as the second argument.
1054 **
1055 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1056 ** sync operation only needs to flush data to mass storage.  Inode
1057 ** information need not be flushed. The SQLITE_SYNC_NORMAL flag means
1058 ** to use normal fsync() semantics. The SQLITE_SYNC_FULL flag means
1059 ** to use Mac OS-X style fullsync instead of fsync().
1060 */
1061 #define SQLITE_SYNC_NORMAL        0x00002
1062 #define SQLITE_SYNC_FULL          0x00003
1063 #define SQLITE_SYNC_DATAONLY      0x00010
1064
1065 /*
1066 ** CAPI3REF: OS Interface Open File Handle {H11110} <S20110>
1067 **
1068 ** An [sqlite3_file] object represents an open file in the OS
1069 ** interface layer.  Individual OS interface implementations will
1070 ** want to subclass this object by appending additional fields
1071 ** for their own use.  The pMethods entry is a pointer to an
1072 ** [sqlite3_io_methods] object that defines methods for performing
1073 ** I/O operations on the open file.
1074 */
1075 typedef struct sqlite3_file sqlite3_file;
1076 struct sqlite3_file {
1077   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1078 };
1079
1080 /*
1081 ** CAPI3REF: OS Interface File Virtual Methods Object {H11120} <S20110>
1082 **
1083 ** Every file opened by the [sqlite3_vfs] xOpen method populates an
1084 ** [sqlite3_file] object (or, more commonly, a subclass of the
1085 ** [sqlite3_file] object) with a pointer to an instance of this object.
1086 ** This object defines the methods used to perform various operations
1087 ** against the open file represented by the [sqlite3_file] object.
1088 **
1089 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1090 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1091 ** The second choice is a Mac OS-X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1092 ** flag may be ORed in to indicate that only the data of the file
1093 ** and not its inode needs to be synced.
1094 **
1095 ** The integer values to xLock() and xUnlock() are one of
1096 ** <ul>
1097 ** <li> [SQLITE_LOCK_NONE],
1098 ** <li> [SQLITE_LOCK_SHARED],
1099 ** <li> [SQLITE_LOCK_RESERVED],
1100 ** <li> [SQLITE_LOCK_PENDING], or
1101 ** <li> [SQLITE_LOCK_EXCLUSIVE].
1102 ** </ul>
1103 ** xLock() increases the lock. xUnlock() decreases the lock.
1104 ** The xCheckReservedLock() method checks whether any database connection,
1105 ** either in this process or in some other process, is holding a RESERVED,
1106 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
1107 ** if such a lock exists and false otherwise.
1108 **
1109 ** The xFileControl() method is a generic interface that allows custom
1110 ** VFS implementations to directly control an open file using the
1111 ** [sqlite3_file_control()] interface.  The second "op" argument is an
1112 ** integer opcode.  The third argument is a generic pointer intended to
1113 ** point to a structure that may contain arguments or space in which to
1114 ** write return values.  Potential uses for xFileControl() might be
1115 ** functions to enable blocking locks with timeouts, to change the
1116 ** locking strategy (for example to use dot-file locks), to inquire
1117 ** about the status of a lock, or to break stale locks.  The SQLite
1118 ** core reserves all opcodes less than 100 for its own use.
1119 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1120 ** Applications that define a custom xFileControl method should use opcodes
1121 ** greater than 100 to avoid conflicts.
1122 **
1123 ** The xSectorSize() method returns the sector size of the
1124 ** device that underlies the file.  The sector size is the
1125 ** minimum write that can be performed without disturbing
1126 ** other bytes in the file.  The xDeviceCharacteristics()
1127 ** method returns a bit vector describing behaviors of the
1128 ** underlying device:
1129 **
1130 ** <ul>
1131 ** <li> [SQLITE_IOCAP_ATOMIC]
1132 ** <li> [SQLITE_IOCAP_ATOMIC512]
1133 ** <li> [SQLITE_IOCAP_ATOMIC1K]
1134 ** <li> [SQLITE_IOCAP_ATOMIC2K]
1135 ** <li> [SQLITE_IOCAP_ATOMIC4K]
1136 ** <li> [SQLITE_IOCAP_ATOMIC8K]
1137 ** <li> [SQLITE_IOCAP_ATOMIC16K]
1138 ** <li> [SQLITE_IOCAP_ATOMIC32K]
1139 ** <li> [SQLITE_IOCAP_ATOMIC64K]
1140 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
1141 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
1142 ** </ul>
1143 **
1144 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1145 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1146 ** mean that writes of blocks that are nnn bytes in size and
1147 ** are aligned to an address which is an integer multiple of
1148 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1149 ** that when data is appended to a file, the data is appended
1150 ** first then the size of the file is extended, never the other
1151 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1152 ** information is written to disk in the same order as calls
1153 ** to xWrite().
1154 */
1155 typedef struct sqlite3_io_methods sqlite3_io_methods;
1156 struct sqlite3_io_methods {
1157   int iVersion;
1158   int (*xClose)(sqlite3_file*);
1159   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1160   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1161   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1162   int (*xSync)(sqlite3_file*, int flags);
1163   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1164   int (*xLock)(sqlite3_file*, int);
1165   int (*xUnlock)(sqlite3_file*, int);
1166   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1167   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1168   int (*xSectorSize)(sqlite3_file*);
1169   int (*xDeviceCharacteristics)(sqlite3_file*);
1170   /* Additional methods may be added in future releases */
1171 };
1172
1173 /*
1174 ** CAPI3REF: Standard File Control Opcodes {H11310} <S30800>
1175 **
1176 ** These integer constants are opcodes for the xFileControl method
1177 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1178 ** interface.
1179 **
1180 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1181 ** opcode causes the xFileControl method to write the current state of
1182 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1183 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1184 ** into an integer that the pArg argument points to. This capability
1185 ** is used during testing and only needs to be supported when SQLITE_TEST
1186 ** is defined.
1187 */
1188 #define SQLITE_FCNTL_LOCKSTATE        1
1189
1190 /*
1191 ** CAPI3REF: Mutex Handle {H17110} <S20130>
1192 **
1193 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1194 ** abstract type for a mutex object.  The SQLite core never looks
1195 ** at the internal representation of an [sqlite3_mutex].  It only
1196 ** deals with pointers to the [sqlite3_mutex] object.
1197 **
1198 ** Mutexes are created using [sqlite3_mutex_alloc()].
1199 */
1200 typedef struct sqlite3_mutex sqlite3_mutex;
1201
1202 /*
1203 ** CAPI3REF: OS Interface Object {H11140} <S20100>
1204 **
1205 ** An instance of the sqlite3_vfs object defines the interface between
1206 ** the SQLite core and the underlying operating system.  The "vfs"
1207 ** in the name of the object stands for "virtual file system".
1208 **
1209 ** The value of the iVersion field is initially 1 but may be larger in
1210 ** future versions of SQLite.  Additional fields may be appended to this
1211 ** object when the iVersion value is increased.  Note that the structure
1212 ** of the sqlite3_vfs object changes in the transaction between
1213 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1214 ** modified.
1215 **
1216 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1217 ** structure used by this VFS.  mxPathname is the maximum length of
1218 ** a pathname in this VFS.
1219 **
1220 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1221 ** the pNext pointer.  The [sqlite3_vfs_register()]
1222 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1223 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1224 ** searches the list.  Neither the application code nor the VFS
1225 ** implementation should use the pNext pointer.
1226 **
1227 ** The pNext field is the only field in the sqlite3_vfs
1228 ** structure that SQLite will ever modify.  SQLite will only access
1229 ** or modify this field while holding a particular static mutex.
1230 ** The application should never modify anything within the sqlite3_vfs
1231 ** object once the object has been registered.
1232 **
1233 ** The zName field holds the name of the VFS module.  The name must
1234 ** be unique across all VFS modules.
1235 **
1236 ** {H11141} SQLite will guarantee that the zFilename parameter to xOpen
1237 ** is either a NULL pointer or string obtained
1238 ** from xFullPathname().  SQLite further guarantees that
1239 ** the string will be valid and unchanged until xClose() is
1240 ** called. {END}  Because of the previous sentense,
1241 ** the [sqlite3_file] can safely store a pointer to the
1242 ** filename if it needs to remember the filename for some reason.
1243 ** If the zFilename parameter is xOpen is a NULL pointer then xOpen
1244 ** must invite its own temporary name for the file.  Whenever the 
1245 ** xFilename parameter is NULL it will also be the case that the
1246 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1247 **
1248 ** {H11142} The flags argument to xOpen() includes all bits set in
1249 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1250 ** or [sqlite3_open16()] is used, then flags includes at least
1251 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. {END}
1252 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1253 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1254 **
1255 ** {H11143} SQLite will also add one of the following flags to the xOpen()
1256 ** call, depending on the object being opened:
1257 **
1258 ** <ul>
1259 ** <li>  [SQLITE_OPEN_MAIN_DB]
1260 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1261 ** <li>  [SQLITE_OPEN_TEMP_DB]
1262 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1263 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1264 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
1265 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1266 ** </ul> {END}
1267 **
1268 ** The file I/O implementation can use the object type flags to
1269 ** change the way it deals with files.  For example, an application
1270 ** that does not care about crash recovery or rollback might make
1271 ** the open of a journal file a no-op.  Writes to this journal would
1272 ** also be no-ops, and any attempt to read the journal would return
1273 ** SQLITE_IOERR.  Or the implementation might recognize that a database
1274 ** file will be doing page-aligned sector reads and writes in a random
1275 ** order and set up its I/O subsystem accordingly.
1276 **
1277 ** SQLite might also add one of the following flags to the xOpen method:
1278 **
1279 ** <ul>
1280 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1281 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1282 ** </ul>
1283 **
1284 ** {H11145} The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1285 ** deleted when it is closed.  {H11146} The [SQLITE_OPEN_DELETEONCLOSE]
1286 ** will be set for TEMP  databases, journals and for subjournals.
1287 **
1288 ** {H11147} The [SQLITE_OPEN_EXCLUSIVE] flag means the file should be opened
1289 ** for exclusive access.  This flag is set for all files except
1290 ** for the main database file.
1291 **
1292 ** {H11148} At least szOsFile bytes of memory are allocated by SQLite
1293 ** to hold the  [sqlite3_file] structure passed as the third
1294 ** argument to xOpen. {END}  The xOpen method does not have to
1295 ** allocate the structure; it should just fill it in.
1296 **
1297 ** {H11149} The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1298 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1299 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1300 ** to test whether a file is at least readable. {END}  The file can be a
1301 ** directory.
1302 **
1303 ** {H11150} SQLite will always allocate at least mxPathname+1 bytes for the
1304 ** output buffer xFullPathname. {H11151} The exact size of the output buffer
1305 ** is also passed as a parameter to both  methods. {END}  If the output buffer
1306 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1307 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1308 ** to prevent this by setting mxPathname to a sufficiently large value.
1309 **
1310 ** The xRandomness(), xSleep(), and xCurrentTime() interfaces
1311 ** are not strictly a part of the filesystem, but they are
1312 ** included in the VFS structure for completeness.
1313 ** The xRandomness() function attempts to return nBytes bytes
1314 ** of good-quality randomness into zOut.  The return value is
1315 ** the actual number of bytes of randomness obtained.
1316 ** The xSleep() method causes the calling thread to sleep for at
1317 ** least the number of microseconds given.  The xCurrentTime()
1318 ** method returns a Julian Day Number for the current date and time.
1319 */
1320 typedef struct sqlite3_vfs sqlite3_vfs;
1321 struct sqlite3_vfs {
1322   int iVersion;            /* Structure version number */
1323   int szOsFile;            /* Size of subclassed sqlite3_file */
1324   int mxPathname;          /* Maximum file pathname length */
1325   sqlite3_vfs *pNext;      /* Next registered VFS */
1326   const char *zName;       /* Name of this virtual file system */
1327   void *pAppData;          /* Pointer to application-specific data */
1328   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1329                int flags, int *pOutFlags);
1330   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1331   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1332   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1333   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1334   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1335   void *(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol);
1336   void (*xDlClose)(sqlite3_vfs*, void*);
1337   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1338   int (*xSleep)(sqlite3_vfs*, int microseconds);
1339   int (*xCurrentTime)(sqlite3_vfs*, double*);
1340   int (*xGetLastError)(sqlite3_vfs*, int, char *);
1341   /* New fields may be appended in figure versions.  The iVersion
1342   ** value will increment whenever this happens. */
1343 };
1344
1345 /*
1346 ** CAPI3REF: Flags for the xAccess VFS method {H11190} <H11140>
1347 **
1348 ** {H11191} These integer constants can be used as the third parameter to
1349 ** the xAccess method of an [sqlite3_vfs] object. {END}  They determine
1350 ** what kind of permissions the xAccess method is looking for.
1351 ** {H11192} With SQLITE_ACCESS_EXISTS, the xAccess method
1352 ** simply checks whether the file exists.
1353 ** {H11193} With SQLITE_ACCESS_READWRITE, the xAccess method
1354 ** checks whether the file is both readable and writable.
1355 ** {H11194} With SQLITE_ACCESS_READ, the xAccess method
1356 ** checks whether the file is readable.
1357 */
1358 #define SQLITE_ACCESS_EXISTS    0
1359 #define SQLITE_ACCESS_READWRITE 1
1360 #define SQLITE_ACCESS_READ      2
1361
1362 /*
1363 ** CAPI3REF: Initialize The SQLite Library {H10130} <S20000><S30100>
1364 **
1365 ** The sqlite3_initialize() routine initializes the
1366 ** SQLite library.  The sqlite3_shutdown() routine
1367 ** deallocates any resources that were allocated by sqlite3_initialize().
1368 **
1369 ** A call to sqlite3_initialize() is an "effective" call if it is
1370 ** the first time sqlite3_initialize() is invoked during the lifetime of
1371 ** the process, or if it is the first time sqlite3_initialize() is invoked
1372 ** following a call to sqlite3_shutdown().  Only an effective call
1373 ** of sqlite3_initialize() does any initialization.  All other calls
1374 ** are harmless no-ops.
1375 **
1376 ** Among other things, sqlite3_initialize() shall invoke
1377 ** sqlite3_os_init().  Similarly, sqlite3_shutdown()
1378 ** shall invoke sqlite3_os_end().
1379 **
1380 ** The sqlite3_initialize() routine returns SQLITE_OK on success.
1381 ** If for some reason, sqlite3_initialize() is unable to initialize
1382 ** the library (perhaps it is unable to allocate a needed resource such
1383 ** as a mutex) it returns an [error code] other than SQLITE_OK.
1384 **
1385 ** The sqlite3_initialize() routine is called internally by many other
1386 ** SQLite interfaces so that an application usually does not need to
1387 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1388 ** calls sqlite3_initialize() so the SQLite library will be automatically
1389 ** initialized when [sqlite3_open()] is called if it has not be initialized
1390 ** already.  However, if SQLite is compiled with the SQLITE_OMIT_AUTOINIT
1391 ** compile-time option, then the automatic calls to sqlite3_initialize()
1392 ** are omitted and the application must call sqlite3_initialize() directly
1393 ** prior to using any other SQLite interface.  For maximum portability,
1394 ** it is recommended that applications always invoke sqlite3_initialize()
1395 ** directly prior to using any other SQLite interface.  Future releases
1396 ** of SQLite may require this.  In other words, the behavior exhibited
1397 ** when SQLite is compiled with SQLITE_OMIT_AUTOINIT might become the
1398 ** default behavior in some future release of SQLite.
1399 **
1400 ** The sqlite3_os_init() routine does operating-system specific
1401 ** initialization of the SQLite library.  The sqlite3_os_end()
1402 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
1403 ** performed by these routines include allocation or deallocation
1404 ** of static resources, initialization of global variables,
1405 ** setting up a default [sqlite3_vfs] module, or setting up
1406 ** a default configuration using [sqlite3_config()].
1407 **
1408 ** The application should never invoke either sqlite3_os_init()
1409 ** or sqlite3_os_end() directly.  The application should only invoke
1410 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1411 ** interface is called automatically by sqlite3_initialize() and
1412 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1413 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1414 ** are built into SQLite when it is compiled for unix, windows, or os/2.
1415 ** When built for other platforms (using the SQLITE_OS_OTHER=1 compile-time
1416 ** option) the application must supply a suitable implementation for
1417 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1418 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1419 ** must return SQLITE_OK on success and some other [error code] upon
1420 ** failure.
1421 */
1422 SQLITE_API int sqlite3_initialize(void);
1423 SQLITE_API int sqlite3_shutdown(void);
1424 SQLITE_API int sqlite3_os_init(void);
1425 SQLITE_API int sqlite3_os_end(void);
1426
1427 /*
1428 ** CAPI3REF: Configuring The SQLite Library {H10145} <S20000><S30200>
1429 ** EXPERIMENTAL
1430 **
1431 ** The sqlite3_config() interface is used to make global configuration
1432 ** changes to SQLite in order to tune SQLite to the specific needs of
1433 ** the application.  The default configuration is recommended for most
1434 ** applications and so this routine is usually not necessary.  It is
1435 ** provided to support rare applications with unusual needs.
1436 **
1437 ** The sqlite3_config() interface is not threadsafe.  The application
1438 ** must insure that no other SQLite interfaces are invoked by other
1439 ** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1440 ** may only be invoked prior to library initialization using
1441 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1442 ** Note, however, that sqlite3_config() can be called as part of the
1443 ** implementation of an application-defined [sqlite3_os_init()].
1444 **
1445 ** The first argument to sqlite3_config() is an integer
1446 ** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines
1447 ** what property of SQLite is to be configured.  Subsequent arguments
1448 ** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option]
1449 ** in the first argument.
1450 **
1451 ** When a configuration option is set, sqlite3_config() returns SQLITE_OK.
1452 ** If the option is unknown or SQLite is unable to set the option
1453 ** then this routine returns a non-zero [error code].
1454 */
1455 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_config(int, ...);
1456
1457 /*
1458 ** CAPI3REF: Configure database connections  {H10180} <S20000>
1459 ** EXPERIMENTAL
1460 **
1461 ** The sqlite3_db_config() interface is used to make configuration
1462 ** changes to a [database connection].  The interface is similar to
1463 ** [sqlite3_config()] except that the changes apply to a single
1464 ** [database connection] (specified in the first argument).  The
1465 ** sqlite3_db_config() interface can only be used immediately after
1466 ** the database connection is created using [sqlite3_open()],
1467 ** [sqlite3_open16()], or [sqlite3_open_v2()].  
1468 **
1469 ** The second argument to sqlite3_db_config(D,V,...)  is the
1470 ** configuration verb - an integer code that indicates what
1471 ** aspect of the [database connection] is being configured.
1472 ** The only choice for this value is [SQLITE_DBCONFIG_LOOKASIDE].
1473 ** New verbs are likely to be added in future releases of SQLite.
1474 ** Additional arguments depend on the verb.
1475 */
1476 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_config(sqlite3*, int op, ...);
1477
1478 /*
1479 ** CAPI3REF: Memory Allocation Routines {H10155} <S20120>
1480 ** EXPERIMENTAL
1481 **
1482 ** An instance of this object defines the interface between SQLite
1483 ** and low-level memory allocation routines.
1484 **
1485 ** This object is used in only one place in the SQLite interface.
1486 ** A pointer to an instance of this object is the argument to
1487 ** [sqlite3_config()] when the configuration option is
1488 ** [SQLITE_CONFIG_MALLOC].  By creating an instance of this object
1489 ** and passing it to [sqlite3_config()] during configuration, an
1490 ** application can specify an alternative memory allocation subsystem
1491 ** for SQLite to use for all of its dynamic memory needs.
1492 **
1493 ** Note that SQLite comes with a built-in memory allocator that is
1494 ** perfectly adequate for the overwhelming majority of applications
1495 ** and that this object is only useful to a tiny minority of applications
1496 ** with specialized memory allocation requirements.  This object is
1497 ** also used during testing of SQLite in order to specify an alternative
1498 ** memory allocator that simulates memory out-of-memory conditions in
1499 ** order to verify that SQLite recovers gracefully from such
1500 ** conditions.
1501 **
1502 ** The xMalloc, xFree, and xRealloc methods must work like the
1503 ** malloc(), free(), and realloc() functions from the standard library.
1504 **
1505 ** xSize should return the allocated size of a memory allocation
1506 ** previously obtained from xMalloc or xRealloc.  The allocated size
1507 ** is always at least as big as the requested size but may be larger.
1508 **
1509 ** The xRoundup method returns what would be the allocated size of
1510 ** a memory allocation given a particular requested size.  Most memory
1511 ** allocators round up memory allocations at least to the next multiple
1512 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1513 **
1514 ** The xInit method initializes the memory allocator.  (For example,
1515 ** it might allocate any require mutexes or initialize internal data
1516 ** structures.  The xShutdown method is invoked (indirectly) by
1517 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1518 ** by xInit.  The pAppData pointer is used as the only parameter to
1519 ** xInit and xShutdown.
1520 */
1521 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1522 struct sqlite3_mem_methods {
1523   void *(*xMalloc)(int);         /* Memory allocation function */
1524   void (*xFree)(void*);          /* Free a prior allocation */
1525   void *(*xRealloc)(void*,int);  /* Resize an allocation */
1526   int (*xSize)(void*);           /* Return the size of an allocation */
1527   int (*xRoundup)(int);          /* Round up request size to allocation size */
1528   int (*xInit)(void*);           /* Initialize the memory allocator */
1529   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1530   void *pAppData;                /* Argument to xInit() and xShutdown() */
1531 };
1532
1533 /*
1534 ** CAPI3REF: Configuration Options {H10160} <S20000>
1535 ** EXPERIMENTAL
1536 **
1537 ** These constants are the available integer configuration options that
1538 ** can be passed as the first argument to the [sqlite3_config()] interface.
1539 **
1540 ** New configuration options may be added in future releases of SQLite.
1541 ** Existing configuration options might be discontinued.  Applications
1542 ** should check the return code from [sqlite3_config()] to make sure that
1543 ** the call worked.  The [sqlite3_config()] interface will return a
1544 ** non-zero [error code] if a discontinued or unsupported configuration option
1545 ** is invoked.
1546 **
1547 ** <dl>
1548 ** <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1549 ** <dd>There are no arguments to this option.  This option disables
1550 ** all mutexing and puts SQLite into a mode where it can only be used
1551 ** by a single thread.</dd>
1552 **
1553 ** <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1554 ** <dd>There are no arguments to this option.  This option disables
1555 ** mutexing on [database connection] and [prepared statement] objects.
1556 ** The application is responsible for serializing access to
1557 ** [database connections] and [prepared statements].  But other mutexes
1558 ** are enabled so that SQLite will be safe to use in a multi-threaded
1559 ** environment as long as no two threads attempt to use the same
1560 ** [database connection] at the same time.  See the [threading mode]
1561 ** documentation for additional information.</dd>
1562 **
1563 ** <dt>SQLITE_CONFIG_SERIALIZED</dt>
1564 ** <dd>There are no arguments to this option.  This option enables
1565 ** all mutexes including the recursive
1566 ** mutexes on [database connection] and [prepared statement] objects.
1567 ** In this mode (which is the default when SQLite is compiled with
1568 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1569 ** to [database connections] and [prepared statements] so that the
1570 ** application is free to use the same [database connection] or the
1571 ** same [prepared statement] in different threads at the same time.
1572 ** See the [threading mode] documentation for additional information.</dd>
1573 **
1574 ** <dt>SQLITE_CONFIG_MALLOC</dt>
1575 ** <dd>This option takes a single argument which is a pointer to an
1576 ** instance of the [sqlite3_mem_methods] structure.  The argument specifies
1577 ** alternative low-level memory allocation routines to be used in place of
1578 ** the memory allocation routines built into SQLite.</dd>
1579 **
1580 ** <dt>SQLITE_CONFIG_GETMALLOC</dt>
1581 ** <dd>This option takes a single argument which is a pointer to an
1582 ** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
1583 ** structure is filled with the currently defined memory allocation routines.
1584 ** This option can be used to overload the default memory allocation
1585 ** routines with a wrapper that simulations memory allocation failure or
1586 ** tracks memory usage, for example.</dd>
1587 **
1588 ** <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1589 ** <dd>This option takes single argument of type int, interpreted as a 
1590 ** boolean, which enables or disables the collection of memory allocation 
1591 ** statistics. When disabled, the following SQLite interfaces become 
1592 ** non-operational:
1593 **   <ul>
1594 **   <li> [sqlite3_memory_used()]
1595 **   <li> [sqlite3_memory_highwater()]
1596 **   <li> [sqlite3_soft_heap_limit()]
1597 **   <li> [sqlite3_status()]
1598 **   </ul>
1599 ** </dd>
1600 **
1601 ** <dt>SQLITE_CONFIG_SCRATCH</dt>
1602 ** <dd>This option specifies a static memory buffer that SQLite can use for
1603 ** scratch memory.  There are three arguments:  A pointer to the memory, the
1604 ** size of each scratch buffer (sz), and the number of buffers (N).  The sz
1605 ** argument must be a multiple of 16. The sz parameter should be a few bytes
1606 ** larger than the actual scratch space required due internal overhead.
1607 ** The first
1608 ** argument should point to an allocation of at least sz*N bytes of memory.
1609 ** SQLite will use no more than one scratch buffer at once per thread, so
1610 ** N should be set to the expected maximum number of threads.  The sz
1611 ** parameter should be 6 times the size of the largest database page size.
1612 ** Scratch buffers are used as part of the btree balance operation.  If
1613 ** The btree balancer needs additional memory beyond what is provided by
1614 ** scratch buffers or if no scratch buffer space is specified, then SQLite
1615 ** goes to [sqlite3_malloc()] to obtain the memory it needs.</dd>
1616 **
1617 ** <dt>SQLITE_CONFIG_PAGECACHE</dt>
1618 ** <dd>This option specifies a static memory buffer that SQLite can use for
1619 ** the database page cache.  There are three arguments: A pointer to the
1620 ** memory, the size of each page buffer (sz), and the number of pages (N).
1621 ** The sz argument must be a power of two between 512 and 32768.  The first
1622 ** argument should point to an allocation of at least sz*N bytes of memory.
1623 ** SQLite will use the memory provided by the first argument to satisfy its
1624 ** memory needs for the first N pages that it adds to cache.  If additional
1625 ** page cache memory is needed beyond what is provided by this option, then
1626 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1627 ** The implementation might use one or more of the N buffers to hold 
1628 ** memory accounting information. </dd>
1629 **
1630 ** <dt>SQLITE_CONFIG_HEAP</dt>
1631 ** <dd>This option specifies a static memory buffer that SQLite will use
1632 ** for all of its dynamic memory allocation needs beyond those provided
1633 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
1634 ** There are three arguments: A pointer to the memory, the number of
1635 ** bytes in the memory buffer, and the minimum allocation size.  If
1636 ** the first pointer (the memory pointer) is NULL, then SQLite reverts
1637 ** to using its default memory allocator (the system malloc() implementation),
1638 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  If the
1639 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
1640 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
1641 ** allocator is engaged to handle all of SQLites memory allocation needs.</dd>
1642 **
1643 ** <dt>SQLITE_CONFIG_MUTEX</dt>
1644 ** <dd>This option takes a single argument which is a pointer to an
1645 ** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
1646 ** alternative low-level mutex routines to be used in place
1647 ** the mutex routines built into SQLite.</dd>
1648 **
1649 ** <dt>SQLITE_CONFIG_GETMUTEX</dt>
1650 ** <dd>This option takes a single argument which is a pointer to an
1651 ** instance of the [sqlite3_mutex_methods] structure.  The
1652 ** [sqlite3_mutex_methods]
1653 ** structure is filled with the currently defined mutex routines.
1654 ** This option can be used to overload the default mutex allocation
1655 ** routines with a wrapper used to track mutex usage for performance
1656 ** profiling or testing, for example.</dd>
1657 **
1658 ** <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1659 ** <dd>This option takes two arguments that determine the default
1660 ** memory allcation lookaside optimization.  The first argument is the
1661 ** size of each lookaside buffer slot and the second is the number of
1662 ** slots allocated to each database connection.</dd>
1663 **
1664 ** </dl>
1665 */
1666 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
1667 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
1668 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
1669 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
1670 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
1671 #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
1672 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
1673 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
1674 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
1675 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
1676 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
1677 #define SQLITE_CONFIG_CHUNKALLOC   12  /* int threshold */
1678 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
1679
1680 /*
1681 ** CAPI3REF: Configuration Options {H10170} <S20000>
1682 ** EXPERIMENTAL
1683 **
1684 ** These constants are the available integer configuration options that
1685 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
1686 **
1687 ** New configuration options may be added in future releases of SQLite.
1688 ** Existing configuration options might be discontinued.  Applications
1689 ** should check the return code from [sqlite3_db_config()] to make sure that
1690 ** the call worked.  The [sqlite3_db_config()] interface will return a
1691 ** non-zero [error code] if a discontinued or unsupported configuration option
1692 ** is invoked.
1693 **
1694 ** <dl>
1695 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
1696 ** <dd>This option takes three additional arguments that determine the 
1697 ** [lookaside memory allocator] configuration for the [database connection].
1698 ** The first argument (the third parameter to [sqlite3_db_config()] is a
1699 ** pointer to a memory buffer to use for lookaside memory.  The first
1700 ** argument may be NULL in which case SQLite will allocate the lookaside
1701 ** buffer itself using [sqlite3_malloc()].  The second argument is the
1702 ** size of each lookaside buffer slot and the third argument is the number of
1703 ** slots.  The size of the buffer in the first argument must be greater than
1704 ** or equal to the product of the second and third arguments.</dd>
1705 **
1706 ** </dl>
1707 */
1708 #define SQLITE_DBCONFIG_LOOKASIDE    1001  /* void* int int */
1709
1710
1711 /*
1712 ** CAPI3REF: Enable Or Disable Extended Result Codes {H12200} <S10700>
1713 **
1714 ** The sqlite3_extended_result_codes() routine enables or disables the
1715 ** [extended result codes] feature of SQLite. The extended result
1716 ** codes are disabled by default for historical compatibility considerations.
1717 **
1718 ** INVARIANTS:
1719 **
1720 ** {H12201} Each new [database connection] shall have the
1721 **          [extended result codes] feature disabled by default.
1722 **
1723 ** {H12202} The [sqlite3_extended_result_codes(D,F)] interface shall enable
1724 **          [extended result codes] for the  [database connection] D
1725 **          if the F parameter is true, or disable them if F is false.
1726 */
1727 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
1728
1729 /*
1730 ** CAPI3REF: Last Insert Rowid {H12220} <S10700>
1731 **
1732 ** Each entry in an SQLite table has a unique 64-bit signed
1733 ** integer key called the "rowid". The rowid is always available
1734 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
1735 ** names are not also used by explicitly declared columns. If
1736 ** the table has a column of type INTEGER PRIMARY KEY then that column
1737 ** is another alias for the rowid.
1738 **
1739 ** This routine returns the rowid of the most recent
1740 ** successful INSERT into the database from the [database connection]
1741 ** in the first argument.  If no successful INSERTs
1742 ** have ever occurred on that database connection, zero is returned.
1743 **
1744 ** If an INSERT occurs within a trigger, then the rowid of the inserted
1745 ** row is returned by this routine as long as the trigger is running.
1746 ** But once the trigger terminates, the value returned by this routine
1747 ** reverts to the last value inserted before the trigger fired.
1748 **
1749 ** An INSERT that fails due to a constraint violation is not a
1750 ** successful INSERT and does not change the value returned by this
1751 ** routine.  Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
1752 ** and INSERT OR ABORT make no changes to the return value of this
1753 ** routine when their insertion fails.  When INSERT OR REPLACE
1754 ** encounters a constraint violation, it does not fail.  The
1755 ** INSERT continues to completion after deleting rows that caused
1756 ** the constraint problem so INSERT OR REPLACE will always change
1757 ** the return value of this interface.
1758 **
1759 ** For the purposes of this routine, an INSERT is considered to
1760 ** be successful even if it is subsequently rolled back.
1761 **
1762 ** INVARIANTS:
1763 **
1764 ** {H12221} The [sqlite3_last_insert_rowid()] function returns the rowid
1765 **          of the most recent successful INSERT performed on the same
1766 **          [database connection] and within the same or higher level
1767 **          trigger context, or zero if there have been no qualifying inserts.
1768 **
1769 ** {H12223} The [sqlite3_last_insert_rowid()] function returns the
1770 **          same value when called from the same trigger context
1771 **          immediately before and after a ROLLBACK.
1772 **
1773 ** ASSUMPTIONS:
1774 **
1775 ** {A12232} If a separate thread performs a new INSERT on the same
1776 **          database connection while the [sqlite3_last_insert_rowid()]
1777 **          function is running and thus changes the last insert rowid,
1778 **          then the value returned by [sqlite3_last_insert_rowid()] is
1779 **          unpredictable and might not equal either the old or the new
1780 **          last insert rowid.
1781 */
1782 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
1783
1784 /*
1785 ** CAPI3REF: Count The Number Of Rows Modified {H12240} <S10600>
1786 **
1787 ** This function returns the number of database rows that were changed
1788 ** or inserted or deleted by the most recently completed SQL statement
1789 ** on the [database connection] specified by the first parameter.
1790 ** Only changes that are directly specified by the INSERT, UPDATE,
1791 ** or DELETE statement are counted.  Auxiliary changes caused by
1792 ** triggers are not counted. Use the [sqlite3_total_changes()] function
1793 ** to find the total number of changes including changes caused by triggers.
1794 **
1795 ** A "row change" is a change to a single row of a single table
1796 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
1797 ** are changed as side effects of REPLACE constraint resolution,
1798 ** rollback, ABORT processing, DROP TABLE, or by any other
1799 ** mechanisms do not count as direct row changes.
1800 **
1801 ** A "trigger context" is a scope of execution that begins and
1802 ** ends with the script of a trigger.  Most SQL statements are
1803 ** evaluated outside of any trigger.  This is the "top level"
1804 ** trigger context.  If a trigger fires from the top level, a
1805 ** new trigger context is entered for the duration of that one
1806 ** trigger.  Subtriggers create subcontexts for their duration.
1807 **
1808 ** Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
1809 ** not create a new trigger context.
1810 **
1811 ** This function returns the number of direct row changes in the
1812 ** most recent INSERT, UPDATE, or DELETE statement within the same
1813 ** trigger context.
1814 **
1815 ** Thus, when called from the top level, this function returns the
1816 ** number of changes in the most recent INSERT, UPDATE, or DELETE
1817 ** that also occurred at the top level.  Within the body of a trigger,
1818 ** the sqlite3_changes() interface can be called to find the number of
1819 ** changes in the most recently completed INSERT, UPDATE, or DELETE
1820 ** statement within the body of the same trigger.
1821 ** However, the number returned does not include changes
1822 ** caused by subtriggers since those have their own context.
1823 **
1824 ** SQLite implements the command "DELETE FROM table" without a WHERE clause
1825 ** by dropping and recreating the table.  (This is much faster than going
1826 ** through and deleting individual elements from the table.)  Because of this
1827 ** optimization, the deletions in "DELETE FROM table" are not row changes and
1828 ** will not be counted by the sqlite3_changes() or [sqlite3_total_changes()]
1829 ** functions, regardless of the number of elements that were originally
1830 ** in the table.  To get an accurate count of the number of rows deleted, use
1831 ** "DELETE FROM table WHERE 1" instead.
1832 **
1833 ** INVARIANTS:
1834 **
1835 ** {H12241} The [sqlite3_changes()] function shall return the number of
1836 **          row changes caused by the most recent INSERT, UPDATE,
1837 **          or DELETE statement on the same database connection and
1838 **          within the same or higher trigger context, or zero if there have
1839 **          not been any qualifying row changes.
1840 **
1841 ** {H12243} Statements of the form "DELETE FROM tablename" with no
1842 **          WHERE clause shall cause subsequent calls to
1843 **          [sqlite3_changes()] to return zero, regardless of the
1844 **          number of rows originally in the table.
1845 **
1846 ** ASSUMPTIONS:
1847 **
1848 ** {A12252} If a separate thread makes changes on the same database connection
1849 **          while [sqlite3_changes()] is running then the value returned
1850 **          is unpredictable and not meaningful.
1851 */
1852 SQLITE_API int sqlite3_changes(sqlite3*);
1853
1854 /*
1855 ** CAPI3REF: Total Number Of Rows Modified {H12260} <S10600>
1856 **
1857 ** This function returns the number of row changes caused by INSERT,
1858 ** UPDATE or DELETE statements since the [database connection] was opened.
1859 ** The count includes all changes from all trigger contexts.  However,
1860 ** the count does not include changes used to implement REPLACE constraints,
1861 ** do rollbacks or ABORT processing, or DROP table processing.
1862 ** The changes are counted as soon as the statement that makes them is
1863 ** completed (when the statement handle is passed to [sqlite3_reset()] or
1864 ** [sqlite3_finalize()]).
1865 **
1866 ** SQLite implements the command "DELETE FROM table" without a WHERE clause
1867 ** by dropping and recreating the table.  (This is much faster than going
1868 ** through and deleting individual elements from the table.)  Because of this
1869 ** optimization, the deletions in "DELETE FROM table" are not row changes and
1870 ** will not be counted by the sqlite3_changes() or [sqlite3_total_changes()]
1871 ** functions, regardless of the number of elements that were originally
1872 ** in the table.  To get an accurate count of the number of rows deleted, use
1873 ** "DELETE FROM table WHERE 1" instead.
1874 **
1875 ** See also the [sqlite3_changes()] interface.
1876 **
1877 ** INVARIANTS:
1878 **
1879 ** {H12261} The [sqlite3_total_changes()] returns the total number
1880 **          of row changes caused by INSERT, UPDATE, and/or DELETE
1881 **          statements on the same [database connection], in any
1882 **          trigger context, since the database connection was created.
1883 **
1884 ** {H12263} Statements of the form "DELETE FROM tablename" with no
1885 **          WHERE clause shall not change the value returned
1886 **          by [sqlite3_total_changes()].
1887 **
1888 ** ASSUMPTIONS:
1889 **
1890 ** {A12264} If a separate thread makes changes on the same database connection
1891 **          while [sqlite3_total_changes()] is running then the value
1892 **          returned is unpredictable and not meaningful.
1893 */
1894 SQLITE_API int sqlite3_total_changes(sqlite3*);
1895
1896 /*
1897 ** CAPI3REF: Interrupt A Long-Running Query {H12270} <S30500>
1898 **
1899 ** This function causes any pending database operation to abort and
1900 ** return at its earliest opportunity. This routine is typically
1901 ** called in response to a user action such as pressing "Cancel"
1902 ** or Ctrl-C where the user wants a long query operation to halt
1903 ** immediately.
1904 **
1905 ** It is safe to call this routine from a thread different from the
1906 ** thread that is currently running the database operation.  But it
1907 ** is not safe to call this routine with a [database connection] that
1908 ** is closed or might close before sqlite3_interrupt() returns.
1909 **
1910 ** If an SQL operation is very nearly finished at the time when
1911 ** sqlite3_interrupt() is called, then it might not have an opportunity
1912 ** to be interrupted and might continue to completion.
1913 **
1914 ** An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
1915 ** If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
1916 ** that is inside an explicit transaction, then the entire transaction
1917 ** will be rolled back automatically.
1918 **
1919 ** A call to sqlite3_interrupt() has no effect on SQL statements
1920 ** that are started after sqlite3_interrupt() returns.
1921 **
1922 ** INVARIANTS:
1923 **
1924 ** {H12271} The [sqlite3_interrupt()] interface will force all running
1925 **          SQL statements associated with the same database connection
1926 **          to halt after processing at most one additional row of data.
1927 **
1928 ** {H12272} Any SQL statement that is interrupted by [sqlite3_interrupt()]
1929 **          will return [SQLITE_INTERRUPT].
1930 **
1931 ** ASSUMPTIONS:
1932 **
1933 ** {A12279} If the database connection closes while [sqlite3_interrupt()]
1934 **          is running then bad things will likely happen.
1935 */
1936 SQLITE_API void sqlite3_interrupt(sqlite3*);
1937
1938 /*
1939 ** CAPI3REF: Determine If An SQL Statement Is Complete {H10510} <S70200>
1940 **
1941 ** These routines are useful for command-line input to determine if the
1942 ** currently entered text seems to form complete a SQL statement or
1943 ** if additional input is needed before sending the text into
1944 ** SQLite for parsing.  These routines return true if the input string
1945 ** appears to be a complete SQL statement.  A statement is judged to be
1946 ** complete if it ends with a semicolon token and is not a fragment of a
1947 ** CREATE TRIGGER statement.  Semicolons that are embedded within
1948 ** string literals or quoted identifier names or comments are not
1949 ** independent tokens (they are part of the token in which they are
1950 ** embedded) and thus do not count as a statement terminator.
1951 **
1952 ** These routines do not parse the SQL statements thus
1953 ** will not detect syntactically incorrect SQL.
1954 **
1955 ** INVARIANTS:
1956 **
1957 ** {H10511} A successful evaluation of [sqlite3_complete()] or
1958 **          [sqlite3_complete16()] functions shall
1959 **          return a numeric 1 if and only if the last non-whitespace
1960 **          token in their input is a semicolon that is not in between
1961 **          the BEGIN and END of a CREATE TRIGGER statement.
1962 **
1963 ** {H10512} If a memory allocation error occurs during an invocation
1964 **          of [sqlite3_complete()] or [sqlite3_complete16()] then the
1965 **          routine shall return [SQLITE_NOMEM].
1966 **
1967 ** ASSUMPTIONS:
1968 **
1969 ** {A10512} The input to [sqlite3_complete()] must be a zero-terminated
1970 **          UTF-8 string.
1971 **
1972 ** {A10513} The input to [sqlite3_complete16()] must be a zero-terminated
1973 **          UTF-16 string in native byte order.
1974 */
1975 SQLITE_API int sqlite3_complete(const char *sql);
1976 SQLITE_API int sqlite3_complete16(const void *sql);
1977
1978 /*
1979 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {H12310} <S40400>
1980 **
1981 ** This routine sets a callback function that might be invoked whenever
1982 ** an attempt is made to open a database table that another thread
1983 ** or process has locked.
1984 **
1985 ** If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
1986 ** is returned immediately upon encountering the lock. If the busy callback
1987 ** is not NULL, then the callback will be invoked with two arguments.
1988 **
1989 ** The first argument to the handler is a copy of the void* pointer which
1990 ** is the third argument to sqlite3_busy_handler().  The second argument to
1991 ** the handler callback is the number of times that the busy handler has
1992 ** been invoked for this locking event.  If the
1993 ** busy callback returns 0, then no additional attempts are made to
1994 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
1995 ** If the callback returns non-zero, then another attempt
1996 ** is made to open the database for reading and the cycle repeats.
1997 **
1998 ** The presence of a busy handler does not guarantee that it will be invoked
1999 ** when there is lock contention. If SQLite determines that invoking the busy
2000 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2001 ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2002 ** Consider a scenario where one process is holding a read lock that
2003 ** it is trying to promote to a reserved lock and
2004 ** a second process is holding a reserved lock that it is trying
2005 ** to promote to an exclusive lock.  The first process cannot proceed
2006 ** because it is blocked by the second and the second process cannot
2007 ** proceed because it is blocked by the first.  If both processes
2008 ** invoke the busy handlers, neither will make any progress.  Therefore,
2009 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2010 ** will induce the first process to release its read lock and allow
2011 ** the second process to proceed.
2012 **
2013 ** The default busy callback is NULL.
2014 **
2015 ** The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2016 ** when SQLite is in the middle of a large transaction where all the
2017 ** changes will not fit into the in-memory cache.  SQLite will
2018 ** already hold a RESERVED lock on the database file, but it needs
2019 ** to promote this lock to EXCLUSIVE so that it can spill cache
2020 ** pages into the database file without harm to concurrent
2021 ** readers.  If it is unable to promote the lock, then the in-memory
2022 ** cache will be left in an inconsistent state and so the error
2023 ** code is promoted from the relatively benign [SQLITE_BUSY] to
2024 ** the more severe [SQLITE_IOERR_BLOCKED].  This error code promotion
2025 ** forces an automatic rollback of the changes.  See the
2026 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2027 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2028 ** this is important.
2029 **
2030 ** There can only be a single busy handler defined for each
2031 ** [database connection].  Setting a new busy handler clears any
2032 ** previously set handler.  Note that calling [sqlite3_busy_timeout()]
2033 ** will also set or clear the busy handler.
2034 **
2035 ** The busy callback should not take any actions which modify the
2036 ** database connection that invoked the busy handler.  Any such actions
2037 ** result in undefined behavior.
2038 ** 
2039 ** INVARIANTS:
2040 **
2041 ** {H12311} The [sqlite3_busy_handler(D,C,A)] function shall replace
2042 **          busy callback in the [database connection] D with a new
2043 **          a new busy handler C and application data pointer A.
2044 **
2045 ** {H12312} Newly created [database connections] shall have a busy
2046 **          handler of NULL.
2047 **
2048 ** {H12314} When two or more [database connections] share a
2049 **          [sqlite3_enable_shared_cache | common cache],
2050 **          the busy handler for the database connection currently using
2051 **          the cache shall be invoked when the cache encounters a lock.
2052 **
2053 ** {H12316} If a busy handler callback returns zero, then the SQLite interface
2054 **          that provoked the locking event shall return [SQLITE_BUSY].
2055 **
2056 ** {H12318} SQLite shall invokes the busy handler with two arguments which
2057 **          are a copy of the pointer supplied by the 3rd parameter to
2058 **          [sqlite3_busy_handler()] and a count of the number of prior
2059 **          invocations of the busy handler for the same locking event.
2060 **
2061 ** ASSUMPTIONS:
2062 **
2063 ** {A12319} A busy handler must not close the database connection
2064 **          or [prepared statement] that invoked the busy handler.
2065 */
2066 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2067
2068 /*
2069 ** CAPI3REF: Set A Busy Timeout {H12340} <S40410>
2070 **
2071 ** This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2072 ** for a specified amount of time when a table is locked.  The handler
2073 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2074 ** have accumulated. {H12343} After "ms" milliseconds of sleeping,
2075 ** the handler returns 0 which causes [sqlite3_step()] to return
2076 ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2077 **
2078 ** Calling this routine with an argument less than or equal to zero
2079 ** turns off all busy handlers.
2080 **
2081 ** There can only be a single busy handler for a particular
2082 ** [database connection] any any given moment.  If another busy handler
2083 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
2084 ** this routine, that other busy handler is cleared.
2085 **
2086 ** INVARIANTS:
2087 **
2088 ** {H12341} The [sqlite3_busy_timeout()] function shall override any prior
2089 **          [sqlite3_busy_timeout()] or [sqlite3_busy_handler()] setting
2090 **          on the same [database connection].
2091 **
2092 ** {H12343} If the 2nd parameter to [sqlite3_busy_timeout()] is less than
2093 **          or equal to zero, then the busy handler shall be cleared so that
2094 **          all subsequent locking events immediately return [SQLITE_BUSY].
2095 **
2096 ** {H12344} If the 2nd parameter to [sqlite3_busy_timeout()] is a positive
2097 **          number N, then a busy handler shall be set that repeatedly calls
2098 **          the xSleep() method in the [sqlite3_vfs | VFS interface] until
2099 **          either the lock clears or until the cumulative sleep time
2100 **          reported back by xSleep() exceeds N milliseconds.
2101 */
2102 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2103
2104 /*
2105 ** CAPI3REF: Convenience Routines For Running Queries {H12370} <S10000>
2106 **
2107 ** Definition: A <b>result table</b> is memory data structure created by the
2108 ** [sqlite3_get_table()] interface.  A result table records the
2109 ** complete query results from one or more queries.
2110 **
2111 ** The table conceptually has a number of rows and columns.  But
2112 ** these numbers are not part of the result table itself.  These
2113 ** numbers are obtained separately.  Let N be the number of rows
2114 ** and M be the number of columns.
2115 **
2116 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2117 ** There are (N+1)*M elements in the array.  The first M pointers point
2118 ** to zero-terminated strings that  contain the names of the columns.
2119 ** The remaining entries all point to query results.  NULL values result
2120 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2121 ** string representation as returned by [sqlite3_column_text()].
2122 **
2123 ** A result table might consist of one or more memory allocations.
2124 ** It is not safe to pass a result table directly to [sqlite3_free()].
2125 ** A result table should be deallocated using [sqlite3_free_table()].
2126 **
2127 ** As an example of the result table format, suppose a query result
2128 ** is as follows:
2129 **
2130 ** <blockquote><pre>
2131 **        Name        | Age
2132 **        -----------------------
2133 **        Alice       | 43
2134 **        Bob         | 28
2135 **        Cindy       | 21
2136 ** </pre></blockquote>
2137 **
2138 ** There are two column (M==2) and three rows (N==3).  Thus the
2139 ** result table has 8 entries.  Suppose the result table is stored
2140 ** in an array names azResult.  Then azResult holds this content:
2141 **
2142 ** <blockquote><pre>
2143 **        azResult&#91;0] = "Name";
2144 **        azResult&#91;1] = "Age";
2145 **        azResult&#91;2] = "Alice";
2146 **        azResult&#91;3] = "43";
2147 **        azResult&#91;4] = "Bob";
2148 **        azResult&#91;5] = "28";
2149 **        azResult&#91;6] = "Cindy";
2150 **        azResult&#91;7] = "21";
2151 ** </pre></blockquote>
2152 **
2153 ** The sqlite3_get_table() function evaluates one or more
2154 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2155 ** string of its 2nd parameter.  It returns a result table to the
2156 ** pointer given in its 3rd parameter.
2157 **
2158 ** After the calling function has finished using the result, it should
2159 ** pass the pointer to the result table to sqlite3_free_table() in order to
2160 ** release the memory that was malloced.  Because of the way the
2161 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2162 ** function must not try to call [sqlite3_free()] directly.  Only
2163 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2164 **
2165 ** The sqlite3_get_table() interface is implemented as a wrapper around
2166 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2167 ** to any internal data structures of SQLite.  It uses only the public
2168 ** interface defined here.  As a consequence, errors that occur in the
2169 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2170 ** reflected in subsequent calls to [sqlite3_errcode()] or [sqlite3_errmsg()].
2171 **
2172 ** INVARIANTS:
2173 **
2174 ** {H12371} If a [sqlite3_get_table()] fails a memory allocation, then
2175 **          it shall free the result table under construction, abort the
2176 **          query in process, skip any subsequent queries, set the
2177 **          *pazResult output pointer to NULL and return [SQLITE_NOMEM].
2178 **
2179 ** {H12373} If the pnColumn parameter to [sqlite3_get_table()] is not NULL
2180 **          then a successful invocation of [sqlite3_get_table()] shall
2181 **          write the number of columns in the
2182 **          result set of the query into *pnColumn.
2183 **
2184 ** {H12374} If the pnRow parameter to [sqlite3_get_table()] is not NULL
2185 **          then a successful invocation of [sqlite3_get_table()] shall
2186 **          writes the number of rows in the
2187 **          result set of the query into *pnRow.
2188 **
2189 ** {H12376} A successful invocation of [sqlite3_get_table()] that computes
2190 **          N rows of result with C columns per row shall make *pazResult
2191 **          point to an array of pointers to (N+1)*C strings where the first
2192 **          C strings are column names as obtained from
2193 **          [sqlite3_column_name()] and the rest are column result values
2194 **          obtained from [sqlite3_column_text()].
2195 **
2196 ** {H12379} The values in the pazResult array returned by [sqlite3_get_table()]
2197 **          shall remain valid until cleared by [sqlite3_free_table()].
2198 **
2199 ** {H12382} When an error occurs during evaluation of [sqlite3_get_table()]
2200 **          the function shall set *pazResult to NULL, write an error message
2201 **          into memory obtained from [sqlite3_malloc()], make
2202 **          **pzErrmsg point to that error message, and return a
2203 **          appropriate [error code].
2204 */
2205 SQLITE_API int sqlite3_get_table(
2206   sqlite3 *db,          /* An open database */
2207   const char *zSql,     /* SQL to be evaluated */
2208   char ***pazResult,    /* Results of the query */
2209   int *pnRow,           /* Number of result rows written here */
2210   int *pnColumn,        /* Number of result columns written here */
2211   char **pzErrmsg       /* Error msg written here */
2212 );
2213 SQLITE_API void sqlite3_free_table(char **result);
2214
2215 /*
2216 ** CAPI3REF: Formatted String Printing Functions {H17400} <S70000><S20000>
2217 **
2218 ** These routines are workalikes of the "printf()" family of functions
2219 ** from the standard C library.
2220 **
2221 ** The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2222 ** results into memory obtained from [sqlite3_malloc()].
2223 ** The strings returned by these two routines should be
2224 ** released by [sqlite3_free()].  Both routines return a
2225 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2226 ** memory to hold the resulting string.
2227 **
2228 ** In sqlite3_snprintf() routine is similar to "snprintf()" from
2229 ** the standard C library.  The result is written into the
2230 ** buffer supplied as the second parameter whose size is given by
2231 ** the first parameter. Note that the order of the
2232 ** first two parameters is reversed from snprintf().  This is an
2233 ** historical accident that cannot be fixed without breaking
2234 ** backwards compatibility.  Note also that sqlite3_snprintf()
2235 ** returns a pointer to its buffer instead of the number of
2236 ** characters actually written into the buffer.  We admit that
2237 ** the number of characters written would be a more useful return
2238 ** value but we cannot change the implementation of sqlite3_snprintf()
2239 ** now without breaking compatibility.
2240 **
2241 ** As long as the buffer size is greater than zero, sqlite3_snprintf()
2242 ** guarantees that the buffer is always zero-terminated.  The first
2243 ** parameter "n" is the total size of the buffer, including space for
2244 ** the zero terminator.  So the longest string that can be completely
2245 ** written will be n-1 characters.
2246 **
2247 ** These routines all implement some additional formatting
2248 ** options that are useful for constructing SQL statements.
2249 ** All of the usual printf() formatting options apply.  In addition, there
2250 ** is are "%q", "%Q", and "%z" options.
2251 **
2252 ** The %q option works like %s in that it substitutes a null-terminated
2253 ** string from the argument list.  But %q also doubles every '\'' character.
2254 ** %q is designed for use inside a string literal.  By doubling each '\''
2255 ** character it escapes that character and allows it to be inserted into
2256 ** the string.
2257 **
2258 ** For example, assume the string variable zText contains text as follows:
2259 **
2260 ** <blockquote><pre>
2261 **  char *zText = "It's a happy day!";
2262 ** </pre></blockquote>
2263 **
2264 ** One can use this text in an SQL statement as follows:
2265 **
2266 ** <blockquote><pre>
2267 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2268 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2269 **  sqlite3_free(zSQL);
2270 ** </pre></blockquote>
2271 **
2272 ** Because the %q format string is used, the '\'' character in zText
2273 ** is escaped and the SQL generated is as follows:
2274 **
2275 ** <blockquote><pre>
2276 **  INSERT INTO table1 VALUES('It''s a happy day!')
2277 ** </pre></blockquote>
2278 **
2279 ** This is correct.  Had we used %s instead of %q, the generated SQL
2280 ** would have looked like this:
2281 **
2282 ** <blockquote><pre>
2283 **  INSERT INTO table1 VALUES('It's a happy day!');
2284 ** </pre></blockquote>
2285 **
2286 ** This second example is an SQL syntax error.  As a general rule you should
2287 ** always use %q instead of %s when inserting text into a string literal.
2288 **
2289 ** The %Q option works like %q except it also adds single quotes around
2290 ** the outside of the total string.  Additionally, if the parameter in the
2291 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2292 ** single quotes) in place of the %Q option.  So, for example, one could say:
2293 **
2294 ** <blockquote><pre>
2295 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2296 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2297 **  sqlite3_free(zSQL);
2298 ** </pre></blockquote>
2299 **
2300 ** The code above will render a correct SQL statement in the zSQL
2301 ** variable even if the zText variable is a NULL pointer.
2302 **
2303 ** The "%z" formatting option works exactly like "%s" with the
2304 ** addition that after the string has been read and copied into
2305 ** the result, [sqlite3_free()] is called on the input string. {END}
2306 **
2307 ** INVARIANTS:
2308 **
2309 ** {H17403}  The [sqlite3_mprintf()] and [sqlite3_vmprintf()] interfaces
2310 **           return either pointers to zero-terminated UTF-8 strings held in
2311 **           memory obtained from [sqlite3_malloc()] or NULL pointers if
2312 **           a call to [sqlite3_malloc()] fails.
2313 **
2314 ** {H17406}  The [sqlite3_snprintf()] interface writes a zero-terminated
2315 **           UTF-8 string into the buffer pointed to by the second parameter
2316 **           provided that the first parameter is greater than zero.
2317 **
2318 ** {H17407}  The [sqlite3_snprintf()] interface does not write slots of
2319 **           its output buffer (the second parameter) outside the range
2320 **           of 0 through N-1 (where N is the first parameter)
2321 **           regardless of the length of the string
2322 **           requested by the format specification.
2323 */
2324 SQLITE_API char *sqlite3_mprintf(const char*,...);
2325 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2326 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2327
2328 /*
2329 ** CAPI3REF: Memory Allocation Subsystem {H17300} <S20000>
2330 **
2331 ** The SQLite core  uses these three routines for all of its own
2332 ** internal memory allocation needs. "Core" in the previous sentence
2333 ** does not include operating-system specific VFS implementation.  The
2334 ** Windows VFS uses native malloc() and free() for some operations.
2335 **
2336 ** The sqlite3_malloc() routine returns a pointer to a block
2337 ** of memory at least N bytes in length, where N is the parameter.
2338 ** If sqlite3_malloc() is unable to obtain sufficient free
2339 ** memory, it returns a NULL pointer.  If the parameter N to
2340 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2341 ** a NULL pointer.
2342 **
2343 ** Calling sqlite3_free() with a pointer previously returned
2344 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2345 ** that it might be reused.  The sqlite3_free() routine is
2346 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2347 ** to sqlite3_free() is harmless.  After being freed, memory
2348 ** should neither be read nor written.  Even reading previously freed
2349 ** memory might result in a segmentation fault or other severe error.
2350 ** Memory corruption, a segmentation fault, or other severe error
2351 ** might result if sqlite3_free() is called with a non-NULL pointer that
2352 ** was not obtained from sqlite3_malloc() or sqlite3_free().
2353 **
2354 ** The sqlite3_realloc() interface attempts to resize a
2355 ** prior memory allocation to be at least N bytes, where N is the
2356 ** second parameter.  The memory allocation to be resized is the first
2357 ** parameter.  If the first parameter to sqlite3_realloc()
2358 ** is a NULL pointer then its behavior is identical to calling
2359 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2360 ** If the second parameter to sqlite3_realloc() is zero or
2361 ** negative then the behavior is exactly the same as calling
2362 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2363 ** sqlite3_realloc() returns a pointer to a memory allocation
2364 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
2365 ** If M is the size of the prior allocation, then min(N,M) bytes
2366 ** of the prior allocation are copied into the beginning of buffer returned
2367 ** by sqlite3_realloc() and the prior allocation is freed.
2368 ** If sqlite3_realloc() returns NULL, then the prior allocation
2369 ** is not freed.
2370 **
2371 ** The memory returned by sqlite3_malloc() and sqlite3_realloc()
2372 ** is always aligned to at least an 8 byte boundary. {END}
2373 **
2374 ** The default implementation of the memory allocation subsystem uses
2375 ** the malloc(), realloc() and free() provided by the standard C library.
2376 ** {H17382} However, if SQLite is compiled with the
2377 ** SQLITE_MEMORY_SIZE=<i>NNN</i> C preprocessor macro (where <i>NNN</i>
2378 ** is an integer), then SQLite create a static array of at least
2379 ** <i>NNN</i> bytes in size and uses that array for all of its dynamic
2380 ** memory allocation needs. {END}  Additional memory allocator options
2381 ** may be added in future releases.
2382 **
2383 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2384 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2385 ** implementation of these routines to be omitted.  That capability
2386 ** is no longer provided.  Only built-in memory allocators can be used.
2387 **
2388 ** The Windows OS interface layer calls
2389 ** the system malloc() and free() directly when converting
2390 ** filenames between the UTF-8 encoding used by SQLite
2391 ** and whatever filename encoding is used by the particular Windows
2392 ** installation.  Memory allocation errors are detected, but
2393 ** they are reported back as [SQLITE_CANTOPEN] or
2394 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2395 **
2396 ** INVARIANTS:
2397 **
2398 ** {H17303}  The [sqlite3_malloc(N)] interface returns either a pointer to
2399 **           a newly checked-out block of at least N bytes of memory
2400 **           that is 8-byte aligned, or it returns NULL if it is unable
2401 **           to fulfill the request.
2402 **
2403 ** {H17304}  The [sqlite3_malloc(N)] interface returns a NULL pointer if
2404 **           N is less than or equal to zero.
2405 **
2406 ** {H17305}  The [sqlite3_free(P)] interface releases memory previously
2407 **           returned from [sqlite3_malloc()] or [sqlite3_realloc()],
2408 **           making it available for reuse.
2409 **
2410 ** {H17306}  A call to [sqlite3_free(NULL)] is a harmless no-op.
2411 **
2412 ** {H17310}  A call to [sqlite3_realloc(0,N)] is equivalent to a call
2413 **           to [sqlite3_malloc(N)].
2414 **
2415 ** {H17312}  A call to [sqlite3_realloc(P,0)] is equivalent to a call
2416 **           to [sqlite3_free(P)].
2417 **
2418 ** {H17315}  The SQLite core uses [sqlite3_malloc()], [sqlite3_realloc()],
2419 **           and [sqlite3_free()] for all of its memory allocation and
2420 **           deallocation needs.
2421 **
2422 ** {H17318}  The [sqlite3_realloc(P,N)] interface returns either a pointer
2423 **           to a block of checked-out memory of at least N bytes in size
2424 **           that is 8-byte aligned, or a NULL pointer.
2425 **
2426 ** {H17321}  When [sqlite3_realloc(P,N)] returns a non-NULL pointer, it first
2427 **           copies the first K bytes of content from P into the newly
2428 **           allocated block, where K is the lesser of N and the size of
2429 **           the buffer P.
2430 **
2431 ** {H17322}  When [sqlite3_realloc(P,N)] returns a non-NULL pointer, it first
2432 **           releases the buffer P.
2433 **
2434 ** {H17323}  When [sqlite3_realloc(P,N)] returns NULL, the buffer P is
2435 **           not modified or released.
2436 **
2437 ** ASSUMPTIONS:
2438 **
2439 ** {A17350}  The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2440 **           must be either NULL or else pointers obtained from a prior
2441 **           invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2442 **           not yet been released.
2443 **
2444 ** {A17351}  The application must not read or write any part of
2445 **           a block of memory after it has been released using
2446 **           [sqlite3_free()] or [sqlite3_realloc()].
2447 */
2448 SQLITE_API void *sqlite3_malloc(int);
2449 SQLITE_API void *sqlite3_realloc(void*, int);
2450 SQLITE_API void sqlite3_free(void*);
2451
2452 /*
2453 ** CAPI3REF: Memory Allocator Statistics {H17370} <S30210>
2454 **
2455 ** SQLite provides these two interfaces for reporting on the status
2456 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2457 ** routines, which form the built-in memory allocation subsystem.
2458 **
2459 ** INVARIANTS:
2460 **
2461 ** {H17371} The [sqlite3_memory_used()] routine returns the number of bytes
2462 **          of memory currently outstanding (malloced but not freed).
2463 **
2464 ** {H17373} The [sqlite3_memory_highwater()] routine returns the maximum
2465 **          value of [sqlite3_memory_used()] since the high-water mark
2466 **          was last reset.
2467 **
2468 ** {H17374} The values returned by [sqlite3_memory_used()] and
2469 **          [sqlite3_memory_highwater()] include any overhead
2470 **          added by SQLite in its implementation of [sqlite3_malloc()],
2471 **          but not overhead added by the any underlying system library
2472 **          routines that [sqlite3_malloc()] may call.
2473 **
2474 ** {H17375} The memory high-water mark is reset to the current value of
2475 **          [sqlite3_memory_used()] if and only if the parameter to
2476 **          [sqlite3_memory_highwater()] is true.  The value returned
2477 **          by [sqlite3_memory_highwater(1)] is the high-water mark
2478 **          prior to the reset.
2479 */
2480 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2481 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2482
2483 /*
2484 ** CAPI3REF: Pseudo-Random Number Generator {H17390} <S20000>
2485 **
2486 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2487 ** select random ROWIDs when inserting new records into a table that
2488 ** already uses the largest possible ROWID.  The PRNG is also used for
2489 ** the build-in random() and randomblob() SQL functions.  This interface allows
2490 ** applications to access the same PRNG for other purposes.
2491 **
2492 ** A call to this routine stores N bytes of randomness into buffer P.
2493 **
2494 ** The first time this routine is invoked (either internally or by
2495 ** the application) the PRNG is seeded using randomness obtained
2496 ** from the xRandomness method of the default [sqlite3_vfs] object.
2497 ** On all subsequent invocations, the pseudo-randomness is generated
2498 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2499 ** method.
2500 **
2501 ** INVARIANTS:
2502 **
2503 ** {H17392} The [sqlite3_randomness(N,P)] interface writes N bytes of
2504 **          high-quality pseudo-randomness into buffer P.
2505 */
2506 SQLITE_API void sqlite3_randomness(int N, void *P);
2507
2508 /*
2509 ** CAPI3REF: Compile-Time Authorization Callbacks {H12500} <S70100>
2510 **
2511 ** This routine registers a authorizer callback with a particular
2512 ** [database connection], supplied in the first argument.
2513 ** The authorizer callback is invoked as SQL statements are being compiled
2514 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2515 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  At various
2516 ** points during the compilation process, as logic is being created
2517 ** to perform various actions, the authorizer callback is invoked to
2518 ** see if those actions are allowed.  The authorizer callback should
2519 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2520 ** specific action but allow the SQL statement to continue to be
2521 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2522 ** rejected with an error.  If the authorizer callback returns
2523 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2524 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2525 ** the authorizer will fail with an error message.
2526 **
2527 ** When the callback returns [SQLITE_OK], that means the operation
2528 ** requested is ok.  When the callback returns [SQLITE_DENY], the
2529 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2530 ** authorizer will fail with an error message explaining that
2531 ** access is denied.  If the authorizer code is [SQLITE_READ]
2532 ** and the callback returns [SQLITE_IGNORE] then the
2533 ** [prepared statement] statement is constructed to substitute
2534 ** a NULL value in place of the table column that would have
2535 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2536 ** return can be used to deny an untrusted user access to individual
2537 ** columns of a table.
2538 **
2539 ** The first parameter to the authorizer callback is a copy of the third
2540 ** parameter to the sqlite3_set_authorizer() interface. The second parameter
2541 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2542 ** the particular action to be authorized. The third through sixth parameters
2543 ** to the callback are zero-terminated strings that contain additional
2544 ** details about the action to be authorized.
2545 **
2546 ** An authorizer is used when [sqlite3_prepare | preparing]
2547 ** SQL statements from an untrusted source, to ensure that the SQL statements
2548 ** do not try to access data they are not allowed to see, or that they do not
2549 ** try to execute malicious statements that damage the database.  For
2550 ** example, an application may allow a user to enter arbitrary
2551 ** SQL queries for evaluation by a database.  But the application does
2552 ** not want the user to be able to make arbitrary changes to the
2553 ** database.  An authorizer could then be put in place while the
2554 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2555 ** disallows everything except [SELECT] statements.
2556 **
2557 ** Applications that need to process SQL from untrusted sources
2558 ** might also consider lowering resource limits using [sqlite3_limit()]
2559 ** and limiting database size using the [max_page_count] [PRAGMA]
2560 ** in addition to using an authorizer.
2561 **
2562 ** Only a single authorizer can be in place on a database connection
2563 ** at a time.  Each call to sqlite3_set_authorizer overrides the
2564 ** previous call.  Disable the authorizer by installing a NULL callback.
2565 ** The authorizer is disabled by default.
2566 **
2567 ** The authorizer callback must not do anything that will modify
2568 ** the database connection that invoked the authorizer callback.
2569 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2570 ** database connections for the meaning of "modify" in this paragraph.
2571 **
2572 ** When [sqlite3_prepare_v2()] is used to prepare a statement, the
2573 ** statement might be reprepared during [sqlite3_step()] due to a 
2574 ** schema change.  Hence, the application should ensure that the
2575 ** correct authorizer callback remains in place during the [sqlite3_step()].
2576 **
2577 ** Note that the authorizer callback is invoked only during
2578 ** [sqlite3_prepare()] or its variants.  Authorization is not
2579 ** performed during statement evaluation in [sqlite3_step()].
2580 **
2581 ** INVARIANTS:
2582 **
2583 ** {H12501} The [sqlite3_set_authorizer(D,...)] interface registers a
2584 **          authorizer callback with database connection D.
2585 **
2586 ** {H12502} The authorizer callback is invoked as SQL statements are
2587 **          being parseed and compiled.
2588 **
2589 ** {H12503} If the authorizer callback returns any value other than
2590 **          [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY], then
2591 **          the application interface call that caused
2592 **          the authorizer callback to run shall fail with an
2593 **          [SQLITE_ERROR] error code and an appropriate error message.
2594 **
2595 ** {H12504} When the authorizer callback returns [SQLITE_OK], the operation
2596 **          described is processed normally.
2597 **
2598 ** {H12505} When the authorizer callback returns [SQLITE_DENY], the
2599 **          application interface call that caused the
2600 **          authorizer callback to run shall fail
2601 **          with an [SQLITE_ERROR] error code and an error message
2602 **          explaining that access is denied.
2603 **
2604 ** {H12506} If the authorizer code (the 2nd parameter to the authorizer
2605 **          callback) is [SQLITE_READ] and the authorizer callback returns
2606 **          [SQLITE_IGNORE], then the prepared statement is constructed to
2607 **          insert a NULL value in place of the table column that would have
2608 **          been read if [SQLITE_OK] had been returned.
2609 **
2610 ** {H12507} If the authorizer code (the 2nd parameter to the authorizer
2611 **          callback) is anything other than [SQLITE_READ], then
2612 **          a return of [SQLITE_IGNORE] has the same effect as [SQLITE_DENY].
2613 **
2614 ** {H12510} The first parameter to the authorizer callback is a copy of
2615 **          the third parameter to the [sqlite3_set_authorizer()] interface.
2616 **
2617 ** {H12511} The second parameter to the callback is an integer
2618 **          [SQLITE_COPY | action code] that specifies the particular action
2619 **          to be authorized.
2620 **
2621 ** {H12512} The third through sixth parameters to the callback are
2622 **          zero-terminated strings that contain
2623 **          additional details about the action to be authorized.
2624 **
2625 ** {H12520} Each call to [sqlite3_set_authorizer()] overrides
2626 **          any previously installed authorizer.
2627 **
2628 ** {H12521} A NULL authorizer means that no authorization
2629 **          callback is invoked.
2630 **
2631 ** {H12522} The default authorizer is NULL.
2632 */
2633 SQLITE_API int sqlite3_set_authorizer(
2634   sqlite3*,
2635   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2636   void *pUserData
2637 );
2638
2639 /*
2640 ** CAPI3REF: Authorizer Return Codes {H12590} <H12500>
2641 **
2642 ** The [sqlite3_set_authorizer | authorizer callback function] must
2643 ** return either [SQLITE_OK] or one of these two constants in order
2644 ** to signal SQLite whether or not the action is permitted.  See the
2645 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2646 ** information.
2647 */
2648 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2649 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2650
2651 /*
2652 ** CAPI3REF: Authorizer Action Codes {H12550} <H12500>
2653 **
2654 ** The [sqlite3_set_authorizer()] interface registers a callback function
2655 ** that is invoked to authorize certain SQL statement actions.  The
2656 ** second parameter to the callback is an integer code that specifies
2657 ** what action is being authorized.  These are the integer action codes that
2658 ** the authorizer callback may be passed.
2659 **
2660 ** These action code values signify what kind of operation is to be
2661 ** authorized.  The 3rd and 4th parameters to the authorization
2662 ** callback function will be parameters or NULL depending on which of these
2663 ** codes is used as the second parameter.  The 5th parameter to the
2664 ** authorizer callback is the name of the database ("main", "temp",
2665 ** etc.) if applicable.  The 6th parameter to the authorizer callback
2666 ** is the name of the inner-most trigger or view that is responsible for
2667 ** the access attempt or NULL if this access attempt is directly from
2668 ** top-level SQL code.
2669 **
2670 ** INVARIANTS:
2671 **
2672 ** {H12551} The second parameter to an
2673 **          [sqlite3_set_authorizer | authorizer callback] shall be an integer
2674 **          [SQLITE_COPY | authorizer code] that specifies what action
2675 **          is being authorized.
2676 **
2677 ** {H12552} The 3rd and 4th parameters to the
2678 **          [sqlite3_set_authorizer | authorization callback]
2679 **          shall be parameters or NULL depending on which
2680 **          [SQLITE_COPY | authorizer code] is used as the second parameter.
2681 **
2682 ** {H12553} The 5th parameter to the
2683 **          [sqlite3_set_authorizer | authorizer callback] shall be the name
2684 **          of the database (example: "main", "temp", etc.) if applicable.
2685 **
2686 ** {H12554} The 6th parameter to the
2687 **          [sqlite3_set_authorizer | authorizer callback] shall be the name
2688 **          of the inner-most trigger or view that is responsible for
2689 **          the access attempt or NULL if this access attempt is directly from
2690 **          top-level SQL code.
2691 */
2692 /******************************************* 3rd ************ 4th ***********/
2693 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2694 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2695 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2696 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2697 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2698 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2699 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2700 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2701 #define SQLITE_DELETE                9   /* Table Name      NULL            */
2702 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2703 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2704 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2705 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2706 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2707 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2708 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2709 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2710 #define SQLITE_INSERT               18   /* Table Name      NULL            */
2711 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2712 #define SQLITE_READ                 20   /* Table Name      Column Name     */
2713 #define SQLITE_SELECT               21   /* NULL            NULL            */
2714 #define SQLITE_TRANSACTION          22   /* NULL            NULL            */
2715 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2716 #define SQLITE_ATTACH               24   /* Filename        NULL            */
2717 #define SQLITE_DETACH               25   /* Database Name   NULL            */
2718 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2719 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
2720 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2721 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2722 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2723 #define SQLITE_FUNCTION             31   /* Function Name   NULL            */
2724 #define SQLITE_COPY                  0   /* No longer used */
2725
2726 /*
2727 ** CAPI3REF: Tracing And Profiling Functions {H12280} <S60400>
2728 ** EXPERIMENTAL
2729 **
2730 ** These routines register callback functions that can be used for
2731 ** tracing and profiling the execution of SQL statements.
2732 **
2733 ** The callback function registered by sqlite3_trace() is invoked at
2734 ** various times when an SQL statement is being run by [sqlite3_step()].
2735 ** The callback returns a UTF-8 rendering of the SQL statement text
2736 ** as the statement first begins executing.  Additional callbacks occur
2737 ** as each triggered subprogram is entered.  The callbacks for triggers
2738 ** contain a UTF-8 SQL comment that identifies the trigger.
2739 **
2740 ** The callback function registered by sqlite3_profile() is invoked
2741 ** as each SQL statement finishes.  The profile callback contains
2742 ** the original statement text and an estimate of wall-clock time
2743 ** of how long that statement took to run.
2744 **
2745 ** INVARIANTS:
2746 **
2747 ** {H12281} The callback function registered by [sqlite3_trace()] 
2748 **          shall be invoked
2749 **          whenever an SQL statement first begins to execute and
2750 **          whenever a trigger subprogram first begins to run.
2751 **
2752 ** {H12282} Each call to [sqlite3_trace()] shall override the previously
2753 **          registered trace callback.
2754 **
2755 ** {H12283} A NULL trace callback shall disable tracing.
2756 **
2757 ** {H12284} The first argument to the trace callback shall be a copy of
2758 **          the pointer which was the 3rd argument to [sqlite3_trace()].
2759 **
2760 ** {H12285} The second argument to the trace callback is a
2761 **          zero-terminated UTF-8 string containing the original text
2762 **          of the SQL statement as it was passed into [sqlite3_prepare_v2()]
2763 **          or the equivalent, or an SQL comment indicating the beginning
2764 **          of a trigger subprogram.
2765 **
2766 ** {H12287} The callback function registered by [sqlite3_profile()] is invoked
2767 **          as each SQL statement finishes.
2768 **
2769 ** {H12288} The first parameter to the profile callback is a copy of
2770 **          the 3rd parameter to [sqlite3_profile()].
2771 **
2772 ** {H12289} The second parameter to the profile callback is a
2773 **          zero-terminated UTF-8 string that contains the complete text of
2774 **          the SQL statement as it was processed by [sqlite3_prepare_v2()]
2775 **          or the equivalent.
2776 **
2777 ** {H12290} The third parameter to the profile callback is an estimate
2778 **          of the number of nanoseconds of wall-clock time required to
2779 **          run the SQL statement from start to finish.
2780 */
2781 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2782 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2783    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2784
2785 /*
2786 ** CAPI3REF: Query Progress Callbacks {H12910} <S60400>
2787 **
2788 ** This routine configures a callback function - the
2789 ** progress callback - that is invoked periodically during long
2790 ** running calls to [sqlite3_exec()], [sqlite3_step()] and
2791 ** [sqlite3_get_table()].  An example use for this
2792 ** interface is to keep a GUI updated during a large query.
2793 **
2794 ** If the progress callback returns non-zero, the operation is
2795 ** interrupted.  This feature can be used to implement a
2796 ** "Cancel" button on a GUI progress dialog box.
2797 **
2798 ** The progress handler must not do anything that will modify
2799 ** the database connection that invoked the progress handler.
2800 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2801 ** database connections for the meaning of "modify" in this paragraph.
2802 **
2803 ** INVARIANTS:
2804 **
2805 ** {H12911} The callback function registered by sqlite3_progress_handler()
2806 **          is invoked periodically during long running calls to
2807 **          [sqlite3_step()].
2808 **
2809 ** {H12912} The progress callback is invoked once for every N virtual
2810 **          machine opcodes, where N is the second argument to
2811 **          the [sqlite3_progress_handler()] call that registered
2812 **          the callback.  If N is less than 1, sqlite3_progress_handler()
2813 **          acts as if a NULL progress handler had been specified.
2814 **
2815 ** {H12913} The progress callback itself is identified by the third
2816 **          argument to sqlite3_progress_handler().
2817 **
2818 ** {H12914} The fourth argument to sqlite3_progress_handler() is a
2819 **          void pointer passed to the progress callback
2820 **          function each time it is invoked.
2821 **
2822 ** {H12915} If a call to [sqlite3_step()] results in fewer than N opcodes
2823 **          being executed, then the progress callback is never invoked.
2824 **
2825 ** {H12916} Every call to [sqlite3_progress_handler()]
2826 **          overwrites any previously registered progress handler.
2827 **
2828 ** {H12917} If the progress handler callback is NULL then no progress
2829 **          handler is invoked.
2830 **
2831 ** {H12918} If the progress callback returns a result other than 0, then
2832 **          the behavior is a if [sqlite3_interrupt()] had been called.
2833 **          <S30500>
2834 */
2835 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2836
2837 /*
2838 ** CAPI3REF: Opening A New Database Connection {H12700} <S40200>
2839 **
2840 ** These routines open an SQLite database file whose name is given by the
2841 ** filename argument. The filename argument is interpreted as UTF-8 for
2842 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
2843 ** order for sqlite3_open16(). A [database connection] handle is usually
2844 ** returned in *ppDb, even if an error occurs.  The only exception is that
2845 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
2846 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
2847 ** object. If the database is opened (and/or created) successfully, then
2848 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.  The
2849 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
2850 ** an English language description of the error.
2851 **
2852 ** The default encoding for the database will be UTF-8 if
2853 ** sqlite3_open() or sqlite3_open_v2() is called and
2854 ** UTF-16 in the native byte order if sqlite3_open16() is used.
2855 **
2856 ** Whether or not an error occurs when it is opened, resources
2857 ** associated with the [database connection] handle should be released by
2858 ** passing it to [sqlite3_close()] when it is no longer required.
2859 **
2860 ** The sqlite3_open_v2() interface works like sqlite3_open()
2861 ** except that it accepts two additional parameters for additional control
2862 ** over the new database connection.  The flags parameter can take one of
2863 ** the following three values, optionally combined with the 
2864 ** [SQLITE_OPEN_NOMUTEX] or [SQLITE_OPEN_FULLMUTEX] flags:
2865 **
2866 ** <dl>
2867 ** <dt>[SQLITE_OPEN_READONLY]</dt>
2868 ** <dd>The database is opened in read-only mode.  If the database does not
2869 ** already exist, an error is returned.</dd>
2870 **
2871 ** <dt>[SQLITE_OPEN_READWRITE]</dt>
2872 ** <dd>The database is opened for reading and writing if possible, or reading
2873 ** only if the file is write protected by the operating system.  In either
2874 ** case the database must already exist, otherwise an error is returned.</dd>
2875 **
2876 ** <dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
2877 ** <dd>The database is opened for reading and writing, and is creates it if
2878 ** it does not already exist. This is the behavior that is always used for
2879 ** sqlite3_open() and sqlite3_open16().</dd>
2880 ** </dl>
2881 **
2882 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
2883 ** combinations shown above or one of the combinations shown above combined
2884 ** with the [SQLITE_OPEN_NOMUTEX] or [SQLITE_OPEN_FULLMUTEX] flags,
2885 ** then the behavior is undefined.
2886 **
2887 ** If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
2888 ** opens in the multi-thread [threading mode] as long as the single-thread
2889 ** mode has not been set at compile-time or start-time.  If the
2890 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
2891 ** in the serialized [threading mode] unless single-thread was
2892 ** previously selected at compile-time or start-time.
2893 **
2894 ** If the filename is ":memory:", then a private, temporary in-memory database
2895 ** is created for the connection.  This in-memory database will vanish when
2896 ** the database connection is closed.  Future versions of SQLite might
2897 ** make use of additional special filenames that begin with the ":" character.
2898 ** It is recommended that when a database filename actually does begin with
2899 ** a ":" character you should prefix the filename with a pathname such as
2900 ** "./" to avoid ambiguity.
2901 **
2902 ** If the filename is an empty string, then a private, temporary
2903 ** on-disk database will be created.  This private database will be
2904 ** automatically deleted as soon as the database connection is closed.
2905 **
2906 ** The fourth parameter to sqlite3_open_v2() is the name of the
2907 ** [sqlite3_vfs] object that defines the operating system interface that
2908 ** the new database connection should use.  If the fourth parameter is
2909 ** a NULL pointer then the default [sqlite3_vfs] object is used.
2910 **
2911 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
2912 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
2913 ** codepage is currently defined.  Filenames containing international
2914 ** characters must be converted to UTF-8 prior to passing them into
2915 ** sqlite3_open() or sqlite3_open_v2().
2916 **
2917 ** INVARIANTS:
2918 **
2919 ** {H12701} The [sqlite3_open()], [sqlite3_open16()], and
2920 **          [sqlite3_open_v2()] interfaces create a new
2921 **          [database connection] associated with
2922 **          the database file given in their first parameter.
2923 **
2924 ** {H12702} The filename argument is interpreted as UTF-8
2925 **          for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16
2926 **          in the native byte order for [sqlite3_open16()].
2927 **
2928 ** {H12703} A successful invocation of [sqlite3_open()], [sqlite3_open16()],
2929 **          or [sqlite3_open_v2()] writes a pointer to a new
2930 **          [database connection] into *ppDb.
2931 **
2932 ** {H12704} The [sqlite3_open()], [sqlite3_open16()], and
2933 **          [sqlite3_open_v2()] interfaces return [SQLITE_OK] upon success,
2934 **          or an appropriate [error code] on failure.
2935 **
2936 ** {H12706} The default text encoding for a new database created using
2937 **          [sqlite3_open()] or [sqlite3_open_v2()] will be UTF-8.
2938 **
2939 ** {H12707} The default text encoding for a new database created using
2940 **          [sqlite3_open16()] will be UTF-16.
2941 **
2942 ** {H12709} The [sqlite3_open(F,D)] interface is equivalent to
2943 **          [sqlite3_open_v2(F,D,G,0)] where the G parameter is
2944 **          [SQLITE_OPEN_READWRITE]|[SQLITE_OPEN_CREATE].
2945 **
2946 ** {H12711} If the G parameter to [sqlite3_open_v2(F,D,G,V)] contains the
2947 **          bit value [SQLITE_OPEN_READONLY] then the database is opened
2948 **          for reading only.
2949 **
2950 ** {H12712} If the G parameter to [sqlite3_open_v2(F,D,G,V)] contains the
2951 **          bit value [SQLITE_OPEN_READWRITE] then the database is opened
2952 **          reading and writing if possible, or for reading only if the
2953 **          file is write protected by the operating system.
2954 **
2955 ** {H12713} If the G parameter to [sqlite3_open_v2(F,D,G,V)] omits the
2956 **          bit value [SQLITE_OPEN_CREATE] and the database does not
2957 **          previously exist, an error is returned.
2958 **
2959 ** {H12714} If the G parameter to [sqlite3_open_v2(F,D,G,V)] contains the
2960 **          bit value [SQLITE_OPEN_CREATE] and the database does not
2961 **          previously exist, then an attempt is made to create and
2962 **          initialize the database.
2963 **
2964 ** {H12717} If the filename argument to [sqlite3_open()], [sqlite3_open16()],
2965 **          or [sqlite3_open_v2()] is ":memory:", then an private,
2966 **          ephemeral, in-memory database is created for the connection.
2967 **          <todo>Is SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE required
2968 **          in sqlite3_open_v2()?</todo>
2969 **
2970 ** {H12719} If the filename is NULL or an empty string, then a private,
2971 **          ephemeral on-disk database will be created.
2972 **          <todo>Is SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE required
2973 **          in sqlite3_open_v2()?</todo>
2974 **
2975 ** {H12721} The [database connection] created by [sqlite3_open_v2(F,D,G,V)]
2976 **          will use the [sqlite3_vfs] object identified by the V parameter,
2977 **          or the default [sqlite3_vfs] object if V is a NULL pointer.
2978 **
2979 ** {H12723} Two [database connections] will share a common cache if both were
2980 **          opened with the same VFS while [shared cache mode] was enabled and
2981 **          if both filenames compare equal using memcmp() after having been
2982 **          processed by the [sqlite3_vfs | xFullPathname] method of the VFS.
2983 */
2984 SQLITE_API int sqlite3_open(
2985   const char *filename,   /* Database filename (UTF-8) */
2986   sqlite3 **ppDb          /* OUT: SQLite db handle */
2987 );
2988 SQLITE_API int sqlite3_open16(
2989   const void *filename,   /* Database filename (UTF-16) */
2990   sqlite3 **ppDb          /* OUT: SQLite db handle */
2991 );
2992 SQLITE_API int sqlite3_open_v2(
2993   const char *filename,   /* Database filename (UTF-8) */
2994   sqlite3 **ppDb,         /* OUT: SQLite db handle */
2995   int flags,              /* Flags */
2996   const char *zVfs        /* Name of VFS module to use */
2997 );
2998
2999 /*
3000 ** CAPI3REF: Error Codes And Messages {H12800} <S60200>
3001 **
3002 ** The sqlite3_errcode() interface returns the numeric [result code] or
3003 ** [extended result code] for the most recent failed sqlite3_* API call
3004 ** associated with a [database connection]. If a prior API call failed
3005 ** but the most recent API call succeeded, the return value from
3006 ** sqlite3_errcode() is undefined.
3007 **
3008 ** The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
3009 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
3010 ** Memory to hold the error message string is managed internally.
3011 ** The application does not need to worry about freeing the result.
3012 ** However, the error string might be overwritten or deallocated by
3013 ** subsequent calls to other SQLite interface functions.
3014 **
3015 ** If an interface fails with SQLITE_MISUSE, that means the interface
3016 ** was invoked incorrectly by the application.  In that case, the
3017 ** error code and message may or may not be set.
3018 **
3019 ** INVARIANTS:
3020 **
3021 ** {H12801} The [sqlite3_errcode(D)] interface returns the numeric
3022 **          [result code] or [extended result code] for the most recently
3023 **          failed interface call associated with the [database connection] D.
3024 **
3025 ** {H12803} The [sqlite3_errmsg(D)] and [sqlite3_errmsg16(D)]
3026 **          interfaces return English-language text that describes
3027 **          the error in the mostly recently failed interface call,
3028 **          encoded as either UTF-8 or UTF-16 respectively.
3029 **
3030 ** {H12807} The strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()]
3031 **          are valid until the next SQLite interface call.
3032 **
3033 ** {H12808} Calls to API routines that do not return an error code
3034 **          (example: [sqlite3_data_count()]) do not
3035 **          change the error code or message returned by
3036 **          [sqlite3_errcode()], [sqlite3_errmsg()], or [sqlite3_errmsg16()].
3037 **
3038 ** {H12809} Interfaces that are not associated with a specific
3039 **          [database connection] (examples:
3040 **          [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()]
3041 **          do not change the values returned by
3042 **          [sqlite3_errcode()], [sqlite3_errmsg()], or [sqlite3_errmsg16()].
3043 */
3044 SQLITE_API int sqlite3_errcode(sqlite3 *db);
3045 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
3046 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
3047
3048 /*
3049 ** CAPI3REF: SQL Statement Object {H13000} <H13010>
3050 ** KEYWORDS: {prepared statement} {prepared statements}
3051 **
3052 ** An instance of this object represents a single SQL statement.
3053 ** This object is variously known as a "prepared statement" or a
3054 ** "compiled SQL statement" or simply as a "statement".
3055 **
3056 ** The life of a statement object goes something like this:
3057 **
3058 ** <ol>
3059 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
3060 **      function.
3061 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
3062 **      interfaces.
3063 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3064 ** <li> Reset the statement using [sqlite3_reset()] then go back
3065 **      to step 2.  Do this zero or more times.
3066 ** <li> Destroy the object using [sqlite3_finalize()].
3067 ** </ol>
3068 **
3069 ** Refer to documentation on individual methods above for additional
3070 ** information.
3071 */
3072 typedef struct sqlite3_stmt sqlite3_stmt;
3073
3074 /*
3075 ** CAPI3REF: Run-time Limits {H12760} <S20600>
3076 **
3077 ** This interface allows the size of various constructs to be limited
3078 ** on a connection by connection basis.  The first parameter is the
3079 ** [database connection] whose limit is to be set or queried.  The
3080 ** second parameter is one of the [limit categories] that define a
3081 ** class of constructs to be size limited.  The third parameter is the
3082 ** new limit for that construct.  The function returns the old limit.
3083 **
3084 ** If the new limit is a negative number, the limit is unchanged.
3085 ** For the limit category of SQLITE_LIMIT_XYZ there is a hard upper
3086 ** bound set by a compile-time C preprocessor macro named SQLITE_MAX_XYZ.
3087 ** (The "_LIMIT_" in the name is changed to "_MAX_".)
3088 ** Attempts to increase a limit above its hard upper bound are
3089 ** silently truncated to the hard upper limit.
3090 **
3091 ** Run time limits are intended for use in applications that manage
3092 ** both their own internal database and also databases that are controlled
3093 ** by untrusted external sources.  An example application might be a
3094 ** webbrowser that has its own databases for storing history and
3095 ** separate databases controlled by JavaScript applications downloaded
3096 ** off the Internet.  The internal databases can be given the
3097 ** large, default limits.  Databases managed by external sources can
3098 ** be given much smaller limits designed to prevent a denial of service
3099 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
3100 ** interface to further control untrusted SQL.  The size of the database
3101 ** created by an untrusted script can be contained using the
3102 ** [max_page_count] [PRAGMA].
3103 **
3104 ** New run-time limit categories may be added in future releases.
3105 **
3106 ** INVARIANTS:
3107 **
3108 ** {H12762} A successful call to [sqlite3_limit(D,C,V)] where V is
3109 **          positive changes the limit on the size of construct C in the
3110 **          [database connection] D to the lesser of V and the hard upper
3111 **          bound on the size of C that is set at compile-time.
3112 **
3113 ** {H12766} A successful call to [sqlite3_limit(D,C,V)] where V is negative
3114 **          leaves the state of the [database connection] D unchanged.
3115 **
3116 ** {H12769} A successful call to [sqlite3_limit(D,C,V)] returns the
3117 **          value of the limit on the size of construct C in the
3118 **          [database connection] D as it was prior to the call.
3119 */
3120 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
3121
3122 /*
3123 ** CAPI3REF: Run-Time Limit Categories {H12790} <H12760>
3124 ** KEYWORDS: {limit category} {limit categories}
3125 **
3126 ** These constants define various aspects of a [database connection]
3127 ** that can be limited in size by calls to [sqlite3_limit()].
3128 ** The meanings of the various limits are as follows:
3129 **
3130 ** <dl>
3131 ** <dt>SQLITE_LIMIT_LENGTH</dt>
3132 ** <dd>The maximum size of any string or BLOB or table row.<dd>
3133 **
3134 ** <dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3135 ** <dd>The maximum length of an SQL statement.</dd>
3136 **
3137 ** <dt>SQLITE_LIMIT_COLUMN</dt>
3138 ** <dd>The maximum number of columns in a table definition or in the
3139 ** result set of a SELECT or the maximum number of columns in an index
3140 ** or in an ORDER BY or GROUP BY clause.</dd>
3141 **
3142 ** <dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3143 ** <dd>The maximum depth of the parse tree on any expression.</dd>
3144 **
3145 ** <dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3146 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>
3147 **
3148 ** <dt>SQLITE_LIMIT_VDBE_OP</dt>
3149 ** <dd>The maximum number of instructions in a virtual machine program
3150 ** used to implement an SQL statement.</dd>
3151 **
3152 ** <dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3153 ** <dd>The maximum number of arguments on a function.</dd>
3154 **
3155 ** <dt>SQLITE_LIMIT_ATTACHED</dt>
3156 ** <dd>The maximum number of attached databases.</dd>
3157 **
3158 ** <dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3159 ** <dd>The maximum length of the pattern argument to the LIKE or
3160 ** GLOB operators.</dd>
3161 **
3162 ** <dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3163 ** <dd>The maximum number of variables in an SQL statement that can
3164 ** be bound.</dd>
3165 ** </dl>
3166 */
3167 #define SQLITE_LIMIT_LENGTH                    0
3168 #define SQLITE_LIMIT_SQL_LENGTH                1
3169 #define SQLITE_LIMIT_COLUMN                    2
3170 #define SQLITE_LIMIT_EXPR_DEPTH                3
3171 #define SQLITE_LIMIT_COMPOUND_SELECT           4
3172 #define SQLITE_LIMIT_VDBE_OP                   5
3173 #define SQLITE_LIMIT_FUNCTION_ARG              6
3174 #define SQLITE_LIMIT_ATTACHED                  7
3175 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3176 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
3177
3178 /*
3179 ** CAPI3REF: Compiling An SQL Statement {H13010} <S10000>
3180 ** KEYWORDS: {SQL statement compiler}
3181 **
3182 ** To execute an SQL query, it must first be compiled into a byte-code
3183 ** program using one of these routines.
3184 **
3185 ** The first argument, "db", is a [database connection] obtained from a
3186 ** prior call to [sqlite3_open()], [sqlite3_open_v2()] or [sqlite3_open16()].
3187 **
3188 ** The second argument, "zSql", is the statement to be compiled, encoded
3189 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3190 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3191 ** use UTF-16.
3192 **
3193 ** If the nByte argument is less than zero, then zSql is read up to the
3194 ** first zero terminator. If nByte is non-negative, then it is the maximum
3195 ** number of  bytes read from zSql.  When nByte is non-negative, the
3196 ** zSql string ends at either the first '\000' or '\u0000' character or
3197 ** the nByte-th byte, whichever comes first. If the caller knows
3198 ** that the supplied string is nul-terminated, then there is a small
3199 ** performance advantage to be gained by passing an nByte parameter that
3200 ** is equal to the number of bytes in the input string <i>including</i>
3201 ** the nul-terminator bytes.
3202 **
3203 ** *pzTail is made to point to the first byte past the end of the
3204 ** first SQL statement in zSql.  These routines only compile the first
3205 ** statement in zSql, so *pzTail is left pointing to what remains
3206 ** uncompiled.
3207 **
3208 ** *ppStmt is left pointing to a compiled [prepared statement] that can be
3209 ** executed using [sqlite3_step()].  If there is an error, *ppStmt is set
3210 ** to NULL.  If the input text contains no SQL (if the input is an empty
3211 ** string or a comment) then *ppStmt is set to NULL.
3212 ** {A13018} The calling procedure is responsible for deleting the compiled
3213 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3214 **
3215 ** On success, [SQLITE_OK] is returned, otherwise an [error code] is returned.
3216 **
3217 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3218 ** recommended for all new programs. The two older interfaces are retained
3219 ** for backwards compatibility, but their use is discouraged.
3220 ** In the "v2" interfaces, the prepared statement
3221 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3222 ** original SQL text. This causes the [sqlite3_step()] interface to
3223 ** behave a differently in two ways:
3224 **
3225 ** <ol>
3226 ** <li>
3227 ** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3228 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3229 ** statement and try to run it again.  If the schema has changed in
3230 ** a way that makes the statement no longer valid, [sqlite3_step()] will still
3231 ** return [SQLITE_SCHEMA].  But unlike the legacy behavior, [SQLITE_SCHEMA] is
3232 ** now a fatal error.  Calling [sqlite3_prepare_v2()] again will not make the
3233 ** error go away.  Note: use [sqlite3_errmsg()] to find the text
3234 ** of the parsing error that results in an [SQLITE_SCHEMA] return.
3235 ** </li>
3236 **
3237 ** <li>
3238 ** When an error occurs, [sqlite3_step()] will return one of the detailed
3239 ** [error codes] or [extended error codes].  The legacy behavior was that
3240 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3241 ** and you would have to make a second call to [sqlite3_reset()] in order
3242 ** to find the underlying cause of the problem. With the "v2" prepare
3243 ** interfaces, the underlying reason for the error is returned immediately.
3244 ** </li>
3245 ** </ol>
3246 **
3247 ** INVARIANTS:
3248 **
3249 ** {H13011} The [sqlite3_prepare(db,zSql,...)] and
3250 **          [sqlite3_prepare_v2(db,zSql,...)] interfaces interpret the
3251 **          text in their zSql parameter as UTF-8.
3252 **
3253 ** {H13012} The [sqlite3_prepare16(db,zSql,...)] and
3254 **          [sqlite3_prepare16_v2(db,zSql,...)] interfaces interpret the
3255 **          text in their zSql parameter as UTF-16 in the native byte order.
3256 **
3257 ** {H13013} If the nByte argument to [sqlite3_prepare_v2(db,zSql,nByte,...)]
3258 **          and its variants is less than zero, the SQL text is
3259 **          read from zSql is read up to the first zero terminator.
3260 **
3261 ** {H13014} If the nByte argument to [sqlite3_prepare_v2(db,zSql,nByte,...)]
3262 **          and its variants is non-negative, then at most nBytes bytes of
3263 **          SQL text is read from zSql.
3264 **
3265 ** {H13015} In [sqlite3_prepare_v2(db,zSql,N,P,pzTail)] and its variants
3266 **          if the zSql input text contains more than one SQL statement
3267 **          and pzTail is not NULL, then *pzTail is made to point to the
3268 **          first byte past the end of the first SQL statement in zSql.
3269 **          <todo>What does *pzTail point to if there is one statement?</todo>
3270 **
3271 ** {H13016} A successful call to [sqlite3_prepare_v2(db,zSql,N,ppStmt,...)]
3272 **          or one of its variants writes into *ppStmt a pointer to a new
3273 **          [prepared statement] or a pointer to NULL if zSql contains
3274 **          nothing other than whitespace or comments.
3275 **
3276 ** {H13019} The [sqlite3_prepare_v2()] interface and its variants return
3277 **          [SQLITE_OK] or an appropriate [error code] upon failure.
3278 **
3279 ** {H13021} Before [sqlite3_prepare(db,zSql,nByte,ppStmt,pzTail)] or its
3280 **          variants returns an error (any value other than [SQLITE_OK]),
3281 **          they first set *ppStmt to NULL.
3282 */
3283 SQLITE_API int sqlite3_prepare(
3284   sqlite3 *db,            /* Database handle */
3285   const char *zSql,       /* SQL statement, UTF-8 encoded */
3286   int nByte,              /* Maximum length of zSql in bytes. */
3287   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3288   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3289 );
3290 SQLITE_API int sqlite3_prepare_v2(
3291   sqlite3 *db,            /* Database handle */
3292   const char *zSql,       /* SQL statement, UTF-8 encoded */
3293   int nByte,              /* Maximum length of zSql in bytes. */
3294   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3295   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3296 );
3297 SQLITE_API int sqlite3_prepare16(
3298   sqlite3 *db,            /* Database handle */
3299   const void *zSql,       /* SQL statement, UTF-16 encoded */
3300   int nByte,              /* Maximum length of zSql in bytes. */
3301   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3302   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3303 );
3304 SQLITE_API int sqlite3_prepare16_v2(
3305   sqlite3 *db,            /* Database handle */
3306   const void *zSql,       /* SQL statement, UTF-16 encoded */
3307   int nByte,              /* Maximum length of zSql in bytes. */
3308   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3309   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3310 );
3311
3312 /*
3313 ** CAPIREF: Retrieving Statement SQL {H13100} <H13000>
3314 **
3315 ** This interface can be used to retrieve a saved copy of the original
3316 ** SQL text used to create a [prepared statement] if that statement was
3317 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3318 **
3319 ** INVARIANTS:
3320 **
3321 ** {H13101} If the [prepared statement] passed as the argument to
3322 **          [sqlite3_sql()] was compiled using either [sqlite3_prepare_v2()] or
3323 **          [sqlite3_prepare16_v2()], then [sqlite3_sql()] returns
3324 **          a pointer to a zero-terminated string containing a UTF-8 rendering
3325 **          of the original SQL statement.
3326 **
3327 ** {H13102} If the [prepared statement] passed as the argument to
3328 **          [sqlite3_sql()] was compiled using either [sqlite3_prepare()] or
3329 **          [sqlite3_prepare16()], then [sqlite3_sql()] returns a NULL pointer.
3330 **
3331 ** {H13103} The string returned by [sqlite3_sql(S)] is valid until the
3332 **          [prepared statement] S is deleted using [sqlite3_finalize(S)].
3333 */
3334 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3335
3336 /*
3337 ** CAPI3REF: Dynamically Typed Value Object {H15000} <S20200>
3338 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3339 **
3340 ** SQLite uses the sqlite3_value object to represent all values
3341 ** that can be stored in a database table. SQLite uses dynamic typing
3342 ** for the values it stores. Values stored in sqlite3_value objects
3343 ** can be integers, floating point values, strings, BLOBs, or NULL.
3344 **
3345 ** An sqlite3_value object may be either "protected" or "unprotected".
3346 ** Some interfaces require a protected sqlite3_value.  Other interfaces
3347 ** will accept either a protected or an unprotected sqlite3_value.
3348 ** Every interface that accepts sqlite3_value arguments specifies
3349 ** whether or not it requires a protected sqlite3_value.
3350 **
3351 ** The terms "protected" and "unprotected" refer to whether or not
3352 ** a mutex is held.  A internal mutex is held for a protected
3353 ** sqlite3_value object but no mutex is held for an unprotected
3354 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
3355 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3356 ** or if SQLite is run in one of reduced mutex modes 
3357 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3358 ** then there is no distinction between protected and unprotected
3359 ** sqlite3_value objects and they can be used interchangeably.  However,
3360 ** for maximum code portability it is recommended that applications
3361 ** still make the distinction between between protected and unprotected
3362 ** sqlite3_value objects even when not strictly required.
3363 **
3364 ** The sqlite3_value objects that are passed as parameters into the
3365 ** implementation of [application-defined SQL functions] are protected.
3366 ** The sqlite3_value object returned by
3367 ** [sqlite3_column_value()] is unprotected.
3368 ** Unprotected sqlite3_value objects may only be used with
3369 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3370 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3371 ** interfaces require protected sqlite3_value objects.
3372 */
3373 typedef struct Mem sqlite3_value;
3374
3375 /*
3376 ** CAPI3REF: SQL Function Context Object {H16001} <S20200>
3377 **
3378 ** The context in which an SQL function executes is stored in an
3379 ** sqlite3_context object.  A pointer to an sqlite3_context object
3380 ** is always first parameter to [application-defined SQL functions].
3381 ** The application-defined SQL function implementation will pass this
3382 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3383 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3384 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3385 ** and/or [sqlite3_set_auxdata()].
3386 */
3387 typedef struct sqlite3_context sqlite3_context;
3388
3389 /*
3390 ** CAPI3REF: Binding Values To Prepared Statements {H13500} <S70300>
3391 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3392 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3393 **
3394 ** In the SQL strings input to [sqlite3_prepare_v2()] and its variants,
3395 ** literals may be replaced by a parameter in one of these forms:
3396 **
3397 ** <ul>
3398 ** <li>  ?
3399 ** <li>  ?NNN
3400 ** <li>  :VVV
3401 ** <li>  @VVV
3402 ** <li>  $VVV
3403 ** </ul>
3404 **
3405 ** In the parameter forms shown above NNN is an integer literal,
3406 ** and VVV is an alpha-numeric parameter name. The values of these
3407 ** parameters (also called "host parameter names" or "SQL parameters")
3408 ** can be set using the sqlite3_bind_*() routines defined here.
3409 **
3410 ** The first argument to the sqlite3_bind_*() routines is always
3411 ** a pointer to the [sqlite3_stmt] object returned from
3412 ** [sqlite3_prepare_v2()] or its variants.
3413 **
3414 ** The second argument is the index of the SQL parameter to be set.
3415 ** The leftmost SQL parameter has an index of 1.  When the same named
3416 ** SQL parameter is used more than once, second and subsequent
3417 ** occurrences have the same index as the first occurrence.
3418 ** The index for named parameters can be looked up using the
3419 ** [sqlite3_bind_parameter_index()] API if desired.  The index
3420 ** for "?NNN" parameters is the value of NNN.
3421 ** The NNN value must be between 1 and the [sqlite3_limit()]
3422 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3423 **
3424 ** The third argument is the value to bind to the parameter.
3425 **
3426 ** In those routines that have a fourth argument, its value is the
3427 ** number of bytes in the parameter.  To be clear: the value is the
3428 ** number of <u>bytes</u> in the value, not the number of characters.
3429 ** If the fourth parameter is negative, the length of the string is
3430 ** the number of bytes up to the first zero terminator.
3431 **
3432 ** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3433 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3434 ** string after SQLite has finished with it. If the fifth argument is
3435 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3436 ** information is in static, unmanaged space and does not need to be freed.
3437 ** If the fifth argument has the value [SQLITE_TRANSIENT], then
3438 ** SQLite makes its own private copy of the data immediately, before
3439 ** the sqlite3_bind_*() routine returns.
3440 **
3441 ** The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3442 ** is filled with zeroes.  A zeroblob uses a fixed amount of memory
3443 ** (just an integer to hold its size) while it is being processed.
3444 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3445 ** content is later written using
3446 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3447 ** A negative value for the zeroblob results in a zero-length BLOB.
3448 **
3449 ** The sqlite3_bind_*() routines must be called after
3450 ** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and
3451 ** before [sqlite3_step()].
3452 ** Bindings are not cleared by the [sqlite3_reset()] routine.
3453 ** Unbound parameters are interpreted as NULL.
3454 **
3455 ** These routines return [SQLITE_OK] on success or an error code if
3456 ** anything goes wrong.  [SQLITE_RANGE] is returned if the parameter
3457 ** index is out of range.  [SQLITE_NOMEM] is returned if malloc() fails.
3458 ** [SQLITE_MISUSE] might be returned if these routines are called on a
3459 ** virtual machine that is the wrong state or which has already been finalized.
3460 ** Detection of misuse is unreliable.  Applications should not depend
3461 ** on SQLITE_MISUSE returns.  SQLITE_MISUSE is intended to indicate a
3462 ** a logic error in the application.  Future versions of SQLite might
3463 ** panic rather than return SQLITE_MISUSE.
3464 **
3465 ** See also: [sqlite3_bind_parameter_count()],
3466 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3467 **
3468 ** INVARIANTS:
3469 **
3470 ** {H13506} The [SQL statement compiler] recognizes tokens of the forms
3471 **          "?", "?NNN", "$VVV", ":VVV", and "@VVV" as SQL parameters,
3472 **          where NNN is any sequence of one or more digits
3473 **          and where VVV is any sequence of one or more alphanumeric
3474 **          characters or "::" optionally followed by a string containing
3475 **          no spaces and contained within parentheses.
3476 **
3477 ** {H13509} The initial value of an SQL parameter is NULL.
3478 **
3479 ** {H13512} The index of an "?" SQL parameter is one larger than the
3480 **          largest index of SQL parameter to the left, or 1 if
3481 **          the "?" is the leftmost SQL parameter.
3482 **
3483 ** {H13515} The index of an "?NNN" SQL parameter is the integer NNN.
3484 **
3485 ** {H13518} The index of an ":VVV", "$VVV", or "@VVV" SQL parameter is
3486 **          the same as the index of leftmost occurrences of the same
3487 **          parameter, or one more than the largest index over all
3488 **          parameters to the left if this is the first occurrence
3489 **          of this parameter, or 1 if this is the leftmost parameter.
3490 **
3491 ** {H13521} The [SQL statement compiler] fails with an [SQLITE_RANGE]
3492 **          error if the index of an SQL parameter is less than 1
3493 **          or greater than the compile-time SQLITE_MAX_VARIABLE_NUMBER
3494 **          parameter.
3495 **
3496 ** {H13524} Calls to [sqlite3_bind_text | sqlite3_bind(S,N,V,...)]
3497 **          associate the value V with all SQL parameters having an
3498 **          index of N in the [prepared statement] S.
3499 **
3500 ** {H13527} Calls to [sqlite3_bind_text | sqlite3_bind(S,N,...)]
3501 **          override prior calls with the same values of S and N.
3502 **
3503 ** {H13530} Bindings established by [sqlite3_bind_text | sqlite3_bind(S,...)]
3504 **          persist across calls to [sqlite3_reset(S)].
3505 **
3506 ** {H13533} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
3507 **          [sqlite3_bind_text(S,N,V,L,D)], or
3508 **          [sqlite3_bind_text16(S,N,V,L,D)] SQLite binds the first L
3509 **          bytes of the BLOB or string pointed to by V, when L
3510 **          is non-negative.
3511 **
3512 ** {H13536} In calls to [sqlite3_bind_text(S,N,V,L,D)] or
3513 **          [sqlite3_bind_text16(S,N,V,L,D)] SQLite binds characters
3514 **          from V through the first zero character when L is negative.
3515 **
3516 ** {H13539} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
3517 **          [sqlite3_bind_text(S,N,V,L,D)], or
3518 **          [sqlite3_bind_text16(S,N,V,L,D)] when D is the special
3519 **          constant [SQLITE_STATIC], SQLite assumes that the value V
3520 **          is held in static unmanaged space that will not change
3521 **          during the lifetime of the binding.
3522 **
3523 ** {H13542} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
3524 **          [sqlite3_bind_text(S,N,V,L,D)], or
3525 **          [sqlite3_bind_text16(S,N,V,L,D)] when D is the special
3526 **          constant [SQLITE_TRANSIENT], the routine makes a
3527 **          private copy of the value V before it returns.
3528 **
3529 ** {H13545} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
3530 **          [sqlite3_bind_text(S,N,V,L,D)], or
3531 **          [sqlite3_bind_text16(S,N,V,L,D)] when D is a pointer to
3532 **          a function, SQLite invokes that function to destroy the
3533 **          value V after it has finished using the value V.
3534 **
3535 ** {H13548} In calls to [sqlite3_bind_zeroblob(S,N,V,L)] the value bound
3536 **          is a BLOB of L bytes, or a zero-length BLOB if L is negative.
3537 **
3538 ** {H13551} In calls to [sqlite3_bind_value(S,N,V)] the V argument may
3539 **          be either a [protected sqlite3_value] object or an
3540 **          [unprotected sqlite3_value] object.
3541 */
3542 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3543 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3544 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3545 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3546 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3547 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3548 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3549 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3550 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3551
3552 /*
3553 ** CAPI3REF: Number Of SQL Parameters {H13600} <S70300>
3554 **
3555 ** This routine can be used to find the number of [SQL parameters]
3556 ** in a [prepared statement].  SQL parameters are tokens of the
3557 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3558 ** placeholders for values that are [sqlite3_bind_blob | bound]
3559 ** to the parameters at a later time.
3560 **
3561 ** This routine actually returns the index of the largest (rightmost)
3562 ** parameter. For all forms except ?NNN, this will correspond to the
3563 ** number of unique parameters.  If parameters of the ?NNN are used,
3564 ** there may be gaps in the list.
3565 **
3566 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3567 ** [sqlite3_bind_parameter_name()], and
3568 ** [sqlite3_bind_parameter_index()].
3569 **
3570 ** INVARIANTS:
3571 **
3572 ** {H13601} The [sqlite3_bind_parameter_count(S)] interface returns
3573 **          the largest index of all SQL parameters in the
3574 **          [prepared statement] S, or 0 if S contains no SQL parameters.
3575 */
3576 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3577
3578 /*
3579 ** CAPI3REF: Name Of A Host Parameter {H13620} <S70300>
3580 **
3581 ** This routine returns a pointer to the name of the n-th
3582 ** [SQL parameter] in a [prepared statement].
3583 ** SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3584 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3585 ** respectively.
3586 ** In other words, the initial ":" or "$" or "@" or "?"
3587 ** is included as part of the name.
3588 ** Parameters of the form "?" without a following integer have no name
3589 ** and are also referred to as "anonymous parameters".
3590 **
3591 ** The first host parameter has an index of 1, not 0.
3592 **
3593 ** If the value n is out of range or if the n-th parameter is
3594 ** nameless, then NULL is returned.  The returned string is
3595 ** always in UTF-8 encoding even if the named parameter was
3596 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3597 ** [sqlite3_prepare16_v2()].
3598 **
3599 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3600 ** [sqlite3_bind_parameter_count()], and
3601 ** [sqlite3_bind_parameter_index()].
3602 **
3603 ** INVARIANTS:
3604 **
3605 ** {H13621} The [sqlite3_bind_parameter_name(S,N)] interface returns
3606 **          a UTF-8 rendering of the name of the SQL parameter in
3607 **          the [prepared statement] S having index N, or
3608 **          NULL if there is no SQL parameter with index N or if the
3609 **          parameter with index N is an anonymous parameter "?".
3610 */
3611 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3612
3613 /*
3614 ** CAPI3REF: Index Of A Parameter With A Given Name {H13640} <S70300>
3615 **
3616 ** Return the index of an SQL parameter given its name.  The
3617 ** index value returned is suitable for use as the second
3618 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  A zero
3619 ** is returned if no matching parameter is found.  The parameter
3620 ** name must be given in UTF-8 even if the original statement
3621 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3622 **
3623 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3624 ** [sqlite3_bind_parameter_count()], and
3625 ** [sqlite3_bind_parameter_index()].
3626 **
3627 ** INVARIANTS:
3628 **
3629 ** {H13641} The [sqlite3_bind_parameter_index(S,N)] interface returns
3630 **          the index of SQL parameter in the [prepared statement]
3631 **          S whose name matches the UTF-8 string N, or 0 if there is
3632 **          no match.
3633 */
3634 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3635
3636 /*
3637 ** CAPI3REF: Reset All Bindings On A Prepared Statement {H13660} <S70300>
3638 **
3639 ** Contrary to the intuition of many, [sqlite3_reset()] does not reset
3640 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3641 ** Use this routine to reset all host parameters to NULL.
3642 **
3643 ** INVARIANTS:
3644 **
3645 ** {H13661} The [sqlite3_clear_bindings(S)] interface resets all SQL
3646 **          parameter bindings in the [prepared statement] S back to NULL.
3647 */
3648 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3649
3650 /*
3651 ** CAPI3REF: Number Of Columns In A Result Set {H13710} <S10700>
3652 **
3653 ** Return the number of columns in the result set returned by the
3654 ** [prepared statement]. This routine returns 0 if pStmt is an SQL
3655 ** statement that does not return data (for example an [UPDATE]).
3656 **
3657 ** INVARIANTS:
3658 **
3659 ** {H13711} The [sqlite3_column_count(S)] interface returns the number of
3660 **          columns in the result set generated by the [prepared statement] S,
3661 **          or 0 if S does not generate a result set.
3662 */
3663 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3664
3665 /*
3666 ** CAPI3REF: Column Names In A Result Set {H13720} <S10700>
3667 **
3668 ** These routines return the name assigned to a particular column
3669 ** in the result set of a [SELECT] statement.  The sqlite3_column_name()
3670 ** interface returns a pointer to a zero-terminated UTF-8 string
3671 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3672 ** UTF-16 string.  The first parameter is the [prepared statement]
3673 ** that implements the [SELECT] statement. The second parameter is the
3674 ** column number.  The leftmost column is number 0.
3675 **
3676 ** The returned string pointer is valid until either the [prepared statement]
3677 ** is destroyed by [sqlite3_finalize()] or until the next call to
3678 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3679 **
3680 ** If sqlite3_malloc() fails during the processing of either routine
3681 ** (for example during a conversion from UTF-8 to UTF-16) then a
3682 ** NULL pointer is returned.
3683 **
3684 ** The name of a result column is the value of the "AS" clause for
3685 ** that column, if there is an AS clause.  If there is no AS clause
3686 ** then the name of the column is unspecified and may change from
3687 ** one release of SQLite to the next.
3688 **
3689 ** INVARIANTS:
3690 **
3691 ** {H13721} A successful invocation of the [sqlite3_column_name(S,N)]
3692 **          interface returns the name of the Nth column (where 0 is
3693 **          the leftmost column) for the result set of the
3694 **          [prepared statement] S as a zero-terminated UTF-8 string.
3695 **
3696 ** {H13723} A successful invocation of the [sqlite3_column_name16(S,N)]
3697 **          interface returns the name of the Nth column (where 0 is
3698 **          the leftmost column) for the result set of the
3699 **          [prepared statement] S as a zero-terminated UTF-16 string
3700 **          in the native byte order.
3701 **
3702 ** {H13724} The [sqlite3_column_name()] and [sqlite3_column_name16()]
3703 **          interfaces return a NULL pointer if they are unable to
3704 **          allocate memory to hold their normal return strings.
3705 **
3706 ** {H13725} If the N parameter to [sqlite3_column_name(S,N)] or
3707 **          [sqlite3_column_name16(S,N)] is out of range, then the
3708 **          interfaces return a NULL pointer.
3709 **
3710 ** {H13726} The strings returned by [sqlite3_column_name(S,N)] and
3711 **          [sqlite3_column_name16(S,N)] are valid until the next
3712 **          call to either routine with the same S and N parameters
3713 **          or until [sqlite3_finalize(S)] is called.
3714 **
3715 ** {H13727} When a result column of a [SELECT] statement contains
3716 **          an AS clause, the name of that column is the identifier
3717 **          to the right of the AS keyword.
3718 */
3719 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3720 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3721
3722 /*
3723 ** CAPI3REF: Source Of Data In A Query Result {H13740} <S10700>
3724 **
3725 ** These routines provide a means to determine what column of what
3726 ** table in which database a result of a [SELECT] statement comes from.
3727 ** The name of the database or table or column can be returned as
3728 ** either a UTF-8 or UTF-16 string.  The _database_ routines return
3729 ** the database name, the _table_ routines return the table name, and
3730 ** the origin_ routines return the column name.
3731 ** The returned string is valid until the [prepared statement] is destroyed
3732 ** using [sqlite3_finalize()] or until the same information is requested
3733 ** again in a different encoding.
3734 **
3735 ** The names returned are the original un-aliased names of the
3736 ** database, table, and column.
3737 **
3738 ** The first argument to the following calls is a [prepared statement].
3739 ** These functions return information about the Nth column returned by
3740 ** the statement, where N is the second function argument.
3741 **
3742 ** If the Nth column returned by the statement is an expression or
3743 ** subquery and is not a column value, then all of these functions return
3744 ** NULL.  These routine might also return NULL if a memory allocation error
3745 ** occurs.  Otherwise, they return the name of the attached database, table
3746 ** and column that query result column was extracted from.
3747 **
3748 ** As with all other SQLite APIs, those postfixed with "16" return
3749 ** UTF-16 encoded strings, the other functions return UTF-8. {END}
3750 **
3751 ** These APIs are only available if the library was compiled with the
3752 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
3753 **
3754 ** {A13751}
3755 ** If two or more threads call one or more of these routines against the same
3756 ** prepared statement and column at the same time then the results are
3757 ** undefined.
3758 **
3759 ** INVARIANTS:
3760 **
3761 ** {H13741} The [sqlite3_column_database_name(S,N)] interface returns either
3762 **          the UTF-8 zero-terminated name of the database from which the
3763 **          Nth result column of the [prepared statement] S is extracted,
3764 **          or NULL if the Nth column of S is a general expression
3765 **          or if unable to allocate memory to store the name.
3766 **
3767 ** {H13742} The [sqlite3_column_database_name16(S,N)] interface returns either
3768 **          the UTF-16 native byte order zero-terminated name of the database
3769 **          from which the Nth result column of the [prepared statement] S is
3770 **          extracted, or NULL if the Nth column of S is a general expression
3771 **          or if unable to allocate memory to store the name.
3772 **
3773 ** {H13743} The [sqlite3_column_table_name(S,N)] interface returns either
3774 **          the UTF-8 zero-terminated name of the table from which the
3775 **          Nth result column of the [prepared statement] S is extracted,
3776 **          or NULL if the Nth column of S is a general expression
3777 **          or if unable to allocate memory to store the name.
3778 **
3779 ** {H13744} The [sqlite3_column_table_name16(S,N)] interface returns either
3780 **          the UTF-16 native byte order zero-terminated name of the table
3781 **          from which the Nth result column of the [prepared statement] S is
3782 **          extracted, or NULL if the Nth column of S is a general expression
3783 **          or if unable to allocate memory to store the name.
3784 **
3785 ** {H13745} The [sqlite3_column_origin_name(S,N)] interface returns either
3786 **          the UTF-8 zero-terminated name of the table column from which the
3787 **          Nth result column of the [prepared statement] S is extracted,
3788 **          or NULL if the Nth column of S is a general expression
3789 **          or if unable to allocate memory to store the name.
3790 **
3791 ** {H13746} The [sqlite3_column_origin_name16(S,N)] interface returns either
3792 **          the UTF-16 native byte order zero-terminated name of the table
3793 **          column from which the Nth result column of the
3794 **          [prepared statement] S is extracted, or NULL if the Nth column
3795 **          of S is a general expression or if unable to allocate memory
3796 **          to store the name.
3797 **
3798 ** {H13748} The return values from
3799 **          [sqlite3_column_database_name | column metadata interfaces]
3800 **          are valid for the lifetime of the [prepared statement]
3801 **          or until the encoding is changed by another metadata
3802 **          interface call for the same prepared statement and column.
3803 **
3804 ** ASSUMPTIONS:
3805 **
3806 ** {A13751} If two or more threads call one or more
3807 **          [sqlite3_column_database_name | column metadata interfaces]
3808 **          for the same [prepared statement] and result column
3809 **          at the same time then the results are undefined.
3810 */
3811 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3812 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3813 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3814 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3815 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3816 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3817
3818 /*
3819 ** CAPI3REF: Declared Datatype Of A Query Result {H13760} <S10700>
3820 **
3821 ** The first parameter is a [prepared statement].
3822 ** If this statement is a [SELECT] statement and the Nth column of the
3823 ** returned result set of that [SELECT] is a table column (not an
3824 ** expression or subquery) then the declared type of the table
3825 ** column is returned.  If the Nth column of the result set is an
3826 ** expression or subquery, then a NULL pointer is returned.
3827 ** The returned string is always UTF-8 encoded. {END}
3828 **
3829 ** For example, given the database schema:
3830 **
3831 ** CREATE TABLE t1(c1 VARIANT);
3832 **
3833 ** and the following statement to be compiled:
3834 **
3835 ** SELECT c1 + 1, c1 FROM t1;
3836 **
3837 ** this routine would return the string "VARIANT" for the second result
3838 ** column (i==1), and a NULL pointer for the first result column (i==0).
3839 **
3840 ** SQLite uses dynamic run-time typing.  So just because a column
3841 ** is declared to contain a particular type does not mean that the
3842 ** data stored in that column is of the declared type.  SQLite is
3843 ** strongly typed, but the typing is dynamic not static.  Type
3844 ** is associated with individual values, not with the containers
3845 ** used to hold those values.
3846 **
3847 ** INVARIANTS:
3848 **
3849 ** {H13761}  A successful call to [sqlite3_column_decltype(S,N)] returns a
3850 **           zero-terminated UTF-8 string containing the declared datatype
3851 **           of the table column that appears as the Nth column (numbered
3852 **           from 0) of the result set to the [prepared statement] S.
3853 **
3854 ** {H13762}  A successful call to [sqlite3_column_decltype16(S,N)]
3855 **           returns a zero-terminated UTF-16 native byte order string
3856 **           containing the declared datatype of the table column that appears
3857 **           as the Nth column (numbered from 0) of the result set to the
3858 **           [prepared statement] S.
3859 **
3860 ** {H13763}  If N is less than 0 or N is greater than or equal to
3861 **           the number of columns in the [prepared statement] S,
3862 **           or if the Nth column of S is an expression or subquery rather
3863 **           than a table column, or if a memory allocation failure
3864 **           occurs during encoding conversions, then
3865 **           calls to [sqlite3_column_decltype(S,N)] or
3866 **           [sqlite3_column_decltype16(S,N)] return NULL.
3867 */
3868 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3869 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3870
3871 /*
3872 ** CAPI3REF: Evaluate An SQL Statement {H13200} <S10000>
3873 **
3874 ** After a [prepared statement] has been prepared using either
3875 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3876 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3877 ** must be called one or more times to evaluate the statement.
3878 **
3879 ** The details of the behavior of the sqlite3_step() interface depend
3880 ** on whether the statement was prepared using the newer "v2" interface
3881 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3882 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
3883 ** new "v2" interface is recommended for new applications but the legacy
3884 ** interface will continue to be supported.
3885 **
3886 ** In the legacy interface, the return value will be either [SQLITE_BUSY],
3887 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3888 ** With the "v2" interface, any of the other [result codes] or
3889 ** [extended result codes] might be returned as well.
3890 **
3891 ** [SQLITE_BUSY] means that the database engine was unable to acquire the
3892 ** database locks it needs to do its job.  If the statement is a [COMMIT]
3893 ** or occurs outside of an explicit transaction, then you can retry the
3894 ** statement.  If the statement is not a [COMMIT] and occurs within a
3895 ** explicit transaction then you should rollback the transaction before
3896 ** continuing.
3897 **
3898 ** [SQLITE_DONE] means that the statement has finished executing
3899 ** successfully.  sqlite3_step() should not be called again on this virtual
3900 ** machine without first calling [sqlite3_reset()] to reset the virtual
3901 ** machine back to its initial state.
3902 **
3903 ** If the SQL statement being executed returns any data, then [SQLITE_ROW]
3904 ** is returned each time a new row of data is ready for processing by the
3905 ** caller. The values may be accessed using the [column access functions].
3906 ** sqlite3_step() is called again to retrieve the next row of data.
3907 **
3908 ** [SQLITE_ERROR] means that a run-time error (such as a constraint
3909 ** violation) has occurred.  sqlite3_step() should not be called again on
3910 ** the VM. More information may be found by calling [sqlite3_errmsg()].
3911 ** With the legacy interface, a more specific error code (for example,
3912 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
3913 ** can be obtained by calling [sqlite3_reset()] on the
3914 ** [prepared statement].  In the "v2" interface,
3915 ** the more specific error code is returned directly by sqlite3_step().
3916 **
3917 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
3918 ** Perhaps it was called on a [prepared statement] that has
3919 ** already been [sqlite3_finalize | finalized] or on one that had
3920 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
3921 ** be the case that the same database connection is being used by two or
3922 ** more threads at the same moment in time.
3923 **
3924 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
3925 ** API always returns a generic error code, [SQLITE_ERROR], following any
3926 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
3927 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
3928 ** specific [error codes] that better describes the error.
3929 ** We admit that this is a goofy design.  The problem has been fixed
3930 ** with the "v2" interface.  If you prepare all of your SQL statements
3931 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
3932 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
3933 ** then the more specific [error codes] are returned directly
3934 ** by sqlite3_step().  The use of the "v2" interface is recommended.
3935 **
3936 ** INVARIANTS:
3937 **
3938 ** {H13202}  If the [prepared statement] S is ready to be run, then
3939 **           [sqlite3_step(S)] advances that prepared statement until
3940 **           completion or until it is ready to return another row of the
3941 **           result set, or until an [sqlite3_interrupt | interrupt]
3942 **           or a run-time error occurs.
3943 **
3944 ** {H15304}  When a call to [sqlite3_step(S)] causes the [prepared statement]
3945 **           S to run to completion, the function returns [SQLITE_DONE].
3946 **
3947 ** {H15306}  When a call to [sqlite3_step(S)] stops because it is ready to
3948 **           return another row of the result set, it returns [SQLITE_ROW].
3949 **
3950 ** {H15308}  If a call to [sqlite3_step(S)] encounters an
3951 **           [sqlite3_interrupt | interrupt] or a run-time error,
3952 **           it returns an appropriate error code that is not one of
3953 **           [SQLITE_OK], [SQLITE_ROW], or [SQLITE_DONE].
3954 **
3955 ** {H15310}  If an [sqlite3_interrupt | interrupt] or a run-time error
3956 **           occurs during a call to [sqlite3_step(S)]
3957 **           for a [prepared statement] S created using
3958 **           legacy interfaces [sqlite3_prepare()] or
3959 **           [sqlite3_prepare16()], then the function returns either
3960 **           [SQLITE_ERROR], [SQLITE_BUSY], or [SQLITE_MISUSE].
3961 */
3962 SQLITE_API int sqlite3_step(sqlite3_stmt*);
3963
3964 /*
3965 ** CAPI3REF: Number of columns in a result set {H13770} <S10700>
3966 **
3967 ** Returns the number of values in the current row of the result set.
3968 **
3969 ** INVARIANTS:
3970 **
3971 ** {H13771}  After a call to [sqlite3_step(S)] that returns [SQLITE_ROW],
3972 **           the [sqlite3_data_count(S)] routine will return the same value
3973 **           as the [sqlite3_column_count(S)] function.
3974 **
3975 ** {H13772}  After [sqlite3_step(S)] has returned any value other than
3976 **           [SQLITE_ROW] or before [sqlite3_step(S)] has been called on the
3977 **           [prepared statement] for the first time since it was
3978 **           [sqlite3_prepare | prepared] or [sqlite3_reset | reset],
3979 **           the [sqlite3_data_count(S)] routine returns zero.
3980 */
3981 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
3982
3983 /*
3984 ** CAPI3REF: Fundamental Datatypes {H10265} <S10110><S10120>
3985 ** KEYWORDS: SQLITE_TEXT
3986 **
3987 ** {H10266} Every value in SQLite has one of five fundamental datatypes:
3988 **
3989 ** <ul>
3990 ** <li> 64-bit signed integer
3991 ** <li> 64-bit IEEE floating point number
3992 ** <li> string
3993 ** <li> BLOB
3994 ** <li> NULL
3995 ** </ul> {END}
3996 **
3997 ** These constants are codes for each of those types.
3998 **
3999 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
4000 ** for a completely different meaning.  Software that links against both
4001 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
4002 ** SQLITE_TEXT.
4003 */
4004 #define SQLITE_INTEGER  1
4005 #define SQLITE_FLOAT    2
4006 #define SQLITE_BLOB     4
4007 #define SQLITE_NULL     5
4008 #ifdef SQLITE_TEXT
4009 # undef SQLITE_TEXT
4010 #else
4011 # define SQLITE_TEXT     3
4012 #endif
4013 #define SQLITE3_TEXT     3
4014
4015 /*
4016 ** CAPI3REF: Result Values From A Query {H13800} <S10700>
4017 ** KEYWORDS: {column access functions}
4018 **
4019 ** These routines form the "result set query" interface.
4020 **
4021 ** These routines return information about a single column of the current
4022 ** result row of a query.  In every case the first argument is a pointer
4023 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
4024 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
4025 ** and the second argument is the index of the column for which information
4026 ** should be returned.  The leftmost column of the result set has the index 0.
4027 **
4028 ** If the SQL statement does not currently point to a valid row, or if the
4029 ** column index is out of range, the result is undefined.
4030 ** These routines may only be called when the most recent call to
4031 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
4032 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
4033 ** If any of these routines are called after [sqlite3_reset()] or
4034 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
4035 ** something other than [SQLITE_ROW], the results are undefined.
4036 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
4037 ** are called from a different thread while any of these routines
4038 ** are pending, then the results are undefined.
4039 **
4040 ** The sqlite3_column_type() routine returns the
4041 ** [SQLITE_INTEGER | datatype code] for the initial data type
4042 ** of the result column.  The returned value is one of [SQLITE_INTEGER],
4043 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
4044 ** returned by sqlite3_column_type() is only meaningful if no type
4045 ** conversions have occurred as described below.  After a type conversion,
4046 ** the value returned by sqlite3_column_type() is undefined.  Future
4047 ** versions of SQLite may change the behavior of sqlite3_column_type()
4048 ** following a type conversion.
4049 **
4050 ** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
4051 ** routine returns the number of bytes in that BLOB or string.
4052 ** If the result is a UTF-16 string, then sqlite3_column_bytes() converts
4053 ** the string to UTF-8 and then returns the number of bytes.
4054 ** If the result is a numeric value then sqlite3_column_bytes() uses
4055 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
4056 ** the number of bytes in that string.
4057 ** The value returned does not include the zero terminator at the end
4058 ** of the string.  For clarity: the value returned is the number of
4059 ** bytes in the string, not the number of characters.
4060 **
4061 ** Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
4062 ** even empty strings, are always zero terminated.  The return
4063 ** value from sqlite3_column_blob() for a zero-length BLOB is an arbitrary
4064 ** pointer, possibly even a NULL pointer.
4065 **
4066 ** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
4067 ** but leaves the result in UTF-16 in native byte order instead of UTF-8.
4068 ** The zero terminator is not included in this count.
4069 **
4070 ** The object returned by [sqlite3_column_value()] is an
4071 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
4072 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
4073 ** If the [unprotected sqlite3_value] object returned by
4074 ** [sqlite3_column_value()] is used in any other way, including calls
4075 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
4076 ** or [sqlite3_value_bytes()], then the behavior is undefined.
4077 **
4078 ** These routines attempt to convert the value where appropriate.  For
4079 ** example, if the internal representation is FLOAT and a text result
4080 ** is requested, [sqlite3_snprintf()] is used internally to perform the
4081 ** conversion automatically.  The following table details the conversions
4082 ** that are applied:
4083 **
4084 ** <blockquote>
4085 ** <table border="1">
4086 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
4087 **
4088 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
4089 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
4090 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
4091 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
4092 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
4093 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
4094 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
4095 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
4096 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
4097 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
4098 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
4099 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
4100 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
4101 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
4102 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
4103 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
4104 ** </table>
4105 ** </blockquote>
4106 **
4107 ** The table above makes reference to standard C library functions atoi()
4108 ** and atof().  SQLite does not really use these functions.  It has its
4109 ** own equivalent internal routines.  The atoi() and atof() names are
4110 ** used in the table for brevity and because they are familiar to most
4111 ** C programmers.
4112 **
4113 ** Note that when type conversions occur, pointers returned by prior
4114 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
4115 ** sqlite3_column_text16() may be invalidated.
4116 ** Type conversions and pointer invalidations might occur
4117 ** in the following cases:
4118 **
4119 ** <ul>
4120 ** <li> The initial content is a BLOB and sqlite3_column_text() or
4121 **      sqlite3_column_text16() is called.  A zero-terminator might
4122 **      need to be added to the string.</li>
4123 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
4124 **      sqlite3_column_text16() is called.  The content must be converted
4125 **      to UTF-16.</li>
4126 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
4127 **      sqlite3_column_text() is called.  The content must be converted
4128 **      to UTF-8.</li>
4129 ** </ul>
4130 **
4131 ** Conversions between UTF-16be and UTF-16le are always done in place and do
4132 ** not invalidate a prior pointer, though of course the content of the buffer
4133 ** that the prior pointer points to will have been modified.  Other kinds
4134 ** of conversion are done in place when it is possible, but sometimes they
4135 ** are not possible and in those cases prior pointers are invalidated.
4136 **
4137 ** The safest and easiest to remember policy is to invoke these routines
4138 ** in one of the following ways:
4139 **
4140 ** <ul>
4141 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
4142 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
4143 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
4144 ** </ul>
4145 **
4146 ** In other words, you should call sqlite3_column_text(),
4147 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
4148 ** into the desired format, then invoke sqlite3_column_bytes() or
4149 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
4150 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
4151 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
4152 ** with calls to sqlite3_column_bytes().
4153 **
4154 ** The pointers returned are valid until a type conversion occurs as
4155 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
4156 ** [sqlite3_finalize()] is called.  The memory space used to hold strings
4157 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
4158 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
4159 ** [sqlite3_free()].
4160 **
4161 ** If a memory allocation error occurs during the evaluation of any
4162 ** of these routines, a default value is returned.  The default value
4163 ** is either the integer 0, the floating point number 0.0, or a NULL
4164 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
4165 ** [SQLITE_NOMEM].
4166 **
4167 ** INVARIANTS:
4168 **
4169 ** {H13803} The [sqlite3_column_blob(S,N)] interface converts the
4170 **          Nth column in the current row of the result set for
4171 **          the [prepared statement] S into a BLOB and then returns a
4172 **          pointer to the converted value.
4173 **
4174 ** {H13806} The [sqlite3_column_bytes(S,N)] interface returns the
4175 **          number of bytes in the BLOB or string (exclusive of the
4176 **          zero terminator on the string) that was returned by the
4177 **          most recent call to [sqlite3_column_blob(S,N)] or
4178 **          [sqlite3_column_text(S,N)].
4179 **
4180 ** {H13809} The [sqlite3_column_bytes16(S,N)] interface returns the
4181 **          number of bytes in the string (exclusive of the
4182 **          zero terminator on the string) that was returned by the
4183 **          most recent call to [sqlite3_column_text16(S,N)].
4184 **
4185 ** {H13812} The [sqlite3_column_double(S,N)] interface converts the
4186 **          Nth column in the current row of the result set for the
4187 **          [prepared statement] S into a floating point value and
4188 **          returns a copy of that value.
4189 **
4190 ** {H13815} The [sqlite3_column_int(S,N)] interface converts the
4191 **          Nth column in the current row of the result set for the
4192 **          [prepared statement] S into a 64-bit signed integer and
4193 **          returns the lower 32 bits of that integer.
4194 **
4195 ** {H13818} The [sqlite3_column_int64(S,N)] interface converts the
4196 **          Nth column in the current row of the result set for the
4197 **          [prepared statement] S into a 64-bit signed integer and
4198 **          returns a copy of that integer.
4199 **
4200 ** {H13821} The [sqlite3_column_text(S,N)] interface converts the
4201 **          Nth column in the current row of the result set for
4202 **          the [prepared statement] S into a zero-terminated UTF-8
4203 **          string and returns a pointer to that string.
4204 **
4205 ** {H13824} The [sqlite3_column_text16(S,N)] interface converts the
4206 **          Nth column in the current row of the result set for the
4207 **          [prepared statement] S into a zero-terminated 2-byte
4208 **          aligned UTF-16 native byte order string and returns
4209 **          a pointer to that string.
4210 **
4211 ** {H13827} The [sqlite3_column_type(S,N)] interface returns
4212 **          one of [SQLITE_NULL], [SQLITE_INTEGER], [SQLITE_FLOAT],
4213 **          [SQLITE_TEXT], or [SQLITE_BLOB] as appropriate for
4214 **          the Nth column in the current row of the result set for
4215 **          the [prepared statement] S.
4216 **
4217 ** {H13830} The [sqlite3_column_value(S,N)] interface returns a
4218 **          pointer to an [unprotected sqlite3_value] object for the
4219 **          Nth column in the current row of the result set for
4220 **          the [prepared statement] S.
4221 */
4222 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
4223 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
4224 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
4225 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
4226 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
4227 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
4228 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
4229 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
4230 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
4231 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
4232
4233 /*
4234 ** CAPI3REF: Destroy A Prepared Statement Object {H13300} <S70300><S30100>
4235 **
4236 ** The sqlite3_finalize() function is called to delete a [prepared statement].
4237 ** If the statement was executed successfully or not executed at all, then
4238 ** SQLITE_OK is returned. If execution of the statement failed then an
4239 ** [error code] or [extended error code] is returned.
4240 **
4241 ** This routine can be called at any point during the execution of the
4242 ** [prepared statement].  If the virtual machine has not
4243 ** completed execution when this routine is called, that is like
4244 ** encountering an error or an [sqlite3_interrupt | interrupt].
4245 ** Incomplete updates may be rolled back and transactions canceled,
4246 ** depending on the circumstances, and the
4247 ** [error code] returned will be [SQLITE_ABORT].
4248 **
4249 ** INVARIANTS:
4250 **
4251 ** {H11302} The [sqlite3_finalize(S)] interface destroys the
4252 **          [prepared statement] S and releases all
4253 **          memory and file resources held by that object.
4254 **
4255 ** {H11304} If the most recent call to [sqlite3_step(S)] for the
4256 **          [prepared statement] S returned an error,
4257 **          then [sqlite3_finalize(S)] returns that same error.
4258 */
4259 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
4260
4261 /*
4262 ** CAPI3REF: Reset A Prepared Statement Object {H13330} <S70300>
4263 **
4264 ** The sqlite3_reset() function is called to reset a [prepared statement]
4265 ** object back to its initial state, ready to be re-executed.
4266 ** Any SQL statement variables that had values bound to them using
4267 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
4268 ** Use [sqlite3_clear_bindings()] to reset the bindings.
4269 **
4270 ** {H11332} The [sqlite3_reset(S)] interface resets the [prepared statement] S
4271 **          back to the beginning of its program.
4272 **
4273 ** {H11334} If the most recent call to [sqlite3_step(S)] for the
4274 **          [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
4275 **          or if [sqlite3_step(S)] has never before been called on S,
4276 **          then [sqlite3_reset(S)] returns [SQLITE_OK].
4277 **
4278 ** {H11336} If the most recent call to [sqlite3_step(S)] for the
4279 **          [prepared statement] S indicated an error, then
4280 **          [sqlite3_reset(S)] returns an appropriate [error code].
4281 **
4282 ** {H11338} The [sqlite3_reset(S)] interface does not change the values
4283 **          of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
4284 */
4285 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
4286
4287 /*
4288 ** CAPI3REF: Create Or Redefine SQL Functions {H16100} <S20200>
4289 ** KEYWORDS: {function creation routines}
4290 ** KEYWORDS: {application-defined SQL function}
4291 ** KEYWORDS: {application-defined SQL functions}
4292 **
4293 ** These two functions (collectively known as "function creation routines")
4294 ** are used to add SQL functions or aggregates or to redefine the behavior
4295 ** of existing SQL functions or aggregates.  The only difference between the
4296 ** two is that the second parameter, the name of the (scalar) function or
4297 ** aggregate, is encoded in UTF-8 for sqlite3_create_function() and UTF-16
4298 ** for sqlite3_create_function16().
4299 **
4300 ** The first parameter is the [database connection] to which the SQL
4301 ** function is to be added.  If a single program uses more than one database
4302 ** connection internally, then SQL functions must be added individually to
4303 ** each database connection.
4304 **
4305 ** The second parameter is the name of the SQL function to be created or
4306 ** redefined.  The length of the name is limited to 255 bytes, exclusive of
4307 ** the zero-terminator.  Note that the name length limit is in bytes, not
4308 ** characters.  Any attempt to create a function with a longer name
4309 ** will result in [SQLITE_ERROR] being returned.
4310 **
4311 ** The third parameter (nArg)
4312 ** is the number of arguments that the SQL function or
4313 ** aggregate takes. If this parameter is negative, then the SQL function or
4314 ** aggregate may take any number of arguments.
4315 **
4316 ** The fourth parameter, eTextRep, specifies what
4317 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4318 ** its parameters.  Any SQL function implementation should be able to work
4319 ** work with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
4320 ** more efficient with one encoding than another.  It is allowed to
4321 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
4322 ** times with the same function but with different values of eTextRep.
4323 ** When multiple implementations of the same function are available, SQLite
4324 ** will pick the one that involves the least amount of data conversion.
4325 ** If there is only a single implementation which does not care what text
4326 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
4327 **
4328 ** The fifth parameter is an arbitrary pointer.  The implementation of the
4329 ** function can gain access to this pointer using [sqlite3_user_data()].
4330 **
4331 ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
4332 ** pointers to C-language functions that implement the SQL function or
4333 ** aggregate. A scalar SQL function requires an implementation of the xFunc
4334 ** callback only, NULL pointers should be passed as the xStep and xFinal
4335 ** parameters. An aggregate SQL function requires an implementation of xStep
4336 ** and xFinal and NULL should be passed for xFunc. To delete an existing
4337 ** SQL function or aggregate, pass NULL for all three function callbacks.
4338 **
4339 ** It is permitted to register multiple implementations of the same
4340 ** functions with the same name but with either differing numbers of
4341 ** arguments or differing preferred text encodings.  SQLite will use
4342 ** the implementation most closely matches the way in which the
4343 ** SQL function is used.  A function implementation with a non-negative
4344 ** nArg parameter is a better match than a function implementation with
4345 ** a negative nArg.  A function where the preferred text encoding
4346 ** matches the database encoding is a better
4347 ** match than a function where the encoding is different.  
4348 ** A function where the encoding difference is between UTF16le and UTF16be
4349 ** is a closer match than a function where the encoding difference is
4350 ** between UTF8 and UTF16.
4351 **
4352 ** Built-in functions may be overloaded by new application-defined functions.
4353 ** The first application-defined function with a given name overrides all
4354 ** built-in functions in the same [database connection] with the same name.
4355 ** Subsequent application-defined functions of the same name only override 
4356 ** prior application-defined functions that are an exact match for the
4357 ** number of parameters and preferred encoding.
4358 **
4359 ** An application-defined function is permitted to call other
4360 ** SQLite interfaces.  However, such calls must not
4361 ** close the database connection nor finalize or reset the prepared
4362 ** statement in which the function is running.
4363 **
4364 ** INVARIANTS:
4365 **
4366 ** {H16103} The [sqlite3_create_function16(D,X,...)] interface shall behave
4367 **          as [sqlite3_create_function(D,X,...)] in every way except that it
4368 **          interprets the X argument as zero-terminated UTF-16
4369 **          native byte order instead of as zero-terminated UTF-8.
4370 **
4371 ** {H16106} A successful invocation of the
4372 **          [sqlite3_create_function(D,X,N,E,...)] interface shall register
4373 **          or replaces callback functions in the [database connection] D
4374 **          used to implement the SQL function named X with N parameters
4375 **          and having a preferred text encoding of E.
4376 **
4377 ** {H16109} A successful call to [sqlite3_create_function(D,X,N,E,P,F,S,L)]
4378 **          shall replace the P, F, S, and L values from any prior calls with
4379 **          the same D, X, N, and E values.
4380 **
4381 ** {H16112} The [sqlite3_create_function(D,X,...)] interface shall fail
4382 **          if the SQL function name X is
4383 **          longer than 255 bytes exclusive of the zero terminator.
4384 **
4385 ** {H16118} The [sqlite3_create_function(D,X,N,E,P,F,S,L)] interface
4386 **          shall fail unless either F is NULL and S and L are non-NULL or
4387 ***         F is non-NULL and S and L are NULL.
4388 **
4389 ** {H16121} The [sqlite3_create_function(D,...)] interface shall fails with an
4390 **          error code of [SQLITE_BUSY] if there exist [prepared statements]
4391 **          associated with the [database connection] D.
4392 **
4393 ** {H16124} The [sqlite3_create_function(D,X,N,...)] interface shall fail with
4394 **          an error code of [SQLITE_ERROR] if parameter N is less
4395 **          than -1 or greater than 127.
4396 **
4397 ** {H16127} When N is non-negative, the [sqlite3_create_function(D,X,N,...)]
4398 **          interface shall register callbacks to be invoked for the
4399 **          SQL function
4400 **          named X when the number of arguments to the SQL function is
4401 **          exactly N.
4402 **
4403 ** {H16130} When N is -1, the [sqlite3_create_function(D,X,N,...)]
4404 **          interface shall register callbacks to be invoked for the SQL
4405 **          function named X with any number of arguments.
4406 **
4407 ** {H16133} When calls to [sqlite3_create_function(D,X,N,...)]
4408 **          specify multiple implementations of the same function X
4409 **          and when one implementation has N>=0 and the other has N=(-1)
4410 **          the implementation with a non-zero N shall be preferred.
4411 **
4412 ** {H16136} When calls to [sqlite3_create_function(D,X,N,E,...)]
4413 **          specify multiple implementations of the same function X with
4414 **          the same number of arguments N but with different
4415 **          encodings E, then the implementation where E matches the
4416 **          database encoding shall preferred.
4417 **
4418 ** {H16139} For an aggregate SQL function created using
4419 **          [sqlite3_create_function(D,X,N,E,P,0,S,L)] the finalizer
4420 **          function L shall always be invoked exactly once if the
4421 **          step function S is called one or more times.
4422 **
4423 ** {H16142} When SQLite invokes either the xFunc or xStep function of
4424 **          an application-defined SQL function or aggregate created
4425 **          by [sqlite3_create_function()] or [sqlite3_create_function16()],
4426 **          then the array of [sqlite3_value] objects passed as the
4427 **          third parameter shall be [protected sqlite3_value] objects.
4428 */
4429 SQLITE_API int sqlite3_create_function(
4430   sqlite3 *db,
4431   const char *zFunctionName,
4432   int nArg,
4433   int eTextRep,
4434   void *pApp,
4435   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4436   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4437   void (*xFinal)(sqlite3_context*)
4438 );
4439 SQLITE_API int sqlite3_create_function16(
4440   sqlite3 *db,
4441   const void *zFunctionName,
4442   int nArg,
4443   int eTextRep,
4444   void *pApp,
4445   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4446   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4447   void (*xFinal)(sqlite3_context*)
4448 );
4449
4450 /*
4451 ** CAPI3REF: Text Encodings {H10267} <S50200> <H16100>
4452 **
4453 ** These constant define integer codes that represent the various
4454 ** text encodings supported by SQLite.
4455 */
4456 #define SQLITE_UTF8           1
4457 #define SQLITE_UTF16LE        2
4458 #define SQLITE_UTF16BE        3
4459 #define SQLITE_UTF16          4    /* Use native byte order */
4460 #define SQLITE_ANY            5    /* sqlite3_create_function only */
4461 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
4462
4463 /*
4464 ** CAPI3REF: Deprecated Functions
4465 ** DEPRECATED
4466 **
4467 ** These functions are [deprecated].  In order to maintain
4468 ** backwards compatibility with older code, these functions continue 
4469 ** to be supported.  However, new applications should avoid
4470 ** the use of these functions.  To help encourage people to avoid
4471 ** using these functions, we are not going to tell you want they do.
4472 */
4473 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
4474 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
4475 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4476 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
4477 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
4478 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
4479
4480 /*
4481 ** CAPI3REF: Obtaining SQL Function Parameter Values {H15100} <S20200>
4482 **
4483 ** The C-language implementation of SQL functions and aggregates uses
4484 ** this set of interface routines to access the parameter values on
4485 ** the function or aggregate.
4486 **
4487 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4488 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4489 ** define callbacks that implement the SQL functions and aggregates.
4490 ** The 4th parameter to these callbacks is an array of pointers to
4491 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
4492 ** each parameter to the SQL function.  These routines are used to
4493 ** extract values from the [sqlite3_value] objects.
4494 **
4495 ** These routines work only with [protected sqlite3_value] objects.
4496 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4497 ** object results in undefined behavior.
4498 **
4499 ** These routines work just like the corresponding [column access functions]
4500 ** except that  these routines take a single [protected sqlite3_value] object
4501 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4502 **
4503 ** The sqlite3_value_text16() interface extracts a UTF-16 string
4504 ** in the native byte-order of the host machine.  The
4505 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4506 ** extract UTF-16 strings as big-endian and little-endian respectively.
4507 **
4508 ** The sqlite3_value_numeric_type() interface attempts to apply
4509 ** numeric affinity to the value.  This means that an attempt is
4510 ** made to convert the value to an integer or floating point.  If
4511 ** such a conversion is possible without loss of information (in other
4512 ** words, if the value is a string that looks like a number)
4513 ** then the conversion is performed.  Otherwise no conversion occurs.
4514 ** The [SQLITE_INTEGER | datatype] after conversion is returned.
4515 **
4516 ** Please pay particular attention to the fact that the pointer returned
4517 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4518 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4519 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4520 ** or [sqlite3_value_text16()].
4521 **
4522 ** These routines must be called from the same thread as
4523 ** the SQL function that supplied the [sqlite3_value*] parameters.
4524 **
4525 ** INVARIANTS:
4526 **
4527 ** {H15103} The [sqlite3_value_blob(V)] interface converts the
4528 **          [protected sqlite3_value] object V into a BLOB and then
4529 **          returns a pointer to the converted value.
4530 **
4531 ** {H15106} The [sqlite3_value_bytes(V)] interface returns the
4532 **          number of bytes in the BLOB or string (exclusive of the
4533 **          zero terminator on the string) that was returned by the
4534 **          most recent call to [sqlite3_value_blob(V)] or
4535 **          [sqlite3_value_text(V)].
4536 **
4537 ** {H15109} The [sqlite3_value_bytes16(V)] interface returns the
4538 **          number of bytes in the string (exclusive of the
4539 **          zero terminator on the string) that was returned by the
4540 **          most recent call to [sqlite3_value_text16(V)],
4541 **          [sqlite3_value_text16be(V)], or [sqlite3_value_text16le(V)].
4542 **
4543 ** {H15112} The [sqlite3_value_double(V)] interface converts the
4544 **          [protected sqlite3_value] object V into a floating point value and
4545 **          returns a copy of that value.
4546 **
4547 ** {H15115} The [sqlite3_value_int(V)] interface converts the
4548 **          [protected sqlite3_value] object V into a 64-bit signed integer and
4549 **          returns the lower 32 bits of that integer.
4550 **
4551 ** {H15118} The [sqlite3_value_int64(V)] interface converts the
4552 **          [protected sqlite3_value] object V into a 64-bit signed integer and
4553 **          returns a copy of that integer.
4554 **
4555 ** {H15121} The [sqlite3_value_text(V)] interface converts the
4556 **          [protected sqlite3_value] object V into a zero-terminated UTF-8
4557 **          string and returns a pointer to that string.
4558 **
4559 ** {H15124} The [sqlite3_value_text16(V)] interface converts the
4560 **          [protected sqlite3_value] object V into a zero-terminated 2-byte
4561 **          aligned UTF-16 native byte order
4562 **          string and returns a pointer to that string.
4563 **
4564 ** {H15127} The [sqlite3_value_text16be(V)] interface converts the
4565 **          [protected sqlite3_value] object V into a zero-terminated 2-byte
4566 **          aligned UTF-16 big-endian
4567 **          string and returns a pointer to that string.
4568 **
4569 ** {H15130} The [sqlite3_value_text16le(V)] interface converts the
4570 **          [protected sqlite3_value] object V into a zero-terminated 2-byte
4571 **          aligned UTF-16 little-endian
4572 **          string and returns a pointer to that string.
4573 **
4574 ** {H15133} The [sqlite3_value_type(V)] interface returns
4575 **          one of [SQLITE_NULL], [SQLITE_INTEGER], [SQLITE_FLOAT],
4576 **          [SQLITE_TEXT], or [SQLITE_BLOB] as appropriate for
4577 **          the [sqlite3_value] object V.
4578 **
4579 ** {H15136} The [sqlite3_value_numeric_type(V)] interface converts
4580 **          the [protected sqlite3_value] object V into either an integer or
4581 **          a floating point value if it can do so without loss of
4582 **          information, and returns one of [SQLITE_NULL],
4583 **          [SQLITE_INTEGER], [SQLITE_FLOAT], [SQLITE_TEXT], or
4584 **          [SQLITE_BLOB] as appropriate for the
4585 **          [protected sqlite3_value] object V after the conversion attempt.
4586 */
4587 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4588 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4589 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4590 SQLITE_API double sqlite3_value_double(sqlite3_value*);
4591 SQLITE_API int sqlite3_value_int(sqlite3_value*);
4592 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4593 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4594 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4595 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4596 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4597 SQLITE_API int sqlite3_value_type(sqlite3_value*);
4598 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4599
4600 /*
4601 ** CAPI3REF: Obtain Aggregate Function Context {H16210} <S20200>
4602 **
4603 ** The implementation of aggregate SQL functions use this routine to allocate
4604 ** a structure for storing their state.
4605 **
4606 ** The first time the sqlite3_aggregate_context() routine is called for a
4607 ** particular aggregate, SQLite allocates nBytes of memory, zeroes out that
4608 ** memory, and returns a pointer to it. On second and subsequent calls to
4609 ** sqlite3_aggregate_context() for the same aggregate function index,
4610 ** the same buffer is returned. The implementation of the aggregate can use
4611 ** the returned buffer to accumulate data.
4612 **
4613 ** SQLite automatically frees the allocated buffer when the aggregate
4614 ** query concludes.
4615 **
4616 ** The first parameter should be a copy of the
4617 ** [sqlite3_context | SQL function context] that is the first parameter
4618 ** to the callback routine that implements the aggregate function.
4619 **
4620 ** This routine must be called from the same thread in which
4621 ** the aggregate SQL function is running.
4622 **
4623 ** INVARIANTS:
4624 **
4625 ** {H16211} The first invocation of [sqlite3_aggregate_context(C,N)] for
4626 **          a particular instance of an aggregate function (for a particular
4627 **          context C) causes SQLite to allocate N bytes of memory,
4628 **          zero that memory, and return a pointer to the allocated memory.
4629 **
4630 ** {H16213} If a memory allocation error occurs during
4631 **          [sqlite3_aggregate_context(C,N)] then the function returns 0.
4632 **
4633 ** {H16215} Second and subsequent invocations of
4634 **          [sqlite3_aggregate_context(C,N)] for the same context pointer C
4635 **          ignore the N parameter and return a pointer to the same
4636 **          block of memory returned by the first invocation.
4637 **
4638 ** {H16217} The memory allocated by [sqlite3_aggregate_context(C,N)] is
4639 **          automatically freed on the next call to [sqlite3_reset()]
4640 **          or [sqlite3_finalize()] for the [prepared statement] containing
4641 **          the aggregate function associated with context C.
4642 */
4643 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4644
4645 /*
4646 ** CAPI3REF: User Data For Functions {H16240} <S20200>
4647 **
4648 ** The sqlite3_user_data() interface returns a copy of
4649 ** the pointer that was the pUserData parameter (the 5th parameter)
4650 ** of the [sqlite3_create_function()]
4651 ** and [sqlite3_create_function16()] routines that originally
4652 ** registered the application defined function. {END}
4653 **
4654 ** This routine must be called from the same thread in which
4655 ** the application-defined function is running.
4656 **
4657 ** INVARIANTS:
4658 **
4659 ** {H16243} The [sqlite3_user_data(C)] interface returns a copy of the
4660 **          P pointer from the [sqlite3_create_function(D,X,N,E,P,F,S,L)]
4661 **          or [sqlite3_create_function16(D,X,N,E,P,F,S,L)] call that
4662 **          registered the SQL function associated with [sqlite3_context] C.
4663 */
4664 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4665
4666 /*
4667 ** CAPI3REF: Database Connection For Functions {H16250} <S60600><S20200>
4668 **
4669 ** The sqlite3_context_db_handle() interface returns a copy of
4670 ** the pointer to the [database connection] (the 1st parameter)
4671 ** of the [sqlite3_create_function()]
4672 ** and [sqlite3_create_function16()] routines that originally
4673 ** registered the application defined function.
4674 **
4675 ** INVARIANTS:
4676 **
4677 ** {H16253} The [sqlite3_context_db_handle(C)] interface returns a copy of the
4678 **          D pointer from the [sqlite3_create_function(D,X,N,E,P,F,S,L)]
4679 **          or [sqlite3_create_function16(D,X,N,E,P,F,S,L)] call that
4680 **          registered the SQL function associated with [sqlite3_context] C.
4681 */
4682 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4683
4684 /*
4685 ** CAPI3REF: Function Auxiliary Data {H16270} <S20200>
4686 **
4687 ** The following two functions may be used by scalar SQL functions to
4688 ** associate metadata with argument values. If the same value is passed to
4689 ** multiple invocations of the same SQL function during query execution, under
4690 ** some circumstances the associated metadata may be preserved. This may
4691 ** be used, for example, to add a regular-expression matching scalar
4692 ** function. The compiled version of the regular expression is stored as
4693 ** metadata associated with the SQL value passed as the regular expression
4694 ** pattern.  The compiled regular expression can be reused on multiple
4695 ** invocations of the same function so that the original pattern string
4696 ** does not need to be recompiled on each invocation.
4697 **
4698 ** The sqlite3_get_auxdata() interface returns a pointer to the metadata
4699 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4700 ** value to the application-defined function. If no metadata has been ever
4701 ** been set for the Nth argument of the function, or if the corresponding
4702 ** function parameter has changed since the meta-data was set,
4703 ** then sqlite3_get_auxdata() returns a NULL pointer.
4704 **
4705 ** The sqlite3_set_auxdata() interface saves the metadata
4706 ** pointed to by its 3rd parameter as the metadata for the N-th
4707 ** argument of the application-defined function.  Subsequent
4708 ** calls to sqlite3_get_auxdata() might return this data, if it has
4709 ** not been destroyed.
4710 ** If it is not NULL, SQLite will invoke the destructor
4711 ** function given by the 4th parameter to sqlite3_set_auxdata() on
4712 ** the metadata when the corresponding function parameter changes
4713 ** or when the SQL statement completes, whichever comes first.
4714 **
4715 ** SQLite is free to call the destructor and drop metadata on any
4716 ** parameter of any function at any time.  The only guarantee is that
4717 ** the destructor will be called before the metadata is dropped.
4718 **
4719 ** In practice, metadata is preserved between function calls for
4720 ** expressions that are constant at compile time. This includes literal
4721 ** values and SQL variables.
4722 **
4723 ** These routines must be called from the same thread in which
4724 ** the SQL function is running.
4725 **
4726 ** INVARIANTS:
4727 **
4728 ** {H16272} The [sqlite3_get_auxdata(C,N)] interface returns a pointer
4729 **          to metadata associated with the Nth parameter of the SQL function
4730 **          whose context is C, or NULL if there is no metadata associated
4731 **          with that parameter.
4732 **
4733 ** {H16274} The [sqlite3_set_auxdata(C,N,P,D)] interface assigns a metadata
4734 **          pointer P to the Nth parameter of the SQL function with context C.
4735 **
4736 ** {H16276} SQLite will invoke the destructor D with a single argument
4737 **          which is the metadata pointer P following a call to
4738 **          [sqlite3_set_auxdata(C,N,P,D)] when SQLite ceases to hold
4739 **          the metadata.
4740 **
4741 ** {H16277} SQLite ceases to hold metadata for an SQL function parameter
4742 **          when the value of that parameter changes.
4743 **
4744 ** {H16278} When [sqlite3_set_auxdata(C,N,P,D)] is invoked, the destructor
4745 **          is called for any prior metadata associated with the same function
4746 **          context C and parameter N.
4747 **
4748 ** {H16279} SQLite will call destructors for any metadata it is holding
4749 **          in a particular [prepared statement] S when either
4750 **          [sqlite3_reset(S)] or [sqlite3_finalize(S)] is called.
4751 */
4752 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4753 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4754
4755
4756 /*
4757 ** CAPI3REF: Constants Defining Special Destructor Behavior {H10280} <S30100>
4758 **
4759 ** These are special values for the destructor that is passed in as the
4760 ** final argument to routines like [sqlite3_result_blob()].  If the destructor
4761 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4762 ** and will never change.  It does not need to be destroyed.  The
4763 ** SQLITE_TRANSIENT value means that the content will likely change in
4764 ** the near future and that SQLite should make its own private copy of
4765 ** the content before returning.
4766 **
4767 ** The typedef is necessary to work around problems in certain
4768 ** C++ compilers.  See ticket #2191.
4769 */
4770 typedef void (*sqlite3_destructor_type)(void*);
4771 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4772 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4773
4774 /*
4775 ** CAPI3REF: Setting The Result Of An SQL Function {H16400} <S20200>
4776 **
4777 ** These routines are used by the xFunc or xFinal callbacks that
4778 ** implement SQL functions and aggregates.  See
4779 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4780 ** for additional information.
4781 **
4782 ** These functions work very much like the [parameter binding] family of
4783 ** functions used to bind values to host parameters in prepared statements.
4784 ** Refer to the [SQL parameter] documentation for additional information.
4785 **
4786 ** The sqlite3_result_blob() interface sets the result from
4787 ** an application-defined function to be the BLOB whose content is pointed
4788 ** to by the second parameter and which is N bytes long where N is the
4789 ** third parameter.
4790 **
4791 ** The sqlite3_result_zeroblob() interfaces set the result of
4792 ** the application-defined function to be a BLOB containing all zero
4793 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4794 **
4795 ** The sqlite3_result_double() interface sets the result from
4796 ** an application-defined function to be a floating point value specified
4797 ** by its 2nd argument.
4798 **
4799 ** The sqlite3_result_error() and sqlite3_result_error16() functions
4800 ** cause the implemented SQL function to throw an exception.
4801 ** SQLite uses the string pointed to by the
4802 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4803 ** as the text of an error message.  SQLite interprets the error
4804 ** message string from sqlite3_result_error() as UTF-8. SQLite
4805 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
4806 ** byte order.  If the third parameter to sqlite3_result_error()
4807 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4808 ** message all text up through the first zero character.
4809 ** If the third parameter to sqlite3_result_error() or
4810 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4811 ** bytes (not characters) from the 2nd parameter as the error message.
4812 ** The sqlite3_result_error() and sqlite3_result_error16()
4813 ** routines make a private copy of the error message text before
4814 ** they return.  Hence, the calling function can deallocate or
4815 ** modify the text after they return without harm.
4816 ** The sqlite3_result_error_code() function changes the error code
4817 ** returned by SQLite as a result of an error in a function.  By default,
4818 ** the error code is SQLITE_ERROR.  A subsequent call to sqlite3_result_error()
4819 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4820 **
4821 ** The sqlite3_result_toobig() interface causes SQLite to throw an error
4822 ** indicating that a string or BLOB is to long to represent.
4823 **
4824 ** The sqlite3_result_nomem() interface causes SQLite to throw an error
4825 ** indicating that a memory allocation failed.
4826 **
4827 ** The sqlite3_result_int() interface sets the return value
4828 ** of the application-defined function to be the 32-bit signed integer
4829 ** value given in the 2nd argument.
4830 ** The sqlite3_result_int64() interface sets the return value
4831 ** of the application-defined function to be the 64-bit signed integer
4832 ** value given in the 2nd argument.
4833 **
4834 ** The sqlite3_result_null() interface sets the return value
4835 ** of the application-defined function to be NULL.
4836 **
4837 ** The sqlite3_result_text(), sqlite3_result_text16(),
4838 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4839 ** set the return value of the application-defined function to be
4840 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4841 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4842 ** SQLite takes the text result from the application from
4843 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4844 ** If the 3rd parameter to the sqlite3_result_text* interfaces
4845 ** is negative, then SQLite takes result text from the 2nd parameter
4846 ** through the first zero character.
4847 ** If the 3rd parameter to the sqlite3_result_text* interfaces
4848 ** is non-negative, then as many bytes (not characters) of the text
4849 ** pointed to by the 2nd parameter are taken as the application-defined
4850 ** function result.
4851 ** If the 4th parameter to the sqlite3_result_text* interfaces
4852 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4853 ** function as the destructor on the text or BLOB result when it has
4854 ** finished using that result.
4855 ** If the 4th parameter to the sqlite3_result_text* interfaces or
4856 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4857 ** assumes that the text or BLOB result is in constant space and does not
4858 ** copy the it or call a destructor when it has finished using that result.
4859 ** If the 4th parameter to the sqlite3_result_text* interfaces
4860 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4861 ** then SQLite makes a copy of the result into space obtained from
4862 ** from [sqlite3_malloc()] before it returns.
4863 **
4864 ** The sqlite3_result_value() interface sets the result of
4865 ** the application-defined function to be a copy the
4866 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  The
4867 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4868 ** so that the [sqlite3_value] specified in the parameter may change or
4869 ** be deallocated after sqlite3_result_value() returns without harm.
4870 ** A [protected sqlite3_value] object may always be used where an
4871 ** [unprotected sqlite3_value] object is required, so either
4872 ** kind of [sqlite3_value] object can be used with this interface.
4873 **
4874 ** If these routines are called from within the different thread
4875 ** than the one containing the application-defined function that received
4876 ** the [sqlite3_context] pointer, the results are undefined.
4877 **
4878 ** INVARIANTS:
4879 **
4880 ** {H16403} The default return value from any SQL function is NULL.
4881 **
4882 ** {H16406} The [sqlite3_result_blob(C,V,N,D)] interface changes the
4883 **          return value of function C to be a BLOB that is N bytes
4884 **          in length and with content pointed to by V.
4885 **
4886 ** {H16409} The [sqlite3_result_double(C,V)] interface changes the
4887 **          return value of function C to be the floating point value V.
4888 **
4889 ** {H16412} The [sqlite3_result_error(C,V,N)] interface changes the return
4890 **          value of function C to be an exception with error code
4891 **          [SQLITE_ERROR] and a UTF-8 error message copied from V up to the
4892 **          first zero byte or until N bytes are read if N is positive.
4893 **
4894 ** {H16415} The [sqlite3_result_error16(C,V,N)] interface changes the return
4895 **          value of function C to be an exception with error code
4896 **          [SQLITE_ERROR] and a UTF-16 native byte order error message
4897 **          copied from V up to the first zero terminator or until N bytes
4898 **          are read if N is positive.
4899 **
4900 ** {H16418} The [sqlite3_result_error_toobig(C)] interface changes the return
4901 **          value of the function C to be an exception with error code
4902 **          [SQLITE_TOOBIG] and an appropriate error message.
4903 **
4904 ** {H16421} The [sqlite3_result_error_nomem(C)] interface changes the return
4905 **          value of the function C to be an exception with error code
4906 **          [SQLITE_NOMEM] and an appropriate error message.
4907 **
4908 ** {H16424} The [sqlite3_result_error_code(C,E)] interface changes the return
4909 **          value of the function C to be an exception with error code E.
4910 **          The error message text is unchanged.
4911 **
4912 ** {H16427} The [sqlite3_result_int(C,V)] interface changes the
4913 **          return value of function C to be the 32-bit integer value V.
4914 **
4915 ** {H16430} The [sqlite3_result_int64(C,V)] interface changes the
4916 **          return value of function C to be the 64-bit integer value V.
4917 **
4918 ** {H16433} The [sqlite3_result_null(C)] interface changes the
4919 **          return value of function C to be NULL.
4920 **
4921 ** {H16436} The [sqlite3_result_text(C,V,N,D)] interface changes the
4922 **          return value of function C to be the UTF-8 string
4923 **          V up to the first zero if N is negative
4924 **          or the first N bytes of V if N is non-negative.
4925 **
4926 ** {H16439} The [sqlite3_result_text16(C,V,N,D)] interface changes the
4927 **          return value of function C to be the UTF-16 native byte order
4928 **          string V up to the first zero if N is negative
4929 **          or the first N bytes of V if N is non-negative.
4930 **
4931 ** {H16442} The [sqlite3_result_text16be(C,V,N,D)] interface changes the
4932 **          return value of function C to be the UTF-16 big-endian
4933 **          string V up to the first zero if N is negative
4934 **          or the first N bytes or V if N is non-negative.
4935 **
4936 ** {H16445} The [sqlite3_result_text16le(C,V,N,D)] interface changes the
4937 **          return value of function C to be the UTF-16 little-endian
4938 **          string V up to the first zero if N is negative
4939 **          or the first N bytes of V if N is non-negative.
4940 **
4941 ** {H16448} The [sqlite3_result_value(C,V)] interface changes the
4942 **          return value of function C to be the [unprotected sqlite3_value]
4943 **          object V.
4944 **
4945 ** {H16451} The [sqlite3_result_zeroblob(C,N)] interface changes the
4946 **          return value of function C to be an N-byte BLOB of all zeros.
4947 **
4948 ** {H16454} The [sqlite3_result_error()] and [sqlite3_result_error16()]
4949 **          interfaces make a copy of their error message strings before
4950 **          returning.
4951 **
4952 ** {H16457} If the D destructor parameter to [sqlite3_result_blob(C,V,N,D)],
4953 **          [sqlite3_result_text(C,V,N,D)], [sqlite3_result_text16(C,V,N,D)],
4954 **          [sqlite3_result_text16be(C,V,N,D)], or
4955 **          [sqlite3_result_text16le(C,V,N,D)] is the constant [SQLITE_STATIC]
4956 **          then no destructor is ever called on the pointer V and SQLite
4957 **          assumes that V is immutable.
4958 **
4959 ** {H16460} If the D destructor parameter to [sqlite3_result_blob(C,V,N,D)],
4960 **          [sqlite3_result_text(C,V,N,D)], [sqlite3_result_text16(C,V,N,D)],
4961 **          [sqlite3_result_text16be(C,V,N,D)], or
4962 **          [sqlite3_result_text16le(C,V,N,D)] is the constant
4963 **          [SQLITE_TRANSIENT] then the interfaces makes a copy of the
4964 **          content of V and retains the copy.
4965 **
4966 ** {H16463} If the D destructor parameter to [sqlite3_result_blob(C,V,N,D)],
4967 **          [sqlite3_result_text(C,V,N,D)], [sqlite3_result_text16(C,V,N,D)],
4968 **          [sqlite3_result_text16be(C,V,N,D)], or
4969 **          [sqlite3_result_text16le(C,V,N,D)] is some value other than
4970 **          the constants [SQLITE_STATIC] and [SQLITE_TRANSIENT] then
4971 **          SQLite will invoke the destructor D with V as its only argument
4972 **          when it has finished with the V value.
4973 */
4974 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4975 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4976 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4977 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4978 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4979 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4980 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4981 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4982 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4983 SQLITE_API void sqlite3_result_null(sqlite3_context*);
4984 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4985 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4986 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4987 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4988 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4989 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4990
4991 /*
4992 ** CAPI3REF: Define New Collating Sequences {H16600} <S20300>
4993 **
4994 ** These functions are used to add new collation sequences to the
4995 ** [database connection] specified as the first argument.
4996 **
4997 ** The name of the new collation sequence is specified as a UTF-8 string
4998 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4999 ** and a UTF-16 string for sqlite3_create_collation16(). In all cases
5000 ** the name is passed as the second function argument.
5001 **
5002 ** The third argument may be one of the constants [SQLITE_UTF8],
5003 ** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied
5004 ** routine expects to be passed pointers to strings encoded using UTF-8,
5005 ** UTF-16 little-endian, or UTF-16 big-endian, respectively. The
5006 ** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that
5007 ** the routine expects pointers to 16-bit word aligned strings
5008 ** of UTF-16 in the native byte order of the host computer.
5009 **
5010 ** A pointer to the user supplied routine must be passed as the fifth
5011 ** argument.  If it is NULL, this is the same as deleting the collation
5012 ** sequence (so that SQLite cannot call it anymore).
5013 ** Each time the application supplied function is invoked, it is passed
5014 ** as its first parameter a copy of the void* passed as the fourth argument
5015 ** to sqlite3_create_collation() or sqlite3_create_collation16().
5016 **
5017 ** The remaining arguments to the application-supplied routine are two strings,
5018 ** each represented by a (length, data) pair and encoded in the encoding
5019 ** that was passed as the third argument when the collation sequence was
5020 ** registered. {END}  The application defined collation routine should
5021 ** return negative, zero or positive if the first string is less than,
5022 ** equal to, or greater than the second string. i.e. (STRING1 - STRING2).
5023 **
5024 ** The sqlite3_create_collation_v2() works like sqlite3_create_collation()
5025 ** except that it takes an extra argument which is a destructor for
5026 ** the collation.  The destructor is called when the collation is
5027 ** destroyed and is passed a copy of the fourth parameter void* pointer
5028 ** of the sqlite3_create_collation_v2().
5029 ** Collations are destroyed when they are overridden by later calls to the
5030 ** collation creation functions or when the [database connection] is closed
5031 ** using [sqlite3_close()].
5032 **
5033 ** INVARIANTS:
5034 **
5035 ** {H16603} A successful call to the
5036 **          [sqlite3_create_collation_v2(B,X,E,P,F,D)] interface
5037 **          registers function F as the comparison function used to
5038 **          implement collation X on the [database connection] B for
5039 **          databases having encoding E.
5040 **
5041 ** {H16604} SQLite understands the X parameter to
5042 **          [sqlite3_create_collation_v2(B,X,E,P,F,D)] as a zero-terminated
5043 **          UTF-8 string in which case is ignored for ASCII characters and
5044 **          is significant for non-ASCII characters.
5045 **
5046 ** {H16606} Successive calls to [sqlite3_create_collation_v2(B,X,E,P,F,D)]
5047 **          with the same values for B, X, and E, override prior values
5048 **          of P, F, and D.
5049 **
5050 ** {H16609} If the destructor D in [sqlite3_create_collation_v2(B,X,E,P,F,D)]
5051 **          is not NULL then it is called with argument P when the
5052 **          collating function is dropped by SQLite.
5053 **
5054 ** {H16612} A collating function is dropped when it is overloaded.
5055 **
5056 ** {H16615} A collating function is dropped when the database connection
5057 **          is closed using [sqlite3_close()].
5058 **
5059 ** {H16618} The pointer P in [sqlite3_create_collation_v2(B,X,E,P,F,D)]
5060 **          is passed through as the first parameter to the comparison
5061 **          function F for all subsequent invocations of F.
5062 **
5063 ** {H16621} A call to [sqlite3_create_collation(B,X,E,P,F)] is exactly
5064 **          the same as a call to [sqlite3_create_collation_v2()] with
5065 **          the same parameters and a NULL destructor.
5066 **
5067 ** {H16624} Following a [sqlite3_create_collation_v2(B,X,E,P,F,D)],
5068 **          SQLite uses the comparison function F for all text comparison
5069 **          operations on the [database connection] B on text values that
5070 **          use the collating sequence named X.
5071 **
5072 ** {H16627} The [sqlite3_create_collation16(B,X,E,P,F)] works the same
5073 **          as [sqlite3_create_collation(B,X,E,P,F)] except that the
5074 **          collation name X is understood as UTF-16 in native byte order
5075 **          instead of UTF-8.
5076 **
5077 ** {H16630} When multiple comparison functions are available for the same
5078 **          collating sequence, SQLite chooses the one whose text encoding
5079 **          requires the least amount of conversion from the default
5080 **          text encoding of the database.
5081 */
5082 SQLITE_API int sqlite3_create_collation(
5083   sqlite3*, 
5084   const char *zName, 
5085   int eTextRep, 
5086   void*,
5087   int(*xCompare)(void*,int,const void*,int,const void*)
5088 );
5089 SQLITE_API int sqlite3_create_collation_v2(
5090   sqlite3*, 
5091   const char *zName, 
5092   int eTextRep, 
5093   void*,
5094   int(*xCompare)(void*,int,const void*,int,const void*),
5095   void(*xDestroy)(void*)
5096 );
5097 SQLITE_API int sqlite3_create_collation16(
5098   sqlite3*, 
5099   const void *zName,
5100   int eTextRep, 
5101   void*,
5102   int(*xCompare)(void*,int,const void*,int,const void*)
5103 );
5104
5105 /*
5106 ** CAPI3REF: Collation Needed Callbacks {H16700} <S20300>
5107 **
5108 ** To avoid having to register all collation sequences before a database
5109 ** can be used, a single callback function may be registered with the
5110 ** [database connection] to be called whenever an undefined collation
5111 ** sequence is required.
5112 **
5113 ** If the function is registered using the sqlite3_collation_needed() API,
5114 ** then it is passed the names of undefined collation sequences as strings
5115 ** encoded in UTF-8. {H16703} If sqlite3_collation_needed16() is used,
5116 ** the names are passed as UTF-16 in machine native byte order.
5117 ** A call to either function replaces any existing callback.
5118 **
5119 ** When the callback is invoked, the first argument passed is a copy
5120 ** of the second argument to sqlite3_collation_needed() or
5121 ** sqlite3_collation_needed16().  The second argument is the database
5122 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
5123 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
5124 ** sequence function required.  The fourth parameter is the name of the
5125 ** required collation sequence.
5126 **
5127 ** The callback function should register the desired collation using
5128 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
5129 ** [sqlite3_create_collation_v2()].
5130 **
5131 ** INVARIANTS:
5132 **
5133 ** {H16702} A successful call to [sqlite3_collation_needed(D,P,F)]
5134 **          or [sqlite3_collation_needed16(D,P,F)] causes
5135 **          the [database connection] D to invoke callback F with first
5136 **          parameter P whenever it needs a comparison function for a
5137 **          collating sequence that it does not know about.
5138 **
5139 ** {H16704} Each successful call to [sqlite3_collation_needed()] or
5140 **          [sqlite3_collation_needed16()] overrides the callback registered
5141 **          on the same [database connection] by prior calls to either
5142 **          interface.
5143 **
5144 ** {H16706} The name of the requested collating function passed in the
5145 **          4th parameter to the callback is in UTF-8 if the callback
5146 **          was registered using [sqlite3_collation_needed()] and
5147 **          is in UTF-16 native byte order if the callback was
5148 **          registered using [sqlite3_collation_needed16()].
5149 */
5150 SQLITE_API int sqlite3_collation_needed(
5151   sqlite3*, 
5152   void*, 
5153   void(*)(void*,sqlite3*,int eTextRep,const char*)
5154 );
5155 SQLITE_API int sqlite3_collation_needed16(
5156   sqlite3*, 
5157   void*,
5158   void(*)(void*,sqlite3*,int eTextRep,const void*)
5159 );
5160
5161 /*
5162 ** Specify the key for an encrypted database.  This routine should be
5163 ** called right after sqlite3_open().
5164 **
5165 ** The code to implement this API is not available in the public release
5166 ** of SQLite.
5167 */
5168 SQLITE_API int sqlite3_key(
5169   sqlite3 *db,                   /* Database to be rekeyed */
5170   const void *pKey, int nKey     /* The key */
5171 );
5172
5173 /*
5174 ** Change the key on an open database.  If the current database is not
5175 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
5176 ** database is decrypted.
5177 **
5178 ** The code to implement this API is not available in the public release
5179 ** of SQLite.
5180 */
5181 SQLITE_API int sqlite3_rekey(
5182   sqlite3 *db,                   /* Database to be rekeyed */
5183   const void *pKey, int nKey     /* The new key */
5184 );
5185
5186 /*
5187 ** CAPI3REF: Suspend Execution For A Short Time {H10530} <S40410>
5188 **
5189 ** The sqlite3_sleep() function causes the current thread to suspend execution
5190 ** for at least a number of milliseconds specified in its parameter.
5191 **
5192 ** If the operating system does not support sleep requests with
5193 ** millisecond time resolution, then the time will be rounded up to
5194 ** the nearest second. The number of milliseconds of sleep actually
5195 ** requested from the operating system is returned.
5196 **
5197 ** SQLite implements this interface by calling the xSleep()
5198 ** method of the default [sqlite3_vfs] object.
5199 **
5200 ** INVARIANTS:
5201 **
5202 ** {H10533} The [sqlite3_sleep(M)] interface invokes the xSleep
5203 **          method of the default [sqlite3_vfs|VFS] in order to
5204 **          suspend execution of the current thread for at least
5205 **          M milliseconds.
5206 **
5207 ** {H10536} The [sqlite3_sleep(M)] interface returns the number of
5208 **          milliseconds of sleep actually requested of the operating
5209 **          system, which might be larger than the parameter M.
5210 */
5211 SQLITE_API int sqlite3_sleep(int);
5212
5213 /*
5214 ** CAPI3REF: Name Of The Folder Holding Temporary Files {H10310} <S20000>
5215 **
5216 ** If this global variable is made to point to a string which is
5217 ** the name of a folder (a.k.a. directory), then all temporary files
5218 ** created by SQLite will be placed in that directory.  If this variable
5219 ** is a NULL pointer, then SQLite performs a search for an appropriate
5220 ** temporary file directory.
5221 **
5222 ** It is not safe to modify this variable once a [database connection]
5223 ** has been opened.  It is intended that this variable be set once
5224 ** as part of process initialization and before any SQLite interface
5225 ** routines have been call and remain unchanged thereafter.
5226 */
5227 SQLITE_API char *sqlite3_temp_directory;
5228
5229 /*
5230 ** CAPI3REF: Test For Auto-Commit Mode {H12930} <S60200>
5231 ** KEYWORDS: {autocommit mode}
5232 **
5233 ** The sqlite3_get_autocommit() interface returns non-zero or
5234 ** zero if the given database connection is or is not in autocommit mode,
5235 ** respectively.  Autocommit mode is on by default.
5236 ** Autocommit mode is disabled by a [BEGIN] statement.
5237 ** Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
5238 **
5239 ** If certain kinds of errors occur on a statement within a multi-statement
5240 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
5241 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
5242 ** transaction might be rolled back automatically.  The only way to
5243 ** find out whether SQLite automatically rolled back the transaction after
5244 ** an error is to use this function.
5245 **
5246 ** INVARIANTS:
5247 **
5248 ** {H12931} The [sqlite3_get_autocommit(D)] interface returns non-zero or
5249 **          zero if the [database connection] D is or is not in autocommit
5250 **          mode, respectively.
5251 **
5252 ** {H12932} Autocommit mode is on by default.
5253 **
5254 ** {H12933} Autocommit mode is disabled by a successful [BEGIN] statement.
5255 **
5256 ** {H12934} Autocommit mode is enabled by a successful [COMMIT] or [ROLLBACK]
5257 **          statement.
5258 **
5259 ** ASSUMPTIONS:
5260 **
5261 ** {A12936} If another thread changes the autocommit status of the database
5262 **          connection while this routine is running, then the return value
5263 **          is undefined.
5264 */
5265 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
5266
5267 /*
5268 ** CAPI3REF: Find The Database Handle Of A Prepared Statement {H13120} <S60600>
5269 **
5270 ** The sqlite3_db_handle interface returns the [database connection] handle
5271 ** to which a [prepared statement] belongs.  The database handle returned by
5272 ** sqlite3_db_handle is the same database handle that was the first argument
5273 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
5274 ** create the statement in the first place.
5275 **
5276 ** INVARIANTS:
5277 **
5278 ** {H13123} The [sqlite3_db_handle(S)] interface returns a pointer
5279 **          to the [database connection] associated with the
5280 **          [prepared statement] S.
5281 */
5282 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
5283
5284 /*
5285 ** CAPI3REF: Find the next prepared statement {H13140} <S60600>
5286 **
5287 ** This interface returns a pointer to the next [prepared statement] after
5288 ** pStmt associated with the [database connection] pDb.  If pStmt is NULL
5289 ** then this interface returns a pointer to the first prepared statement
5290 ** associated with the database connection pDb.  If no prepared statement
5291 ** satisfies the conditions of this routine, it returns NULL.
5292 **
5293 ** INVARIANTS:
5294 **
5295 ** {H13143} If D is a [database connection] that holds one or more
5296 **          unfinalized [prepared statements] and S is a NULL pointer,
5297 **          then [sqlite3_next_stmt(D, S)] routine shall return a pointer
5298 **          to one of the prepared statements associated with D.
5299 **
5300 ** {H13146} If D is a [database connection] that holds no unfinalized
5301 **          [prepared statements] and S is a NULL pointer, then
5302 **          [sqlite3_next_stmt(D, S)] routine shall return a NULL pointer.
5303 **
5304 ** {H13149} If S is a [prepared statement] in the [database connection] D
5305 **          and S is not the last prepared statement in D, then
5306 **          [sqlite3_next_stmt(D, S)] routine shall return a pointer
5307 **          to the next prepared statement in D after S.
5308 **
5309 ** {H13152} If S is the last [prepared statement] in the
5310 **          [database connection] D then the [sqlite3_next_stmt(D, S)]
5311 **          routine shall return a NULL pointer.
5312 **
5313 ** ASSUMPTIONS:
5314 **
5315 ** {A13154} The [database connection] pointer D in a call to
5316 **          [sqlite3_next_stmt(D,S)] must refer to an open database
5317 **          connection and in particular must not be a NULL pointer.
5318 */
5319 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
5320
5321 /*
5322 ** CAPI3REF: Commit And Rollback Notification Callbacks {H12950} <S60400>
5323 **
5324 ** The sqlite3_commit_hook() interface registers a callback
5325 ** function to be invoked whenever a transaction is committed.
5326 ** Any callback set by a previous call to sqlite3_commit_hook()
5327 ** for the same database connection is overridden.
5328 ** The sqlite3_rollback_hook() interface registers a callback
5329 ** function to be invoked whenever a transaction is committed.
5330 ** Any callback set by a previous call to sqlite3_commit_hook()
5331 ** for the same database connection is overridden.
5332 ** The pArg argument is passed through to the callback.
5333 ** If the callback on a commit hook function returns non-zero,
5334 ** then the commit is converted into a rollback.
5335 **
5336 ** If another function was previously registered, its
5337 ** pArg value is returned.  Otherwise NULL is returned.
5338 **
5339 ** The callback implementation must not do anything that will modify
5340 ** the database connection that invoked the callback.  Any actions
5341 ** to modify the database connection must be deferred until after the
5342 ** completion of the [sqlite3_step()] call that triggered the commit
5343 ** or rollback hook in the first place.
5344 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5345 ** database connections for the meaning of "modify" in this paragraph.
5346 **
5347 ** Registering a NULL function disables the callback.
5348 **
5349 ** For the purposes of this API, a transaction is said to have been
5350 ** rolled back if an explicit "ROLLBACK" statement is executed, or
5351 ** an error or constraint causes an implicit rollback to occur.
5352 ** The rollback callback is not invoked if a transaction is
5353 ** automatically rolled back because the database connection is closed.
5354 ** The rollback callback is not invoked if a transaction is
5355 ** rolled back because a commit callback returned non-zero.
5356 ** <todo> Check on this </todo>
5357 **
5358 ** INVARIANTS:
5359 **
5360 ** {H12951} The [sqlite3_commit_hook(D,F,P)] interface registers the
5361 **          callback function F to be invoked with argument P whenever
5362 **          a transaction commits on the [database connection] D.
5363 **
5364 ** {H12952} The [sqlite3_commit_hook(D,F,P)] interface returns the P argument
5365 **          from the previous call with the same [database connection] D,
5366 **          or NULL on the first call for a particular database connection D.
5367 **
5368 ** {H12953} Each call to [sqlite3_commit_hook()] overwrites the callback
5369 **          registered by prior calls.
5370 **
5371 ** {H12954} If the F argument to [sqlite3_commit_hook(D,F,P)] is NULL
5372 **          then the commit hook callback is canceled and no callback
5373 **          is invoked when a transaction commits.
5374 **
5375 ** {H12955} If the commit callback returns non-zero then the commit is
5376 **          converted into a rollback.
5377 **
5378 ** {H12961} The [sqlite3_rollback_hook(D,F,P)] interface registers the
5379 **          callback function F to be invoked with argument P whenever
5380 **          a transaction rolls back on the [database connection] D.
5381 **
5382 ** {H12962} The [sqlite3_rollback_hook(D,F,P)] interface returns the P
5383 **          argument from the previous call with the same
5384 **          [database connection] D, or NULL on the first call
5385 **          for a particular database connection D.
5386 **
5387 ** {H12963} Each call to [sqlite3_rollback_hook()] overwrites the callback
5388 **          registered by prior calls.
5389 **
5390 ** {H12964} If the F argument to [sqlite3_rollback_hook(D,F,P)] is NULL
5391 **          then the rollback hook callback is canceled and no callback
5392 **          is invoked when a transaction rolls back.
5393 */
5394 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
5395 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
5396
5397 /*
5398 ** CAPI3REF: Data Change Notification Callbacks {H12970} <S60400>
5399 **
5400 ** The sqlite3_update_hook() interface registers a callback function
5401 ** with the [database connection] identified by the first argument
5402 ** to be invoked whenever a row is updated, inserted or deleted.
5403 ** Any callback set by a previous call to this function
5404 ** for the same database connection is overridden.
5405 **
5406 ** The second argument is a pointer to the function to invoke when a
5407 ** row is updated, inserted or deleted.
5408 ** The first argument to the callback is a copy of the third argument
5409 ** to sqlite3_update_hook().
5410 ** The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
5411 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
5412 ** to be invoked.
5413 ** The third and fourth arguments to the callback contain pointers to the
5414 ** database and table name containing the affected row.
5415 ** The final callback parameter is the rowid of the row. In the case of
5416 ** an update, this is the rowid after the update takes place.
5417 **
5418 ** The update hook is not invoked when internal system tables are
5419 ** modified (i.e. sqlite_master and sqlite_sequence).
5420 **
5421 ** The update hook implementation must not do anything that will modify
5422 ** the database connection that invoked the update hook.  Any actions
5423 ** to modify the database connection must be deferred until after the
5424 ** completion of the [sqlite3_step()] call that triggered the update hook.
5425 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5426 ** database connections for the meaning of "modify" in this paragraph.
5427 **
5428 ** If another function was previously registered, its pArg value
5429 ** is returned.  Otherwise NULL is returned.
5430 **
5431 ** INVARIANTS:
5432 **
5433 ** {H12971} The [sqlite3_update_hook(D,F,P)] interface causes the callback
5434 **          function F to be invoked with first parameter P whenever
5435 **          a table row is modified, inserted, or deleted on
5436 **          the [database connection] D.
5437 **
5438 ** {H12973} The [sqlite3_update_hook(D,F,P)] interface returns the value
5439 **          of P for the previous call on the same [database connection] D,
5440 **          or NULL for the first call.
5441 **
5442 ** {H12975} If the update hook callback F in [sqlite3_update_hook(D,F,P)]
5443 **          is NULL then the no update callbacks are made.
5444 **
5445 ** {H12977} Each call to [sqlite3_update_hook(D,F,P)] overrides prior calls
5446 **          to the same interface on the same [database connection] D.
5447 **
5448 ** {H12979} The update hook callback is not invoked when internal system
5449 **          tables such as sqlite_master and sqlite_sequence are modified.
5450 **
5451 ** {H12981} The second parameter to the update callback
5452 **          is one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE],
5453 **          depending on the operation that caused the callback to be invoked.
5454 **
5455 ** {H12983} The third and fourth arguments to the callback contain pointers
5456 **          to zero-terminated UTF-8 strings which are the names of the
5457 **          database and table that is being updated.
5458
5459 ** {H12985} The final callback parameter is the rowid of the row after
5460 **          the change occurs.
5461 */
5462 SQLITE_API void *sqlite3_update_hook(
5463   sqlite3*, 
5464   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5465   void*
5466 );
5467
5468 /*
5469 ** CAPI3REF: Enable Or Disable Shared Pager Cache {H10330} <S30900>
5470 ** KEYWORDS: {shared cache} {shared cache mode}
5471 **
5472 ** This routine enables or disables the sharing of the database cache
5473 ** and schema data structures between [database connection | connections]
5474 ** to the same database. Sharing is enabled if the argument is true
5475 ** and disabled if the argument is false.
5476 **
5477 ** Cache sharing is enabled and disabled for an entire process. {END}
5478 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
5479 ** sharing was enabled or disabled for each thread separately.
5480 **
5481 ** The cache sharing mode set by this interface effects all subsequent
5482 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
5483 ** Existing database connections continue use the sharing mode
5484 ** that was in effect at the time they were opened.
5485 **
5486 ** Virtual tables cannot be used with a shared cache.  When shared
5487 ** cache is enabled, the [sqlite3_create_module()] API used to register
5488 ** virtual tables will always return an error.
5489 **
5490 ** This routine returns [SQLITE_OK] if shared cache was enabled or disabled
5491 ** successfully.  An [error code] is returned otherwise.
5492 **
5493 ** Shared cache is disabled by default. But this might change in
5494 ** future releases of SQLite.  Applications that care about shared
5495 ** cache setting should set it explicitly.
5496 **
5497 ** INVARIANTS:
5498 **
5499 ** {H10331} A successful invocation of [sqlite3_enable_shared_cache(B)]
5500 **          will enable or disable shared cache mode for any subsequently
5501 **          created [database connection] in the same process.
5502 **
5503 ** {H10336} When shared cache is enabled, the [sqlite3_create_module()]
5504 **          interface will always return an error.
5505 **
5506 ** {H10337} The [sqlite3_enable_shared_cache(B)] interface returns
5507 **          [SQLITE_OK] if shared cache was enabled or disabled successfully.
5508 **
5509 ** {H10339} Shared cache is disabled by default.
5510 */
5511 SQLITE_API int sqlite3_enable_shared_cache(int);
5512
5513 /*
5514 ** CAPI3REF: Attempt To Free Heap Memory {H17340} <S30220>
5515 **
5516 ** The sqlite3_release_memory() interface attempts to free N bytes
5517 ** of heap memory by deallocating non-essential memory allocations
5518 ** held by the database library. {END}  Memory used to cache database
5519 ** pages to improve performance is an example of non-essential memory.
5520 ** sqlite3_release_memory() returns the number of bytes actually freed,
5521 ** which might be more or less than the amount requested.
5522 **
5523 ** INVARIANTS:
5524 **
5525 ** {H17341} The [sqlite3_release_memory(N)] interface attempts to
5526 **          free N bytes of heap memory by deallocating non-essential
5527 **          memory allocations held by the database library.
5528 **
5529 ** {H16342} The [sqlite3_release_memory(N)] returns the number
5530 **          of bytes actually freed, which might be more or less
5531 **          than the amount requested.
5532 */
5533 SQLITE_API int sqlite3_release_memory(int);
5534
5535 /*
5536 ** CAPI3REF: Impose A Limit On Heap Size {H17350} <S30220>
5537 **
5538 ** The sqlite3_soft_heap_limit() interface places a "soft" limit
5539 ** on the amount of heap memory that may be allocated by SQLite.
5540 ** If an internal allocation is requested that would exceed the
5541 ** soft heap limit, [sqlite3_release_memory()] is invoked one or
5542 ** more times to free up some space before the allocation is performed.
5543 **
5544 ** The limit is called "soft", because if [sqlite3_release_memory()]
5545 ** cannot free sufficient memory to prevent the limit from being exceeded,
5546 ** the memory is allocated anyway and the current operation proceeds.
5547 **
5548 ** A negative or zero value for N means that there is no soft heap limit and
5549 ** [sqlite3_release_memory()] will only be called when memory is exhausted.
5550 ** The default value for the soft heap limit is zero.
5551 **
5552 ** SQLite makes a best effort to honor the soft heap limit.
5553 ** But if the soft heap limit cannot be honored, execution will
5554 ** continue without error or notification.  This is why the limit is
5555 ** called a "soft" limit.  It is advisory only.
5556 **
5557 ** Prior to SQLite version 3.5.0, this routine only constrained the memory
5558 ** allocated by a single thread - the same thread in which this routine
5559 ** runs.  Beginning with SQLite version 3.5.0, the soft heap limit is
5560 ** applied to all threads. The value specified for the soft heap limit
5561 ** is an upper bound on the total memory allocation for all threads. In
5562 ** version 3.5.0 there is no mechanism for limiting the heap usage for
5563 ** individual threads.
5564 **
5565 ** INVARIANTS:
5566 **
5567 ** {H16351} The [sqlite3_soft_heap_limit(N)] interface places a soft limit
5568 **          of N bytes on the amount of heap memory that may be allocated
5569 **          using [sqlite3_malloc()] or [sqlite3_realloc()] at any point
5570 **          in time.
5571 **
5572 ** {H16352} If a call to [sqlite3_malloc()] or [sqlite3_realloc()] would
5573 **          cause the total amount of allocated memory to exceed the
5574 **          soft heap limit, then [sqlite3_release_memory()] is invoked
5575 **          in an attempt to reduce the memory usage prior to proceeding
5576 **          with the memory allocation attempt.
5577 **
5578 ** {H16353} Calls to [sqlite3_malloc()] or [sqlite3_realloc()] that trigger
5579 **          attempts to reduce memory usage through the soft heap limit
5580 **          mechanism continue even if the attempt to reduce memory
5581 **          usage is unsuccessful.
5582 **
5583 ** {H16354} A negative or zero value for N in a call to
5584 **          [sqlite3_soft_heap_limit(N)] means that there is no soft
5585 **          heap limit and [sqlite3_release_memory()] will only be
5586 **          called when memory is completely exhausted.
5587 **
5588 ** {H16355} The default value for the soft heap limit is zero.
5589 **
5590 ** {H16358} Each call to [sqlite3_soft_heap_limit(N)] overrides the
5591 **          values set by all prior calls.
5592 */
5593 SQLITE_API void sqlite3_soft_heap_limit(int);
5594
5595 /*
5596 ** CAPI3REF: Extract Metadata About A Column Of A Table {H12850} <S60300>
5597 **
5598 ** This routine returns metadata about a specific column of a specific
5599 ** database table accessible using the [database connection] handle
5600 ** passed as the first function argument.
5601 **
5602 ** The column is identified by the second, third and fourth parameters to
5603 ** this function. The second parameter is either the name of the database
5604 ** (i.e. "main", "temp" or an attached database) containing the specified
5605 ** table or NULL. If it is NULL, then all attached databases are searched
5606 ** for the table using the same algorithm used by the database engine to
5607 ** resolve unqualified table references.
5608 **
5609 ** The third and fourth parameters to this function are the table and column
5610 ** name of the desired column, respectively. Neither of these parameters
5611 ** may be NULL.
5612 **
5613 ** Metadata is returned by writing to the memory locations passed as the 5th
5614 ** and subsequent parameters to this function. Any of these arguments may be
5615 ** NULL, in which case the corresponding element of metadata is omitted.
5616 **
5617 ** <blockquote>
5618 ** <table border="1">
5619 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
5620 **
5621 ** <tr><td> 5th <td> const char* <td> Data type
5622 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5623 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
5624 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
5625 ** <tr><td> 9th <td> int         <td> True if column is AUTOINCREMENT
5626 ** </table>
5627 ** </blockquote>
5628 **
5629 ** The memory pointed to by the character pointers returned for the
5630 ** declaration type and collation sequence is valid only until the next
5631 ** call to any SQLite API function.
5632 **
5633 ** If the specified table is actually a view, an [error code] is returned.
5634 **
5635 ** If the specified column is "rowid", "oid" or "_rowid_" and an
5636 ** INTEGER PRIMARY KEY column has been explicitly declared, then the output
5637 ** parameters are set for the explicitly declared column. If there is no
5638 ** explicitly declared INTEGER PRIMARY KEY column, then the output
5639 ** parameters are set as follows:
5640 **
5641 ** <pre>
5642 **     data type: "INTEGER"
5643 **     collation sequence: "BINARY"
5644 **     not null: 0
5645 **     primary key: 1
5646 **     auto increment: 0
5647 ** </pre>
5648 **
5649 ** This function may load one or more schemas from database files. If an
5650 ** error occurs during this process, or if the requested table or column
5651 ** cannot be found, an [error code] is returned and an error message left
5652 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).
5653 **
5654 ** This API is only available if the library was compiled with the
5655 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
5656 */
5657 SQLITE_API int sqlite3_table_column_metadata(
5658   sqlite3 *db,                /* Connection handle */
5659   const char *zDbName,        /* Database name or NULL */
5660   const char *zTableName,     /* Table name */
5661   const char *zColumnName,    /* Column name */
5662   char const **pzDataType,    /* OUTPUT: Declared data type */
5663   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
5664   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
5665   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
5666   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
5667 );
5668
5669 /*
5670 ** CAPI3REF: Load An Extension {H12600} <S20500>
5671 **
5672 ** This interface loads an SQLite extension library from the named file.
5673 **
5674 ** {H12601} The sqlite3_load_extension() interface attempts to load an
5675 **          SQLite extension library contained in the file zFile.
5676 **
5677 ** {H12602} The entry point is zProc.
5678 **
5679 ** {H12603} zProc may be 0, in which case the name of the entry point
5680 **          defaults to "sqlite3_extension_init".
5681 **
5682 ** {H12604} The sqlite3_load_extension() interface shall return
5683 **          [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5684 **
5685 ** {H12605} If an error occurs and pzErrMsg is not 0, then the
5686 **          [sqlite3_load_extension()] interface shall attempt to
5687 **          fill *pzErrMsg with error message text stored in memory
5688 **          obtained from [sqlite3_malloc()]. {END}  The calling function
5689 **          should free this memory by calling [sqlite3_free()].
5690 **
5691 ** {H12606} Extension loading must be enabled using
5692 **          [sqlite3_enable_load_extension()] prior to calling this API,
5693 **          otherwise an error will be returned.
5694 */
5695 SQLITE_API int sqlite3_load_extension(
5696   sqlite3 *db,          /* Load the extension into this database connection */
5697   const char *zFile,    /* Name of the shared library containing extension */
5698   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
5699   char **pzErrMsg       /* Put error message here if not 0 */
5700 );
5701
5702 /*
5703 ** CAPI3REF: Enable Or Disable Extension Loading {H12620} <S20500>
5704 **
5705 ** So as not to open security holes in older applications that are
5706 ** unprepared to deal with extension loading, and as a means of disabling
5707 ** extension loading while evaluating user-entered SQL, the following API
5708 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5709 **
5710 ** Extension loading is off by default. See ticket #1863.
5711 **
5712 ** {H12621} Call the sqlite3_enable_load_extension() routine with onoff==1
5713 **          to turn extension loading on and call it with onoff==0 to turn
5714 **          it back off again.
5715 **
5716 ** {H12622} Extension loading is off by default.
5717 */
5718 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5719
5720 /*
5721 ** CAPI3REF: Automatically Load An Extensions {H12640} <S20500>
5722 **
5723 ** This API can be invoked at program startup in order to register
5724 ** one or more statically linked extensions that will be available
5725 ** to all new [database connections]. {END}
5726 **
5727 ** This routine stores a pointer to the extension in an array that is
5728 ** obtained from [sqlite3_malloc()].  If you run a memory leak checker
5729 ** on your program and it reports a leak because of this array, invoke
5730 ** [sqlite3_reset_auto_extension()] prior to shutdown to free the memory.
5731 **
5732 ** {H12641} This function registers an extension entry point that is
5733 **          automatically invoked whenever a new [database connection]
5734 **          is opened using [sqlite3_open()], [sqlite3_open16()],
5735 **          or [sqlite3_open_v2()].
5736 **
5737 ** {H12642} Duplicate extensions are detected so calling this routine
5738 **          multiple times with the same extension is harmless.
5739 **
5740 ** {H12643} This routine stores a pointer to the extension in an array
5741 **          that is obtained from [sqlite3_malloc()].
5742 **
5743 ** {H12644} Automatic extensions apply across all threads.
5744 */
5745 SQLITE_API int sqlite3_auto_extension(void *xEntryPoint);
5746
5747 /*
5748 ** CAPI3REF: Reset Automatic Extension Loading {H12660} <S20500>
5749 **
5750 ** This function disables all previously registered automatic
5751 ** extensions. {END}  It undoes the effect of all prior
5752 ** [sqlite3_auto_extension()] calls.
5753 **
5754 ** {H12661} This function disables all previously registered
5755 **          automatic extensions.
5756 **
5757 ** {H12662} This function disables automatic extensions in all threads.
5758 */
5759 SQLITE_API void sqlite3_reset_auto_extension(void);
5760
5761 /*
5762 ****** EXPERIMENTAL - subject to change without notice **************
5763 **
5764 ** The interface to the virtual-table mechanism is currently considered
5765 ** to be experimental.  The interface might change in incompatible ways.
5766 ** If this is a problem for you, do not use the interface at this time.
5767 **
5768 ** When the virtual-table mechanism stabilizes, we will declare the
5769 ** interface fixed, support it indefinitely, and remove this comment.
5770 */
5771
5772 /*
5773 ** Structures used by the virtual table interface
5774 */
5775 typedef struct sqlite3_vtab sqlite3_vtab;
5776 typedef struct sqlite3_index_info sqlite3_index_info;
5777 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5778 typedef struct sqlite3_module sqlite3_module;
5779
5780 /*
5781 ** CAPI3REF: Virtual Table Object {H18000} <S20400>
5782 ** KEYWORDS: sqlite3_module
5783 ** EXPERIMENTAL
5784 **
5785 ** A module is a class of virtual tables.  Each module is defined
5786 ** by an instance of the following structure.  This structure consists
5787 ** mostly of methods for the module.
5788 **
5789 ** This interface is experimental and is subject to change or
5790 ** removal in future releases of SQLite.
5791 */
5792 struct sqlite3_module {
5793   int iVersion;
5794   int (*xCreate)(sqlite3*, void *pAux,
5795                int argc, const char *const*argv,
5796                sqlite3_vtab **ppVTab, char**);
5797   int (*xConnect)(sqlite3*, void *pAux,
5798                int argc, const char *const*argv,
5799                sqlite3_vtab **ppVTab, char**);
5800   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5801   int (*xDisconnect)(sqlite3_vtab *pVTab);
5802   int (*xDestroy)(sqlite3_vtab *pVTab);
5803   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5804   int (*xClose)(sqlite3_vtab_cursor*);
5805   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5806                 int argc, sqlite3_value **argv);
5807   int (*xNext)(sqlite3_vtab_cursor*);
5808   int (*xEof)(sqlite3_vtab_cursor*);
5809   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5810   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5811   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5812   int (*xBegin)(sqlite3_vtab *pVTab);
5813   int (*xSync)(sqlite3_vtab *pVTab);
5814   int (*xCommit)(sqlite3_vtab *pVTab);
5815   int (*xRollback)(sqlite3_vtab *pVTab);
5816   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5817                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5818                        void **ppArg);
5819   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5820 };
5821
5822 /*
5823 ** CAPI3REF: Virtual Table Indexing Information {H18100} <S20400>
5824 ** KEYWORDS: sqlite3_index_info
5825 ** EXPERIMENTAL
5826 **
5827 ** The sqlite3_index_info structure and its substructures is used to
5828 ** pass information into and receive the reply from the xBestIndex
5829 ** method of an sqlite3_module.  The fields under **Inputs** are the
5830 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
5831 ** results into the **Outputs** fields.
5832 **
5833 ** The aConstraint[] array records WHERE clause constraints of the form:
5834 **
5835 ** <pre>column OP expr</pre>
5836 **
5837 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.  The particular operator is
5838 ** stored in aConstraint[].op.  The index of the column is stored in
5839 ** aConstraint[].iColumn.  aConstraint[].usable is TRUE if the
5840 ** expr on the right-hand side can be evaluated (and thus the constraint
5841 ** is usable) and false if it cannot.
5842 **
5843 ** The optimizer automatically inverts terms of the form "expr OP column"
5844 ** and makes other simplifications to the WHERE clause in an attempt to
5845 ** get as many WHERE clause terms into the form shown above as possible.
5846 ** The aConstraint[] array only reports WHERE clause terms in the correct
5847 ** form that refer to the particular virtual table being queried.
5848 **
5849 ** Information about the ORDER BY clause is stored in aOrderBy[].
5850 ** Each term of aOrderBy records a column of the ORDER BY clause.
5851 **
5852 ** The xBestIndex method must fill aConstraintUsage[] with information
5853 ** about what parameters to pass to xFilter.  If argvIndex>0 then
5854 ** the right-hand side of the corresponding aConstraint[] is evaluated
5855 ** and becomes the argvIndex-th entry in argv.  If aConstraintUsage[].omit
5856 ** is true, then the constraint is assumed to be fully handled by the
5857 ** virtual table and is not checked again by SQLite.
5858 **
5859 ** The idxNum and idxPtr values are recorded and passed into xFilter.
5860 ** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true.
5861 **
5862 ** The orderByConsumed means that output from xFilter will occur in
5863 ** the correct order to satisfy the ORDER BY clause so that no separate
5864 ** sorting step is required.
5865 **
5866 ** The estimatedCost value is an estimate of the cost of doing the
5867 ** particular lookup.  A full scan of a table with N entries should have
5868 ** a cost of N.  A binary search of a table of N entries should have a
5869 ** cost of approximately log(N).
5870 **
5871 ** This interface is experimental and is subject to change or
5872 ** removal in future releases of SQLite.
5873 */
5874 struct sqlite3_index_info {
5875   /* Inputs */
5876   int nConstraint;           /* Number of entries in aConstraint */
5877   struct sqlite3_index_constraint {
5878      int iColumn;              /* Column on left-hand side of constraint */
5879      unsigned char op;         /* Constraint operator */
5880      unsigned char usable;     /* True if this constraint is usable */
5881      int iTermOffset;          /* Used internally - xBestIndex should ignore */
5882   } *aConstraint;            /* Table of WHERE clause constraints */
5883   int nOrderBy;              /* Number of terms in the ORDER BY clause */
5884   struct sqlite3_index_orderby {
5885      int iColumn;              /* Column number */
5886      unsigned char desc;       /* True for DESC.  False for ASC. */
5887   } *aOrderBy;               /* The ORDER BY clause */
5888   /* Outputs */
5889   struct sqlite3_index_constraint_usage {
5890     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
5891     unsigned char omit;      /* Do not code a test for this constraint */
5892   } *aConstraintUsage;
5893   int idxNum;                /* Number used to identify the index */
5894   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
5895   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
5896   int orderByConsumed;       /* True if output is already ordered */
5897   double estimatedCost;      /* Estimated cost of using this index */
5898 };
5899 #define SQLITE_INDEX_CONSTRAINT_EQ    2
5900 #define SQLITE_INDEX_CONSTRAINT_GT    4
5901 #define SQLITE_INDEX_CONSTRAINT_LE    8
5902 #define SQLITE_INDEX_CONSTRAINT_LT    16
5903 #define SQLITE_INDEX_CONSTRAINT_GE    32
5904 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
5905
5906 /*
5907 ** CAPI3REF: Register A Virtual Table Implementation {H18200} <S20400>
5908 ** EXPERIMENTAL
5909 **
5910 ** This routine is used to register a new module name with a
5911 ** [database connection].  Module names must be registered before
5912 ** creating new virtual tables on the module, or before using
5913 ** preexisting virtual tables of the module.
5914 **
5915 ** This interface is experimental and is subject to change or
5916 ** removal in future releases of SQLite.
5917 */
5918 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module(
5919   sqlite3 *db,               /* SQLite connection to register module with */
5920   const char *zName,         /* Name of the module */
5921   const sqlite3_module *,    /* Methods for the module */
5922   void *                     /* Client data for xCreate/xConnect */
5923 );
5924
5925 /*
5926 ** CAPI3REF: Register A Virtual Table Implementation {H18210} <S20400>
5927 ** EXPERIMENTAL
5928 **
5929 ** This routine is identical to the [sqlite3_create_module()] method above,
5930 ** except that it allows a destructor function to be specified. It is
5931 ** even more experimental than the rest of the virtual tables API.
5932 */
5933 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module_v2(
5934   sqlite3 *db,               /* SQLite connection to register module with */
5935   const char *zName,         /* Name of the module */
5936   const sqlite3_module *,    /* Methods for the module */
5937   void *,                    /* Client data for xCreate/xConnect */
5938   void(*xDestroy)(void*)     /* Module destructor function */
5939 );
5940
5941 /*
5942 ** CAPI3REF: Virtual Table Instance Object {H18010} <S20400>
5943 ** KEYWORDS: sqlite3_vtab
5944 ** EXPERIMENTAL
5945 **
5946 ** Every module implementation uses a subclass of the following structure
5947 ** to describe a particular instance of the module.  Each subclass will
5948 ** be tailored to the specific needs of the module implementation.
5949 ** The purpose of this superclass is to define certain fields that are
5950 ** common to all module implementations.
5951 **
5952 ** Virtual tables methods can set an error message by assigning a
5953 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
5954 ** take care that any prior string is freed by a call to [sqlite3_free()]
5955 ** prior to assigning a new string to zErrMsg.  After the error message
5956 ** is delivered up to the client application, the string will be automatically
5957 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.  Note
5958 ** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field
5959 ** since virtual tables are commonly implemented in loadable extensions which
5960 ** do not have access to sqlite3MPrintf() or sqlite3Free().
5961 **
5962 ** This interface is experimental and is subject to change or
5963 ** removal in future releases of SQLite.
5964 */
5965 struct sqlite3_vtab {
5966   const sqlite3_module *pModule;  /* The module for this virtual table */
5967   int nRef;                       /* Used internally */
5968   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
5969   /* Virtual table implementations will typically add additional fields */
5970 };
5971
5972 /*
5973 ** CAPI3REF: Virtual Table Cursor Object  {H18020} <S20400>
5974 ** KEYWORDS: sqlite3_vtab_cursor
5975 ** EXPERIMENTAL
5976 **
5977 ** Every module implementation uses a subclass of the following structure
5978 ** to describe cursors that point into the virtual table and are used
5979 ** to loop through the virtual table.  Cursors are created using the
5980 ** xOpen method of the module.  Each module implementation will define
5981 ** the content of a cursor structure to suit its own needs.
5982 **
5983 ** This superclass exists in order to define fields of the cursor that
5984 ** are common to all implementations.
5985 **
5986 ** This interface is experimental and is subject to change or
5987 ** removal in future releases of SQLite.
5988 */
5989 struct sqlite3_vtab_cursor {
5990   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
5991   /* Virtual table implementations will typically add additional fields */
5992 };
5993
5994 /*
5995 ** CAPI3REF: Declare The Schema Of A Virtual Table {H18280} <S20400>
5996 ** EXPERIMENTAL
5997 **
5998 ** The xCreate and xConnect methods of a module use the following API
5999 ** to declare the format (the names and datatypes of the columns) of
6000 ** the virtual tables they implement.
6001 **
6002 ** This interface is experimental and is subject to change or
6003 ** removal in future releases of SQLite.
6004 */
6005 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable);
6006
6007 /*
6008 ** CAPI3REF: Overload A Function For A Virtual Table {H18300} <S20400>
6009 ** EXPERIMENTAL
6010 **
6011 ** Virtual tables can provide alternative implementations of functions
6012 ** using the xFindFunction method.  But global versions of those functions
6013 ** must exist in order to be overloaded.
6014 **
6015 ** This API makes sure a global version of a function with a particular
6016 ** name and number of parameters exists.  If no such function exists
6017 ** before this API is called, a new function is created.  The implementation
6018 ** of the new function always causes an exception to be thrown.  So
6019 ** the new function is not good for anything by itself.  Its only
6020 ** purpose is to be a placeholder function that can be overloaded
6021 ** by virtual tables.
6022 **
6023 ** This API should be considered part of the virtual table interface,
6024 ** which is experimental and subject to change.
6025 */
6026 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
6027
6028 /*
6029 ** The interface to the virtual-table mechanism defined above (back up
6030 ** to a comment remarkably similar to this one) is currently considered
6031 ** to be experimental.  The interface might change in incompatible ways.
6032 ** If this is a problem for you, do not use the interface at this time.
6033 **
6034 ** When the virtual-table mechanism stabilizes, we will declare the
6035 ** interface fixed, support it indefinitely, and remove this comment.
6036 **
6037 ****** EXPERIMENTAL - subject to change without notice **************
6038 */
6039
6040 /*
6041 ** CAPI3REF: A Handle To An Open BLOB {H17800} <S30230>
6042 ** KEYWORDS: {BLOB handle} {BLOB handles}
6043 **
6044 ** An instance of this object represents an open BLOB on which
6045 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
6046 ** Objects of this type are created by [sqlite3_blob_open()]
6047 ** and destroyed by [sqlite3_blob_close()].
6048 ** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
6049 ** can be used to read or write small subsections of the BLOB.
6050 ** The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
6051 */
6052 typedef struct sqlite3_blob sqlite3_blob;
6053
6054 /*
6055 ** CAPI3REF: Open A BLOB For Incremental I/O {H17810} <S30230>
6056 **
6057 ** This interfaces opens a [BLOB handle | handle] to the BLOB located
6058 ** in row iRow, column zColumn, table zTable in database zDb;
6059 ** in other words, the same BLOB that would be selected by:
6060 **
6061 ** <pre>
6062 **     SELECT zColumn FROM zDb.zTable WHERE rowid = iRow;
6063 ** </pre> {END}
6064 **
6065 ** If the flags parameter is non-zero, the the BLOB is opened for read
6066 ** and write access. If it is zero, the BLOB is opened for read access.
6067 **
6068 ** Note that the database name is not the filename that contains
6069 ** the database but rather the symbolic name of the database that
6070 ** is assigned when the database is connected using [ATTACH].
6071 ** For the main database file, the database name is "main".
6072 ** For TEMP tables, the database name is "temp".
6073 **
6074 ** On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
6075 ** to *ppBlob. Otherwise an [error code] is returned and any value written
6076 ** to *ppBlob should not be used by the caller.
6077 ** This function sets the [database connection] error code and message
6078 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()].
6079 **
6080 ** If the row that a BLOB handle points to is modified by an
6081 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
6082 ** then the BLOB handle is marked as "expired".
6083 ** This is true if any column of the row is changed, even a column
6084 ** other than the one the BLOB handle is open on.
6085 ** Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
6086 ** a expired BLOB handle fail with an return code of [SQLITE_ABORT].
6087 ** Changes written into a BLOB prior to the BLOB expiring are not
6088 ** rollback by the expiration of the BLOB.  Such changes will eventually
6089 ** commit if the transaction continues to completion.
6090 **
6091 ** INVARIANTS:
6092 **
6093 ** {H17813} A successful invocation of the [sqlite3_blob_open(D,B,T,C,R,F,P)]
6094 **          interface shall open an [sqlite3_blob] object P on the BLOB
6095 **          in column C of the table T in the database B on
6096 **          the [database connection] D.
6097 **
6098 ** {H17814} A successful invocation of [sqlite3_blob_open(D,...)] shall start
6099 **          a new transaction on the [database connection] D if that
6100 **          connection is not already in a transaction.
6101 **
6102 ** {H17816} The [sqlite3_blob_open(D,B,T,C,R,F,P)] interface shall open
6103 **          the BLOB for read and write access if and only if the F
6104 **          parameter is non-zero.
6105 **
6106 ** {H17819} The [sqlite3_blob_open()] interface shall return [SQLITE_OK] on
6107 **          success and an appropriate [error code] on failure.
6108 **
6109 ** {H17821} If an error occurs during evaluation of [sqlite3_blob_open(D,...)]
6110 **          then subsequent calls to [sqlite3_errcode(D)],
6111 **          [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] shall return
6112 **          information appropriate for that error.
6113 **
6114 ** {H17824} If any column in the row that a [sqlite3_blob] has open is
6115 **          changed by a separate [UPDATE] or [DELETE] statement or by
6116 **          an [ON CONFLICT] side effect, then the [sqlite3_blob] shall
6117 **          be marked as invalid.
6118 */
6119 SQLITE_API int sqlite3_blob_open(
6120   sqlite3*,
6121   const char *zDb,
6122   const char *zTable,
6123   const char *zColumn,
6124   sqlite3_int64 iRow,
6125   int flags,
6126   sqlite3_blob **ppBlob
6127 );
6128
6129 /*
6130 ** CAPI3REF: Close A BLOB Handle {H17830} <S30230>
6131 **
6132 ** Closes an open [BLOB handle].
6133 **
6134 ** Closing a BLOB shall cause the current transaction to commit
6135 ** if there are no other BLOBs, no pending prepared statements, and the
6136 ** database connection is in [autocommit mode].
6137 ** If any writes were made to the BLOB, they might be held in cache
6138 ** until the close operation if they will fit. {END}
6139 **
6140 ** Closing the BLOB often forces the changes
6141 ** out to disk and so if any I/O errors occur, they will likely occur
6142 ** at the time when the BLOB is closed.  {H17833} Any errors that occur during
6143 ** closing are reported as a non-zero return value.
6144 **
6145 ** The BLOB is closed unconditionally.  Even if this routine returns
6146 ** an error code, the BLOB is still closed.
6147 **
6148 ** INVARIANTS:
6149 **
6150 ** {H17833} The [sqlite3_blob_close(P)] interface closes an [sqlite3_blob]
6151 **          object P previously opened using [sqlite3_blob_open()].
6152 **
6153 ** {H17836} Closing an [sqlite3_blob] object using
6154 **          [sqlite3_blob_close()] shall cause the current transaction to
6155 **          commit if there are no other open [sqlite3_blob] objects
6156 **          or [prepared statements] on the same [database connection] and
6157 **          the database connection is in [autocommit mode].
6158 **
6159 ** {H17839} The [sqlite3_blob_close(P)] interfaces shall close the
6160 **          [sqlite3_blob] object P unconditionally, even if
6161 **          [sqlite3_blob_close(P)] returns something other than [SQLITE_OK].
6162 */
6163 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
6164
6165 /*
6166 ** CAPI3REF: Return The Size Of An Open BLOB {H17840} <S30230>
6167 **
6168 ** Returns the size in bytes of the BLOB accessible via the open
6169 ** []BLOB handle] in its only argument.
6170 **
6171 ** INVARIANTS:
6172 **
6173 ** {H17843} The [sqlite3_blob_bytes(P)] interface returns the size
6174 **          in bytes of the BLOB that the [sqlite3_blob] object P
6175 **          refers to.
6176 */
6177 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
6178
6179 /*
6180 ** CAPI3REF: Read Data From A BLOB Incrementally {H17850} <S30230>
6181 **
6182 ** This function is used to read data from an open [BLOB handle] into a
6183 ** caller-supplied buffer. N bytes of data are copied into buffer Z
6184 ** from the open BLOB, starting at offset iOffset.
6185 **
6186 ** If offset iOffset is less than N bytes from the end of the BLOB,
6187 ** [SQLITE_ERROR] is returned and no data is read.  If N or iOffset is
6188 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
6189 **
6190 ** An attempt to read from an expired [BLOB handle] fails with an
6191 ** error code of [SQLITE_ABORT].
6192 **
6193 ** On success, SQLITE_OK is returned.
6194 ** Otherwise, an [error code] or an [extended error code] is returned.
6195 **
6196 ** INVARIANTS:
6197 **
6198 ** {H17853} A successful invocation of [sqlite3_blob_read(P,Z,N,X)] 
6199 **          shall reads N bytes of data out of the BLOB referenced by
6200 **          [BLOB handle] P beginning at offset X and store those bytes
6201 **          into buffer Z.
6202 **
6203 ** {H17856} In [sqlite3_blob_read(P,Z,N,X)] if the size of the BLOB
6204 **          is less than N+X bytes, then the function shall leave the
6205 **          Z buffer unchanged and return [SQLITE_ERROR].
6206 **
6207 ** {H17859} In [sqlite3_blob_read(P,Z,N,X)] if X or N is less than zero
6208 **          then the function shall leave the Z buffer unchanged
6209 **          and return [SQLITE_ERROR].
6210 **
6211 ** {H17862} The [sqlite3_blob_read(P,Z,N,X)] interface shall return [SQLITE_OK]
6212 **          if N bytes are successfully read into buffer Z.
6213 **
6214 ** {H17863} If the [BLOB handle] P is expired and X and N are within bounds
6215 **          then [sqlite3_blob_read(P,Z,N,X)] shall leave the Z buffer
6216 **          unchanged and return [SQLITE_ABORT].
6217 **
6218 ** {H17865} If the requested read could not be completed,
6219 **          the [sqlite3_blob_read(P,Z,N,X)] interface shall return an
6220 **          appropriate [error code] or [extended error code].
6221 **
6222 ** {H17868} If an error occurs during evaluation of [sqlite3_blob_read(P,...)]
6223 **          then subsequent calls to [sqlite3_errcode(D)],
6224 **          [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] shall return
6225 **          information appropriate for that error, where D is the
6226 **          [database connection] that was used to open the [BLOB handle] P.
6227 */
6228 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
6229
6230 /*
6231 ** CAPI3REF: Write Data Into A BLOB Incrementally {H17870} <S30230>
6232 **
6233 ** This function is used to write data into an open [BLOB handle] from a
6234 ** caller-supplied buffer. N bytes of data are copied from the buffer Z
6235 ** into the open BLOB, starting at offset iOffset.
6236 **
6237 ** If the [BLOB handle] passed as the first argument was not opened for
6238 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
6239 ** this function returns [SQLITE_READONLY].
6240 **
6241 ** This function may only modify the contents of the BLOB; it is
6242 ** not possible to increase the size of a BLOB using this API.
6243 ** If offset iOffset is less than N bytes from the end of the BLOB,
6244 ** [SQLITE_ERROR] is returned and no data is written.  If N is
6245 ** less than zero [SQLITE_ERROR] is returned and no data is written.
6246 **
6247 ** An attempt to write to an expired [BLOB handle] fails with an
6248 ** error code of [SQLITE_ABORT].  Writes to the BLOB that occurred
6249 ** before the [BLOB handle] expired are not rolled back by the
6250 ** expiration of the handle, though of course those changes might
6251 ** have been overwritten by the statement that expired the BLOB handle
6252 ** or by other independent statements.
6253 **
6254 ** On success, SQLITE_OK is returned.
6255 ** Otherwise, an  [error code] or an [extended error code] is returned.
6256 **
6257 ** INVARIANTS:
6258 **
6259 ** {H17873} A successful invocation of [sqlite3_blob_write(P,Z,N,X)]
6260 **          shall write N bytes of data from buffer Z into the BLOB 
6261 **          referenced by [BLOB handle] P beginning at offset X into
6262 **          the BLOB.
6263 **
6264 ** {H17874} In the absence of other overridding changes, the changes
6265 **          written to a BLOB by [sqlite3_blob_write()] shall
6266 **          remain in effect after the associated [BLOB handle] expires.
6267 **
6268 ** {H17875} If the [BLOB handle] P was opened for reading only then
6269 **          an invocation of [sqlite3_blob_write(P,Z,N,X)] shall leave
6270 **          the referenced BLOB unchanged and return [SQLITE_READONLY].
6271 **
6272 ** {H17876} If the size of the BLOB referenced by [BLOB handle] P is
6273 **          less than N+X bytes then [sqlite3_blob_write(P,Z,N,X)] shall
6274 **          leave the BLOB unchanged and return [SQLITE_ERROR].
6275 **
6276 ** {H17877} If the [BLOB handle] P is expired and X and N are within bounds
6277 **          then [sqlite3_blob_read(P,Z,N,X)] shall leave the BLOB
6278 **          unchanged and return [SQLITE_ABORT].
6279 **
6280 ** {H17879} If X or N are less than zero then [sqlite3_blob_write(P,Z,N,X)]
6281 **          shall leave the BLOB referenced by [BLOB handle] P unchanged
6282 **          and return [SQLITE_ERROR].
6283 **
6284 ** {H17882} The [sqlite3_blob_write(P,Z,N,X)] interface shall return
6285 **          [SQLITE_OK] if N bytes where successfully written into the BLOB.
6286 **
6287 ** {H17885} If the requested write could not be completed,
6288 **          the [sqlite3_blob_write(P,Z,N,X)] interface shall return an
6289 **          appropriate [error code] or [extended error code].
6290 **
6291 ** {H17888} If an error occurs during evaluation of [sqlite3_blob_write(D,...)]
6292 **          then subsequent calls to [sqlite3_errcode(D)],
6293 **          [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] shall return
6294 **          information appropriate for that error.
6295 */
6296 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
6297
6298 /*
6299 ** CAPI3REF: Virtual File System Objects {H11200} <S20100>
6300 **
6301 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
6302 ** that SQLite uses to interact
6303 ** with the underlying operating system.  Most SQLite builds come with a
6304 ** single default VFS that is appropriate for the host computer.
6305 ** New VFSes can be registered and existing VFSes can be unregistered.
6306 ** The following interfaces are provided.
6307 **
6308 ** The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
6309 ** Names are case sensitive.
6310 ** Names are zero-terminated UTF-8 strings.
6311 ** If there is no match, a NULL pointer is returned.
6312 ** If zVfsName is NULL then the default VFS is returned.
6313 **
6314 ** New VFSes are registered with sqlite3_vfs_register().
6315 ** Each new VFS becomes the default VFS if the makeDflt flag is set.
6316 ** The same VFS can be registered multiple times without injury.
6317 ** To make an existing VFS into the default VFS, register it again
6318 ** with the makeDflt flag set.  If two different VFSes with the
6319 ** same name are registered, the behavior is undefined.  If a
6320 ** VFS is registered with a name that is NULL or an empty string,
6321 ** then the behavior is undefined.
6322 **
6323 ** Unregister a VFS with the sqlite3_vfs_unregister() interface.
6324 ** If the default VFS is unregistered, another VFS is chosen as
6325 ** the default.  The choice for the new VFS is arbitrary.
6326 **
6327 ** INVARIANTS:
6328 **
6329 ** {H11203} The [sqlite3_vfs_find(N)] interface returns a pointer to the
6330 **          registered [sqlite3_vfs] object whose name exactly matches
6331 **          the zero-terminated UTF-8 string N, or it returns NULL if
6332 **          there is no match.
6333 **
6334 ** {H11206} If the N parameter to [sqlite3_vfs_find(N)] is NULL then
6335 **          the function returns a pointer to the default [sqlite3_vfs]
6336 **          object if there is one, or NULL if there is no default
6337 **          [sqlite3_vfs] object.
6338 **
6339 ** {H11209} The [sqlite3_vfs_register(P,F)] interface registers the
6340 **          well-formed [sqlite3_vfs] object P using the name given
6341 **          by the zName field of the object.
6342 **
6343 ** {H11212} Using the [sqlite3_vfs_register(P,F)] interface to register
6344 **          the same [sqlite3_vfs] object multiple times is a harmless no-op.
6345 **
6346 ** {H11215} The [sqlite3_vfs_register(P,F)] interface makes the [sqlite3_vfs]
6347 **          object P the default [sqlite3_vfs] object if F is non-zero.
6348 **
6349 ** {H11218} The [sqlite3_vfs_unregister(P)] interface unregisters the
6350 **          [sqlite3_vfs] object P so that it is no longer returned by
6351 **          subsequent calls to [sqlite3_vfs_find()].
6352 */
6353 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
6354 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
6355 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
6356
6357 /*
6358 ** CAPI3REF: Mutexes {H17000} <S20000>
6359 **
6360 ** The SQLite core uses these routines for thread
6361 ** synchronization. Though they are intended for internal
6362 ** use by SQLite, code that links against SQLite is
6363 ** permitted to use any of these routines.
6364 **
6365 ** The SQLite source code contains multiple implementations
6366 ** of these mutex routines.  An appropriate implementation
6367 ** is selected automatically at compile-time.  The following
6368 ** implementations are available in the SQLite core:
6369 **
6370 ** <ul>
6371 ** <li>   SQLITE_MUTEX_OS2
6372 ** <li>   SQLITE_MUTEX_PTHREAD
6373 ** <li>   SQLITE_MUTEX_W32
6374 ** <li>   SQLITE_MUTEX_NOOP
6375 ** </ul>
6376 **
6377 ** The SQLITE_MUTEX_NOOP implementation is a set of routines
6378 ** that does no real locking and is appropriate for use in
6379 ** a single-threaded application.  The SQLITE_MUTEX_OS2,
6380 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
6381 ** are appropriate for use on OS/2, Unix, and Windows.
6382 **
6383 ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
6384 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
6385 ** implementation is included with the library. In this case the
6386 ** application must supply a custom mutex implementation using the
6387 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
6388 ** before calling sqlite3_initialize() or any other public sqlite3_
6389 ** function that calls sqlite3_initialize().
6390 **
6391 ** {H17011} The sqlite3_mutex_alloc() routine allocates a new
6392 ** mutex and returns a pointer to it. {H17012} If it returns NULL
6393 ** that means that a mutex could not be allocated. {H17013} SQLite
6394 ** will unwind its stack and return an error. {H17014} The argument
6395 ** to sqlite3_mutex_alloc() is one of these integer constants:
6396 **
6397 ** <ul>
6398 ** <li>  SQLITE_MUTEX_FAST
6399 ** <li>  SQLITE_MUTEX_RECURSIVE
6400 ** <li>  SQLITE_MUTEX_STATIC_MASTER
6401 ** <li>  SQLITE_MUTEX_STATIC_MEM
6402 ** <li>  SQLITE_MUTEX_STATIC_MEM2
6403 ** <li>  SQLITE_MUTEX_STATIC_PRNG
6404 ** <li>  SQLITE_MUTEX_STATIC_LRU
6405 ** <li>  SQLITE_MUTEX_STATIC_LRU2
6406 ** </ul>
6407 **
6408 ** {H17015} The first two constants cause sqlite3_mutex_alloc() to create
6409 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
6410 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. {END}
6411 ** The mutex implementation does not need to make a distinction
6412 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
6413 ** not want to.  {H17016} But SQLite will only request a recursive mutex in
6414 ** cases where it really needs one.  {END} If a faster non-recursive mutex
6415 ** implementation is available on the host platform, the mutex subsystem
6416 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
6417 **
6418 ** {H17017} The other allowed parameters to sqlite3_mutex_alloc() each return
6419 ** a pointer to a static preexisting mutex. {END}  Four static mutexes are
6420 ** used by the current version of SQLite.  Future versions of SQLite
6421 ** may add additional static mutexes.  Static mutexes are for internal
6422 ** use by SQLite only.  Applications that use SQLite mutexes should
6423 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
6424 ** SQLITE_MUTEX_RECURSIVE.
6425 **
6426 ** {H17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
6427 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
6428 ** returns a different mutex on every call.  {H17034} But for the static
6429 ** mutex types, the same mutex is returned on every call that has
6430 ** the same type number.
6431 **
6432 ** {H17019} The sqlite3_mutex_free() routine deallocates a previously
6433 ** allocated dynamic mutex. {H17020} SQLite is careful to deallocate every
6434 ** dynamic mutex that it allocates. {A17021} The dynamic mutexes must not be in
6435 ** use when they are deallocated. {A17022} Attempting to deallocate a static
6436 ** mutex results in undefined behavior. {H17023} SQLite never deallocates
6437 ** a static mutex. {END}
6438 **
6439 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
6440 ** to enter a mutex. {H17024} If another thread is already within the mutex,
6441 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
6442 ** SQLITE_BUSY. {H17025}  The sqlite3_mutex_try() interface returns [SQLITE_OK]
6443 ** upon successful entry.  {H17026} Mutexes created using
6444 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
6445 ** {H17027} In such cases the,
6446 ** mutex must be exited an equal number of times before another thread
6447 ** can enter.  {A17028} If the same thread tries to enter any other
6448 ** kind of mutex more than once, the behavior is undefined.
6449 ** {H17029} SQLite will never exhibit
6450 ** such behavior in its own use of mutexes.
6451 **
6452 ** Some systems (for example, Windows 95) do not support the operation
6453 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
6454 ** will always return SQLITE_BUSY.  {H17030} The SQLite core only ever uses
6455 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.
6456 **
6457 ** {H17031} The sqlite3_mutex_leave() routine exits a mutex that was
6458 ** previously entered by the same thread.  {A17032} The behavior
6459 ** is undefined if the mutex is not currently entered by the
6460 ** calling thread or is not currently allocated.  {H17033} SQLite will
6461 ** never do either. {END}
6462 **
6463 ** If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
6464 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
6465 ** behave as no-ops.
6466 **
6467 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
6468 */
6469 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
6470 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
6471 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
6472 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
6473 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
6474
6475 /*
6476 ** CAPI3REF: Mutex Methods Object {H17120} <S20130>
6477 ** EXPERIMENTAL
6478 **
6479 ** An instance of this structure defines the low-level routines
6480 ** used to allocate and use mutexes.
6481 **
6482 ** Usually, the default mutex implementations provided by SQLite are
6483 ** sufficient, however the user has the option of substituting a custom
6484 ** implementation for specialized deployments or systems for which SQLite
6485 ** does not provide a suitable implementation. In this case, the user
6486 ** creates and populates an instance of this structure to pass
6487 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
6488 ** Additionally, an instance of this structure can be used as an
6489 ** output variable when querying the system for the current mutex
6490 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
6491 **
6492 ** The xMutexInit method defined by this structure is invoked as
6493 ** part of system initialization by the sqlite3_initialize() function.
6494 ** {H17001} The xMutexInit routine shall be called by SQLite once for each
6495 ** effective call to [sqlite3_initialize()].
6496 **
6497 ** The xMutexEnd method defined by this structure is invoked as
6498 ** part of system shutdown by the sqlite3_shutdown() function. The
6499 ** implementation of this method is expected to release all outstanding
6500 ** resources obtained by the mutex methods implementation, especially
6501 ** those obtained by the xMutexInit method. {H17003} The xMutexEnd()
6502 ** interface shall be invoked once for each call to [sqlite3_shutdown()].
6503 **
6504 ** The remaining seven methods defined by this structure (xMutexAlloc,
6505 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
6506 ** xMutexNotheld) implement the following interfaces (respectively):
6507 **
6508 ** <ul>
6509 **   <li>  [sqlite3_mutex_alloc()] </li>
6510 **   <li>  [sqlite3_mutex_free()] </li>
6511 **   <li>  [sqlite3_mutex_enter()] </li>
6512 **   <li>  [sqlite3_mutex_try()] </li>
6513 **   <li>  [sqlite3_mutex_leave()] </li>
6514 **   <li>  [sqlite3_mutex_held()] </li>
6515 **   <li>  [sqlite3_mutex_notheld()] </li>
6516 ** </ul>
6517 **
6518 ** The only difference is that the public sqlite3_XXX functions enumerated
6519 ** above silently ignore any invocations that pass a NULL pointer instead
6520 ** of a valid mutex handle. The implementations of the methods defined
6521 ** by this structure are not required to handle this case, the results
6522 ** of passing a NULL pointer instead of a valid mutex handle are undefined
6523 ** (i.e. it is acceptable to provide an implementation that segfaults if
6524 ** it is passed a NULL pointer).
6525 */
6526 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
6527 struct sqlite3_mutex_methods {
6528   int (*xMutexInit)(void);
6529   int (*xMutexEnd)(void);
6530   sqlite3_mutex *(*xMutexAlloc)(int);
6531   void (*xMutexFree)(sqlite3_mutex *);
6532   void (*xMutexEnter)(sqlite3_mutex *);
6533   int (*xMutexTry)(sqlite3_mutex *);
6534   void (*xMutexLeave)(sqlite3_mutex *);
6535   int (*xMutexHeld)(sqlite3_mutex *);
6536   int (*xMutexNotheld)(sqlite3_mutex *);
6537 };
6538
6539 /*
6540 ** CAPI3REF: Mutex Verification Routines {H17080} <S20130> <S30800>
6541 **
6542 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
6543 ** are intended for use inside assert() statements. {H17081} The SQLite core
6544 ** never uses these routines except inside an assert() and applications
6545 ** are advised to follow the lead of the core.  {H17082} The core only
6546 ** provides implementations for these routines when it is compiled
6547 ** with the SQLITE_DEBUG flag.  {A17087} External mutex implementations
6548 ** are only required to provide these routines if SQLITE_DEBUG is
6549 ** defined and if NDEBUG is not defined.
6550 **
6551 ** {H17083} These routines should return true if the mutex in their argument
6552 ** is held or not held, respectively, by the calling thread.
6553 **
6554 ** {X17084} The implementation is not required to provided versions of these
6555 ** routines that actually work. If the implementation does not provide working
6556 ** versions of these routines, it should at least provide stubs that always
6557 ** return true so that one does not get spurious assertion failures.
6558 **
6559 ** {H17085} If the argument to sqlite3_mutex_held() is a NULL pointer then
6560 ** the routine should return 1.  {END} This seems counter-intuitive since
6561 ** clearly the mutex cannot be held if it does not exist.  But the
6562 ** the reason the mutex does not exist is because the build is not
6563 ** using mutexes.  And we do not want the assert() containing the
6564 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
6565 ** the appropriate thing to do.  {H17086} The sqlite3_mutex_notheld()
6566 ** interface should also return 1 when given a NULL pointer.
6567 */
6568 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
6569 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
6570
6571 /*
6572 ** CAPI3REF: Mutex Types {H17001} <H17000>
6573 **
6574 ** The [sqlite3_mutex_alloc()] interface takes a single argument
6575 ** which is one of these integer constants.
6576 **
6577 ** The set of static mutexes may change from one SQLite release to the
6578 ** next.  Applications that override the built-in mutex logic must be
6579 ** prepared to accommodate additional static mutexes.
6580 */
6581 #define SQLITE_MUTEX_FAST             0
6582 #define SQLITE_MUTEX_RECURSIVE        1
6583 #define SQLITE_MUTEX_STATIC_MASTER    2
6584 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
6585 #define SQLITE_MUTEX_STATIC_MEM2      4  /* sqlite3_release_memory() */
6586 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
6587 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
6588 #define SQLITE_MUTEX_STATIC_LRU2      7  /* lru page list */
6589
6590 /*
6591 ** CAPI3REF: Low-Level Control Of Database Files {H11300} <S30800>
6592 **
6593 ** {H11301} The [sqlite3_file_control()] interface makes a direct call to the
6594 ** xFileControl method for the [sqlite3_io_methods] object associated
6595 ** with a particular database identified by the second argument. {H11302} The
6596 ** name of the database is the name assigned to the database by the
6597 ** <a href="lang_attach.html">ATTACH</a> SQL command that opened the
6598 ** database. {H11303} To control the main database file, use the name "main"
6599 ** or a NULL pointer. {H11304} The third and fourth parameters to this routine
6600 ** are passed directly through to the second and third parameters of
6601 ** the xFileControl method.  {H11305} The return value of the xFileControl
6602 ** method becomes the return value of this routine.
6603 **
6604 ** {H11306} If the second parameter (zDbName) does not match the name of any
6605 ** open database file, then SQLITE_ERROR is returned. {H11307} This error
6606 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
6607 ** or [sqlite3_errmsg()]. {A11308} The underlying xFileControl method might
6608 ** also return SQLITE_ERROR.  {A11309} There is no way to distinguish between
6609 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
6610 ** xFileControl method. {END}
6611 **
6612 ** See also: [SQLITE_FCNTL_LOCKSTATE]
6613 */
6614 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
6615
6616 /*
6617 ** CAPI3REF: Testing Interface {H11400} <S30800>
6618 **
6619 ** The sqlite3_test_control() interface is used to read out internal
6620 ** state of SQLite and to inject faults into SQLite for testing
6621 ** purposes.  The first parameter is an operation code that determines
6622 ** the number, meaning, and operation of all subsequent parameters.
6623 **
6624 ** This interface is not for use by applications.  It exists solely
6625 ** for verifying the correct operation of the SQLite library.  Depending
6626 ** on how the SQLite library is compiled, this interface might not exist.
6627 **
6628 ** The details of the operation codes, their meanings, the parameters
6629 ** they take, and what they do are all subject to change without notice.
6630 ** Unlike most of the SQLite API, this function is not guaranteed to
6631 ** operate consistently from one release to the next.
6632 */
6633 SQLITE_API int sqlite3_test_control(int op, ...);
6634
6635 /*
6636 ** CAPI3REF: Testing Interface Operation Codes {H11410} <H11400>
6637 **
6638 ** These constants are the valid operation code parameters used
6639 ** as the first argument to [sqlite3_test_control()].
6640 **
6641 ** These parameters and their meanings are subject to change
6642 ** without notice.  These values are for testing purposes only.
6643 ** Applications should not use any of these parameters or the
6644 ** [sqlite3_test_control()] interface.
6645 */
6646 #define SQLITE_TESTCTRL_PRNG_SAVE                5
6647 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
6648 #define SQLITE_TESTCTRL_PRNG_RESET               7
6649 #define SQLITE_TESTCTRL_BITVEC_TEST              8
6650 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
6651 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
6652
6653 /*
6654 ** CAPI3REF: SQLite Runtime Status {H17200} <S60200>
6655 ** EXPERIMENTAL
6656 **
6657 ** This interface is used to retrieve runtime status information
6658 ** about the preformance of SQLite, and optionally to reset various
6659 ** highwater marks.  The first argument is an integer code for
6660 ** the specific parameter to measure.  Recognized integer codes
6661 ** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].
6662 ** The current value of the parameter is returned into *pCurrent.
6663 ** The highest recorded value is returned in *pHighwater.  If the
6664 ** resetFlag is true, then the highest record value is reset after
6665 ** *pHighwater is written. Some parameters do not record the highest
6666 ** value.  For those parameters
6667 ** nothing is written into *pHighwater and the resetFlag is ignored.
6668 ** Other parameters record only the highwater mark and not the current
6669 ** value.  For these latter parameters nothing is written into *pCurrent.
6670 **
6671 ** This routine returns SQLITE_OK on success and a non-zero
6672 ** [error code] on failure.
6673 **
6674 ** This routine is threadsafe but is not atomic.  This routine can
6675 ** called while other threads are running the same or different SQLite
6676 ** interfaces.  However the values returned in *pCurrent and
6677 ** *pHighwater reflect the status of SQLite at different points in time
6678 ** and it is possible that another thread might change the parameter
6679 ** in between the times when *pCurrent and *pHighwater are written.
6680 **
6681 ** See also: [sqlite3_db_status()]
6682 */
6683 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
6684
6685 /*
6686 ** CAPI3REF: Database Connection Status {H17201} <S60200>
6687 ** EXPERIMENTAL
6688 **
6689 ** This interface is used to retrieve runtime status information 
6690 ** about a single [database connection].  The first argument is the
6691 ** database connection object to be interrogated.  The second argument
6692 ** is the parameter to interrogate.  Currently, the only allowed value
6693 ** for the second parameter is [SQLITE_DBSTATUS_LOOKASIDE_USED].
6694 ** Additional options will likely appear in future releases of SQLite.
6695 **
6696 ** The current value of the request parameter is written into *pCur
6697 ** and the highest instantaneous value is written into *pHiwtr.  If
6698 ** the resetFlg is true, then the highest instantaneous value is
6699 ** reset back down to the current value.
6700 **
6701 ** See also: [sqlite3_status()].
6702 */
6703 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6704
6705
6706 SQLITE_API int sqlite3_wsd_init(int N, int J);
6707 SQLITE_API void *sqlite3_wsd_find(void *K, int L);
6708
6709 /*
6710 ** CAPI3REF: Status Parameters {H17250} <H17200>
6711 ** EXPERIMENTAL
6712 **
6713 ** These integer constants designate various run-time status parameters
6714 ** that can be returned by [sqlite3_status()].
6715 **
6716 ** <dl>
6717 ** <dt>SQLITE_STATUS_MEMORY_USED</dt>
6718 ** <dd>This parameter is the current amount of memory checked out
6719 ** using [sqlite3_malloc()], either directly or indirectly.  The
6720 ** figure includes calls made to [sqlite3_malloc()] by the application
6721 ** and internal memory usage by the SQLite library.  Scratch memory
6722 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
6723 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
6724 ** this parameter.  The amount returned is the sum of the allocation
6725 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>
6726 **
6727 ** <dt>SQLITE_STATUS_MALLOC_SIZE</dt>
6728 ** <dd>This parameter records the largest memory allocation request
6729 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
6730 ** internal equivalents).  Only the value returned in the
6731 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6732 ** The value written into the *pCurrent parameter is undefined.</dd>
6733 **
6734 ** <dt>SQLITE_STATUS_PAGECACHE_USED</dt>
6735 ** <dd>This parameter returns the number of pages used out of the
6736 ** [pagecache memory allocator] that was configured using 
6737 ** [SQLITE_CONFIG_PAGECACHE].  The
6738 ** value returned is in pages, not in bytes.</dd>
6739 **
6740 ** <dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
6741 ** <dd>This parameter returns the number of bytes of page cache
6742 ** allocation which could not be statisfied by the [SQLITE_CONFIG_PAGECACHE]
6743 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
6744 ** returned value includes allocations that overflowed because they
6745 ** where too large (they were larger than the "sz" parameter to
6746 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
6747 ** no space was left in the page cache.</dd>
6748 **
6749 ** <dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
6750 ** <dd>This parameter records the largest memory allocation request
6751 ** handed to [pagecache memory allocator].  Only the value returned in the
6752 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6753 ** The value written into the *pCurrent parameter is undefined.</dd>
6754 **
6755 ** <dt>SQLITE_STATUS_SCRATCH_USED</dt>
6756 ** <dd>This parameter returns the number of allocations used out of the
6757 ** [scratch memory allocator] configured using
6758 ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
6759 ** in bytes.  Since a single thread may only have one scratch allocation
6760 ** outstanding at time, this parameter also reports the number of threads
6761 ** using scratch memory at the same time.</dd>
6762 **
6763 ** <dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6764 ** <dd>This parameter returns the number of bytes of scratch memory
6765 ** allocation which could not be statisfied by the [SQLITE_CONFIG_SCRATCH]
6766 ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
6767 ** returned include overflows because the requested allocation was too
6768 ** larger (that is, because the requested allocation was larger than the
6769 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6770 ** slots were available.
6771 ** </dd>
6772 **
6773 ** <dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6774 ** <dd>This parameter records the largest memory allocation request
6775 ** handed to [scratch memory allocator].  Only the value returned in the
6776 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6777 ** The value written into the *pCurrent parameter is undefined.</dd>
6778 **
6779 ** <dt>SQLITE_STATUS_PARSER_STACK</dt>
6780 ** <dd>This parameter records the deepest parser stack.  It is only
6781 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>
6782 ** </dl>
6783 **
6784 ** New status parameters may be added from time to time.
6785 */
6786 #define SQLITE_STATUS_MEMORY_USED          0
6787 #define SQLITE_STATUS_PAGECACHE_USED       1
6788 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
6789 #define SQLITE_STATUS_SCRATCH_USED         3
6790 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
6791 #define SQLITE_STATUS_MALLOC_SIZE          5
6792 #define SQLITE_STATUS_PARSER_STACK         6
6793 #define SQLITE_STATUS_PAGECACHE_SIZE       7
6794 #define SQLITE_STATUS_SCRATCH_SIZE         8
6795
6796 /*
6797 ** CAPI3REF: Status Parameters for database connections {H17275} <H17200>
6798 ** EXPERIMENTAL
6799 **
6800 ** Status verbs for [sqlite3_db_status()].
6801 **
6802 ** <dl>
6803 ** <dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6804 ** <dd>This parameter returns the number of lookaside memory slots currently
6805 ** checked out.</dd>
6806 ** </dl>
6807 */
6808 #define SQLITE_DBSTATUS_LOOKASIDE_USED     0
6809
6810 /*
6811 ** Undo the hack that converts floating point types to integer for
6812 ** builds on processors without floating point support.
6813 */
6814 #ifdef SQLITE_OMIT_FLOATING_POINT
6815 # undef double
6816 #endif
6817
6818 #if 0
6819 }  /* End of the 'extern "C"' block */
6820 #endif
6821 #endif
6822
6823 /************** End of sqlite3.h *********************************************/
6824 /************** Continuing where we left off in sqliteInt.h ******************/
6825 /************** Include hash.h in the middle of sqliteInt.h ******************/
6826 /************** Begin file hash.h ********************************************/
6827 /*
6828 ** 2001 September 22
6829 **
6830 ** The author disclaims copyright to this source code.  In place of
6831 ** a legal notice, here is a blessing:
6832 **
6833 **    May you do good and not evil.
6834 **    May you find forgiveness for yourself and forgive others.
6835 **    May you share freely, never taking more than you give.
6836 **
6837 *************************************************************************
6838 ** This is the header file for the generic hash-table implemenation
6839 ** used in SQLite.
6840 **
6841 ** $Id: hash.h,v 1.11 2007/09/04 14:31:47 danielk1977 Exp $
6842 */
6843 #ifndef _SQLITE_HASH_H_
6844 #define _SQLITE_HASH_H_
6845
6846 /* Forward declarations of structures. */
6847 typedef struct Hash Hash;
6848 typedef struct HashElem HashElem;
6849
6850 /* A complete hash table is an instance of the following structure.
6851 ** The internals of this structure are intended to be opaque -- client
6852 ** code should not attempt to access or modify the fields of this structure
6853 ** directly.  Change this structure only by using the routines below.
6854 ** However, many of the "procedures" and "functions" for modifying and
6855 ** accessing this structure are really macros, so we can't really make
6856 ** this structure opaque.
6857 */
6858 struct Hash {
6859   char keyClass;          /* SQLITE_HASH_INT, _POINTER, _STRING, _BINARY */
6860   char copyKey;           /* True if copy of key made on insert */
6861   int count;              /* Number of entries in this table */
6862   int htsize;             /* Number of buckets in the hash table */
6863   HashElem *first;        /* The first element of the array */
6864   struct _ht {            /* the hash table */
6865     int count;               /* Number of entries with this hash */
6866     HashElem *chain;         /* Pointer to first entry with this hash */
6867   } *ht;
6868 };
6869
6870 /* Each element in the hash table is an instance of the following 
6871 ** structure.  All elements are stored on a single doubly-linked list.
6872 **
6873 ** Again, this structure is intended to be opaque, but it can't really
6874 ** be opaque because it is used by macros.
6875 */
6876 struct HashElem {
6877   HashElem *next, *prev;   /* Next and previous elements in the table */
6878   void *data;              /* Data associated with this element */
6879   void *pKey; int nKey;    /* Key associated with this element */
6880 };
6881
6882 /*
6883 ** There are 4 different modes of operation for a hash table:
6884 **
6885 **   SQLITE_HASH_INT         nKey is used as the key and pKey is ignored.
6886 **
6887 **   SQLITE_HASH_POINTER     pKey is used as the key and nKey is ignored.
6888 **
6889 **   SQLITE_HASH_STRING      pKey points to a string that is nKey bytes long
6890 **                           (including the null-terminator, if any).  Case
6891 **                           is ignored in comparisons.
6892 **
6893 **   SQLITE_HASH_BINARY      pKey points to binary data nKey bytes long. 
6894 **                           memcmp() is used to compare keys.
6895 **
6896 ** A copy of the key is made for SQLITE_HASH_STRING and SQLITE_HASH_BINARY
6897 ** if the copyKey parameter to HashInit is 1.  
6898 */
6899 /* #define SQLITE_HASH_INT       1 // NOT USED */
6900 /* #define SQLITE_HASH_POINTER   2 // NOT USED */
6901 #define SQLITE_HASH_STRING    3
6902 #define SQLITE_HASH_BINARY    4
6903
6904 /*
6905 ** Access routines.  To delete, insert a NULL pointer.
6906 */
6907 SQLITE_PRIVATE void sqlite3HashInit(Hash*, int keytype, int copyKey);
6908 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const void *pKey, int nKey, void *pData);
6909 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const void *pKey, int nKey);
6910 SQLITE_PRIVATE HashElem *sqlite3HashFindElem(const Hash*, const void *pKey, int nKey);
6911 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
6912
6913 /*
6914 ** Macros for looping over all elements of a hash table.  The idiom is
6915 ** like this:
6916 **
6917 **   Hash h;
6918 **   HashElem *p;
6919 **   ...
6920 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
6921 **     SomeStructure *pData = sqliteHashData(p);
6922 **     // do something with pData
6923 **   }
6924 */
6925 #define sqliteHashFirst(H)  ((H)->first)
6926 #define sqliteHashNext(E)   ((E)->next)
6927 #define sqliteHashData(E)   ((E)->data)
6928 #define sqliteHashKey(E)    ((E)->pKey)
6929 #define sqliteHashKeysize(E) ((E)->nKey)
6930
6931 /*
6932 ** Number of entries in a hash table
6933 */
6934 #define sqliteHashCount(H)  ((H)->count)
6935
6936 #endif /* _SQLITE_HASH_H_ */
6937
6938 /************** End of hash.h ************************************************/
6939 /************** Continuing where we left off in sqliteInt.h ******************/
6940 /************** Include parse.h in the middle of sqliteInt.h *****************/
6941 /************** Begin file parse.h *******************************************/
6942 #define TK_SEMI                            1
6943 #define TK_EXPLAIN                         2
6944 #define TK_QUERY                           3
6945 #define TK_PLAN                            4
6946 #define TK_BEGIN                           5
6947 #define TK_TRANSACTION                     6
6948 #define TK_DEFERRED                        7
6949 #define TK_IMMEDIATE                       8
6950 #define TK_EXCLUSIVE                       9
6951 #define TK_COMMIT                         10
6952 #define TK_END                            11
6953 #define TK_ROLLBACK                       12
6954 #define TK_CREATE                         13
6955 #define TK_TABLE                          14
6956 #define TK_IF                             15
6957 #define TK_NOT                            16
6958 #define TK_EXISTS                         17
6959 #define TK_TEMP                           18
6960 #define TK_LP                             19
6961 #define TK_RP                             20
6962 #define TK_AS                             21
6963 #define TK_COMMA                          22
6964 #define TK_ID                             23
6965 #define TK_ABORT                          24
6966 #define TK_AFTER                          25
6967 #define TK_ANALYZE                        26
6968 #define TK_ASC                            27
6969 #define TK_ATTACH                         28
6970 #define TK_BEFORE                         29
6971 #define TK_CASCADE                        30
6972 #define TK_CAST                           31
6973 #define TK_CONFLICT                       32
6974 #define TK_DATABASE                       33
6975 #define TK_DESC                           34
6976 #define TK_DETACH                         35
6977 #define TK_EACH                           36
6978 #define TK_FAIL                           37
6979 #define TK_FOR                            38
6980 #define TK_IGNORE                         39
6981 #define TK_INITIALLY                      40
6982 #define TK_INSTEAD                        41
6983 #define TK_LIKE_KW                        42
6984 #define TK_MATCH                          43
6985 #define TK_KEY                            44
6986 #define TK_OF                             45
6987 #define TK_OFFSET                         46
6988 #define TK_PRAGMA                         47
6989 #define TK_RAISE                          48
6990 #define TK_REPLACE                        49
6991 #define TK_RESTRICT                       50
6992 #define TK_ROW                            51
6993 #define TK_TRIGGER                        52
6994 #define TK_VACUUM                         53
6995 #define TK_VIEW                           54
6996 #define TK_VIRTUAL                        55
6997 #define TK_REINDEX                        56
6998 #define TK_RENAME                         57
6999 #define TK_CTIME_KW                       58
7000 #define TK_ANY                            59
7001 #define TK_OR                             60
7002 #define TK_AND                            61
7003 #define TK_IS                             62
7004 #define TK_BETWEEN                        63
7005 #define TK_IN                             64
7006 #define TK_ISNULL                         65
7007 #define TK_NOTNULL                        66
7008 #define TK_NE                             67
7009 #define TK_EQ                             68
7010 #define TK_GT                             69
7011 #define TK_LE                             70
7012 #define TK_LT                             71
7013 #define TK_GE                             72
7014 #define TK_ESCAPE                         73
7015 #define TK_BITAND                         74
7016 #define TK_BITOR                          75
7017 #define TK_LSHIFT                         76
7018 #define TK_RSHIFT                         77
7019 #define TK_PLUS                           78
7020 #define TK_MINUS                          79
7021 #define TK_STAR                           80
7022 #define TK_SLASH                          81
7023 #define TK_REM                            82
7024 #define TK_CONCAT                         83
7025 #define TK_COLLATE                        84
7026 #define TK_UMINUS                         85
7027 #define TK_UPLUS                          86
7028 #define TK_BITNOT                         87
7029 #define TK_STRING                         88
7030 #define TK_JOIN_KW                        89
7031 #define TK_CONSTRAINT                     90
7032 #define TK_DEFAULT                        91
7033 #define TK_NULL                           92
7034 #define TK_PRIMARY                        93
7035 #define TK_UNIQUE                         94
7036 #define TK_CHECK                          95
7037 #define TK_REFERENCES                     96
7038 #define TK_AUTOINCR                       97
7039 #define TK_ON                             98
7040 #define TK_DELETE                         99
7041 #define TK_UPDATE                         100
7042 #define TK_INSERT                         101
7043 #define TK_SET                            102
7044 #define TK_DEFERRABLE                     103
7045 #define TK_FOREIGN                        104
7046 #define TK_DROP                           105
7047 #define TK_UNION                          106
7048 #define TK_ALL                            107
7049 #define TK_EXCEPT                         108
7050 #define TK_INTERSECT                      109
7051 #define TK_SELECT                         110
7052 #define TK_DISTINCT                       111
7053 #define TK_DOT                            112
7054 #define TK_FROM                           113
7055 #define TK_JOIN                           114
7056 #define TK_USING                          115
7057 #define TK_ORDER                          116
7058 #define TK_BY                             117
7059 #define TK_GROUP                          118
7060 #define TK_HAVING                         119
7061 #define TK_LIMIT                          120
7062 #define TK_WHERE                          121
7063 #define TK_INTO                           122
7064 #define TK_VALUES                         123
7065 #define TK_INTEGER                        124
7066 #define TK_FLOAT                          125
7067 #define TK_BLOB                           126
7068 #define TK_REGISTER                       127
7069 #define TK_VARIABLE                       128
7070 #define TK_CASE                           129
7071 #define TK_WHEN                           130
7072 #define TK_THEN                           131
7073 #define TK_ELSE                           132
7074 #define TK_INDEX                          133
7075 #define TK_ALTER                          134
7076 #define TK_TO                             135
7077 #define TK_ADD                            136
7078 #define TK_COLUMNKW                       137
7079 #define TK_TO_TEXT                        138
7080 #define TK_TO_BLOB                        139
7081 #define TK_TO_NUMERIC                     140
7082 #define TK_TO_INT                         141
7083 #define TK_TO_REAL                        142
7084 #define TK_END_OF_FILE                    143
7085 #define TK_ILLEGAL                        144
7086 #define TK_SPACE                          145
7087 #define TK_UNCLOSED_STRING                146
7088 #define TK_FUNCTION                       147
7089 #define TK_COLUMN                         148
7090 #define TK_AGG_FUNCTION                   149
7091 #define TK_AGG_COLUMN                     150
7092 #define TK_CONST_FUNC                     151
7093
7094 /************** End of parse.h ***********************************************/
7095 /************** Continuing where we left off in sqliteInt.h ******************/
7096 #include <stdio.h>
7097 #include <stdlib.h>
7098 #include <string.h>
7099 #include <assert.h>
7100 #include <stddef.h>
7101
7102 /*
7103 ** If compiling for a processor that lacks floating point support,
7104 ** substitute integer for floating-point
7105 */
7106 #ifdef SQLITE_OMIT_FLOATING_POINT
7107 # define double sqlite_int64
7108 # define LONGDOUBLE_TYPE sqlite_int64
7109 # ifndef SQLITE_BIG_DBL
7110 #   define SQLITE_BIG_DBL (0x7fffffffffffffff)
7111 # endif
7112 # define SQLITE_OMIT_DATETIME_FUNCS 1
7113 # define SQLITE_OMIT_TRACE 1
7114 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
7115 #endif
7116 #ifndef SQLITE_BIG_DBL
7117 # define SQLITE_BIG_DBL (1e99)
7118 #endif
7119
7120 /*
7121 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
7122 ** afterward. Having this macro allows us to cause the C compiler 
7123 ** to omit code used by TEMP tables without messy #ifndef statements.
7124 */
7125 #ifdef SQLITE_OMIT_TEMPDB
7126 #define OMIT_TEMPDB 1
7127 #else
7128 #define OMIT_TEMPDB 0
7129 #endif
7130
7131 /*
7132 ** If the following macro is set to 1, then NULL values are considered
7133 ** distinct when determining whether or not two entries are the same
7134 ** in a UNIQUE index.  This is the way PostgreSQL, Oracle, DB2, MySQL,
7135 ** OCELOT, and Firebird all work.  The SQL92 spec explicitly says this
7136 ** is the way things are suppose to work.
7137 **
7138 ** If the following macro is set to 0, the NULLs are indistinct for
7139 ** a UNIQUE index.  In this mode, you can only have a single NULL entry
7140 ** for a column declared UNIQUE.  This is the way Informix and SQL Server
7141 ** work.
7142 */
7143 #define NULL_DISTINCT_FOR_UNIQUE 1
7144
7145 /*
7146 ** The "file format" number is an integer that is incremented whenever
7147 ** the VDBE-level file format changes.  The following macros define the
7148 ** the default file format for new databases and the maximum file format
7149 ** that the library can read.
7150 */
7151 #define SQLITE_MAX_FILE_FORMAT 4
7152 #ifndef SQLITE_DEFAULT_FILE_FORMAT
7153 # define SQLITE_DEFAULT_FILE_FORMAT 1
7154 #endif
7155
7156 /*
7157 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
7158 ** on the command-line
7159 */
7160 #ifndef SQLITE_TEMP_STORE
7161 # define SQLITE_TEMP_STORE 1
7162 #endif
7163
7164 /*
7165 ** GCC does not define the offsetof() macro so we'll have to do it
7166 ** ourselves.
7167 */
7168 #ifndef offsetof
7169 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
7170 #endif
7171
7172 /*
7173 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
7174 ** not, there are still machines out there that use EBCDIC.)
7175 */
7176 #if 'A' == '\301'
7177 # define SQLITE_EBCDIC 1
7178 #else
7179 # define SQLITE_ASCII 1
7180 #endif
7181
7182 /*
7183 ** Integers of known sizes.  These typedefs might change for architectures
7184 ** where the sizes very.  Preprocessor macros are available so that the
7185 ** types can be conveniently redefined at compile-type.  Like this:
7186 **
7187 **         cc '-DUINTPTR_TYPE=long long int' ...
7188 */
7189 #ifndef UINT32_TYPE
7190 # ifdef HAVE_UINT32_T
7191 #  define UINT32_TYPE uint32_t
7192 # else
7193 #  define UINT32_TYPE unsigned int
7194 # endif
7195 #endif
7196 #ifndef UINT16_TYPE
7197 # ifdef HAVE_UINT16_T
7198 #  define UINT16_TYPE uint16_t
7199 # else
7200 #  define UINT16_TYPE unsigned short int
7201 # endif
7202 #endif
7203 #ifndef INT16_TYPE
7204 # ifdef HAVE_INT16_T
7205 #  define INT16_TYPE int16_t
7206 # else
7207 #  define INT16_TYPE short int
7208 # endif
7209 #endif
7210 #ifndef UINT8_TYPE
7211 # ifdef HAVE_UINT8_T
7212 #  define UINT8_TYPE uint8_t
7213 # else
7214 #  define UINT8_TYPE unsigned char
7215 # endif
7216 #endif
7217 #ifndef INT8_TYPE
7218 # ifdef HAVE_INT8_T
7219 #  define INT8_TYPE int8_t
7220 # else
7221 #  define INT8_TYPE signed char
7222 # endif
7223 #endif
7224 #ifndef LONGDOUBLE_TYPE
7225 # define LONGDOUBLE_TYPE long double
7226 #endif
7227 typedef sqlite_int64 i64;          /* 8-byte signed integer */
7228 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
7229 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
7230 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
7231 typedef INT16_TYPE i16;            /* 2-byte signed integer */
7232 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
7233 typedef INT8_TYPE i8;              /* 1-byte signed integer */
7234
7235 /*
7236 ** Macros to determine whether the machine is big or little endian,
7237 ** evaluated at runtime.
7238 */
7239 #ifdef SQLITE_AMALGAMATION
7240 SQLITE_PRIVATE const int sqlite3one;
7241 #else
7242 SQLITE_PRIVATE const int sqlite3one;
7243 #endif
7244 #if defined(i386) || defined(__i386__) || defined(_M_IX86)
7245 # define SQLITE_BIGENDIAN    0
7246 # define SQLITE_LITTLEENDIAN 1
7247 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
7248 #else
7249 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
7250 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
7251 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
7252 #endif
7253
7254 /*
7255 ** Constants for the largest and smallest possible 64-bit signed integers.
7256 ** These macros are designed to work correctly on both 32-bit and 64-bit
7257 ** compilers.
7258 */
7259 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
7260 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
7261
7262 /*
7263 ** An instance of the following structure is used to store the busy-handler
7264 ** callback for a given sqlite handle. 
7265 **
7266 ** The sqlite.busyHandler member of the sqlite struct contains the busy
7267 ** callback for the database handle. Each pager opened via the sqlite
7268 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
7269 ** callback is currently invoked only from within pager.c.
7270 */
7271 typedef struct BusyHandler BusyHandler;
7272 struct BusyHandler {
7273   int (*xFunc)(void *,int);  /* The busy callback */
7274   void *pArg;                /* First arg to busy callback */
7275   int nBusy;                 /* Incremented with each busy call */
7276 };
7277
7278 /*
7279 ** Name of the master database table.  The master database table
7280 ** is a special table that holds the names and attributes of all
7281 ** user tables and indices.
7282 */
7283 #define MASTER_NAME       "sqlite_master"
7284 #define TEMP_MASTER_NAME  "sqlite_temp_master"
7285
7286 /*
7287 ** The root-page of the master database table.
7288 */
7289 #define MASTER_ROOT       1
7290
7291 /*
7292 ** The name of the schema table.
7293 */
7294 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
7295
7296 /*
7297 ** A convenience macro that returns the number of elements in
7298 ** an array.
7299 */
7300 #define ArraySize(X)    (sizeof(X)/sizeof(X[0]))
7301
7302 /*
7303 ** The following value as a destructor means to use sqlite3DbFree().
7304 ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
7305 */
7306 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3DbFree)
7307
7308 /*
7309 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
7310 ** not support Writable Static Data (WSD) such as global and static variables.
7311 ** All variables must either be on the stack or dynamically allocated from
7312 ** the heap.  When WSD is unsupported, the variable declarations scattered
7313 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
7314 ** macro is used for this purpose.  And instead of referencing the variable
7315 ** directly, we use its constant as a key to lookup the run-time allocated
7316 ** buffer that holds real variable.  The constant is also the initializer
7317 ** for the run-time allocated buffer.
7318 **
7319 ** In the usually case where WSD is supported, the SQLITE_WSD and GLOBAL
7320 ** macros become no-ops and have zero performance impact.
7321 */
7322 #ifdef SQLITE_OMIT_WSD
7323   #define SQLITE_WSD const
7324   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
7325   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
7326 #else
7327   #define SQLITE_WSD 
7328   #define GLOBAL(t,v) v
7329   #define sqlite3GlobalConfig sqlite3Config
7330 #endif
7331
7332 /*
7333 ** Forward references to structures
7334 */
7335 typedef struct AggInfo AggInfo;
7336 typedef struct AuthContext AuthContext;
7337 typedef struct Bitvec Bitvec;
7338 typedef struct CollSeq CollSeq;
7339 typedef struct Column Column;
7340 typedef struct Db Db;
7341 typedef struct Schema Schema;
7342 typedef struct Expr Expr;
7343 typedef struct ExprList ExprList;
7344 typedef struct FKey FKey;
7345 typedef struct FuncDef FuncDef;
7346 typedef struct FuncDefHash FuncDefHash;
7347 typedef struct IdList IdList;
7348 typedef struct Index Index;
7349 typedef struct KeyClass KeyClass;
7350 typedef struct KeyInfo KeyInfo;
7351 typedef struct Lookaside Lookaside;
7352 typedef struct LookasideSlot LookasideSlot;
7353 typedef struct Module Module;
7354 typedef struct NameContext NameContext;
7355 typedef struct Parse Parse;
7356 typedef struct Select Select;
7357 typedef struct SrcList SrcList;
7358 typedef struct StrAccum StrAccum;
7359 typedef struct Table Table;
7360 typedef struct TableLock TableLock;
7361 typedef struct Token Token;
7362 typedef struct TriggerStack TriggerStack;
7363 typedef struct TriggerStep TriggerStep;
7364 typedef struct Trigger Trigger;
7365 typedef struct UnpackedRecord UnpackedRecord;
7366 typedef struct Walker Walker;
7367 typedef struct WhereInfo WhereInfo;
7368 typedef struct WhereLevel WhereLevel;
7369
7370 /*
7371 ** Defer sourcing vdbe.h and btree.h until after the "u8" and 
7372 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
7373 ** pointer types (i.e. FuncDef) defined above.
7374 */
7375 /************** Include btree.h in the middle of sqliteInt.h *****************/
7376 /************** Begin file btree.h *******************************************/
7377 /*
7378 ** 2001 September 15
7379 **
7380 ** The author disclaims copyright to this source code.  In place of
7381 ** a legal notice, here is a blessing:
7382 **
7383 **    May you do good and not evil.
7384 **    May you find forgiveness for yourself and forgive others.
7385 **    May you share freely, never taking more than you give.
7386 **
7387 *************************************************************************
7388 ** This header file defines the interface that the sqlite B-Tree file
7389 ** subsystem.  See comments in the source code for a detailed description
7390 ** of what each interface routine does.
7391 **
7392 ** @(#) $Id: btree.h,v 1.103 2008/08/13 19:11:48 drh Exp $
7393 */
7394 #ifndef _BTREE_H_
7395 #define _BTREE_H_
7396
7397 /* TODO: This definition is just included so other modules compile. It
7398 ** needs to be revisited.
7399 */
7400 #define SQLITE_N_BTREE_META 10
7401
7402 /*
7403 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
7404 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
7405 */
7406 #ifndef SQLITE_DEFAULT_AUTOVACUUM
7407   #define SQLITE_DEFAULT_AUTOVACUUM 0
7408 #endif
7409
7410 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
7411 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
7412 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
7413
7414 /*
7415 ** Forward declarations of structure
7416 */
7417 typedef struct Btree Btree;
7418 typedef struct BtCursor BtCursor;
7419 typedef struct BtShared BtShared;
7420 typedef struct BtreeMutexArray BtreeMutexArray;
7421
7422 /*
7423 ** This structure records all of the Btrees that need to hold
7424 ** a mutex before we enter sqlite3VdbeExec().  The Btrees are
7425 ** are placed in aBtree[] in order of aBtree[]->pBt.  That way,
7426 ** we can always lock and unlock them all quickly.
7427 */
7428 struct BtreeMutexArray {
7429   int nMutex;
7430   Btree *aBtree[SQLITE_MAX_ATTACHED+1];
7431 };
7432
7433
7434 SQLITE_PRIVATE int sqlite3BtreeOpen(
7435   const char *zFilename,   /* Name of database file to open */
7436   sqlite3 *db,             /* Associated database connection */
7437   Btree **,                /* Return open Btree* here */
7438   int flags,               /* Flags */
7439   int vfsFlags             /* Flags passed through to VFS open */
7440 );
7441
7442 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
7443 ** following values.
7444 **
7445 ** NOTE:  These values must match the corresponding PAGER_ values in
7446 ** pager.h.
7447 */
7448 #define BTREE_OMIT_JOURNAL  1  /* Do not use journal.  No argument */
7449 #define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
7450 #define BTREE_MEMORY        4  /* In-memory DB.  No argument */
7451 #define BTREE_READONLY      8  /* Open the database in read-only mode */
7452 #define BTREE_READWRITE    16  /* Open for both reading and writing */
7453 #define BTREE_CREATE       32  /* Create the database if it does not exist */
7454
7455 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
7456 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
7457 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
7458 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
7459 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree*,int,int);
7460 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
7461 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
7462 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
7463 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
7464 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
7465 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
7466 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
7467 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*);
7468 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
7469 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
7470 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*);
7471 SQLITE_PRIVATE int sqlite3BtreeCommitStmt(Btree*);
7472 SQLITE_PRIVATE int sqlite3BtreeRollbackStmt(Btree*);
7473 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
7474 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
7475 SQLITE_PRIVATE int sqlite3BtreeIsInStmt(Btree*);
7476 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
7477 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
7478 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *);
7479 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *, int, u8);
7480
7481 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
7482 SQLITE_PRIVATE const char *sqlite3BtreeGetDirname(Btree *);
7483 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
7484 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
7485
7486 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
7487
7488 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
7489 ** of the following flags:
7490 */
7491 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
7492 #define BTREE_ZERODATA   2    /* Table has keys only - no data */
7493 #define BTREE_LEAFDATA   4    /* Data stored in leaves only.  Implies INTKEY */
7494
7495 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
7496 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int);
7497 SQLITE_PRIVATE int sqlite3BtreeGetMeta(Btree*, int idx, u32 *pValue);
7498 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
7499 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
7500
7501 SQLITE_PRIVATE int sqlite3BtreeCursor(
7502   Btree*,                              /* BTree containing table to open */
7503   int iTable,                          /* Index of root page */
7504   int wrFlag,                          /* 1 for writing.  0 for read-only */
7505   struct KeyInfo*,                     /* First argument to compare function */
7506   BtCursor *pCursor                    /* Space to write cursor structure */
7507 );
7508 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
7509
7510 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
7511 SQLITE_PRIVATE int sqlite3BtreeMoveto(
7512   BtCursor*,
7513   const void *pKey,
7514   i64 nKey,
7515   int bias,
7516   int *pRes
7517 );
7518 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
7519   BtCursor*,
7520   UnpackedRecord *pUnKey,
7521   i64 intKey,
7522   int bias,
7523   int *pRes
7524 );
7525 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
7526 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
7527 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
7528                                   const void *pData, int nData,
7529                                   int nZero, int bias);
7530 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
7531 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
7532 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
7533 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
7534 SQLITE_PRIVATE int sqlite3BtreeFlags(BtCursor*);
7535 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
7536 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
7537 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
7538 SQLITE_PRIVATE sqlite3 *sqlite3BtreeCursorDb(const BtCursor*);
7539 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
7540 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
7541 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
7542 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
7543
7544 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
7545 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
7546
7547 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
7548 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
7549
7550 #ifdef SQLITE_TEST
7551 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
7552 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
7553 #endif
7554
7555 /*
7556 ** If we are not using shared cache, then there is no need to
7557 ** use mutexes to access the BtShared structures.  So make the
7558 ** Enter and Leave procedures no-ops.
7559 */
7560 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
7561 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
7562 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
7563 #ifndef NDEBUG
7564   /* This routine is used inside assert() statements only. */
7565 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
7566 #endif
7567 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
7568 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
7569 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
7570 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
7571 #ifndef NDEBUG
7572   /* This routine is used inside assert() statements only. */
7573 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
7574 #endif
7575 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*);
7576 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*);
7577 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*);
7578 #else
7579 # define sqlite3BtreeEnter(X)
7580 # define sqlite3BtreeLeave(X)
7581 #ifndef NDEBUG
7582   /* This routine is used inside assert() statements only. */
7583 # define sqlite3BtreeHoldsMutex(X) 1
7584 #endif
7585 # define sqlite3BtreeEnterCursor(X)
7586 # define sqlite3BtreeLeaveCursor(X)
7587 # define sqlite3BtreeEnterAll(X)
7588 # define sqlite3BtreeLeaveAll(X)
7589 #ifndef NDEBUG
7590   /* This routine is used inside assert() statements only. */
7591 # define sqlite3BtreeHoldsAllMutexes(X) 1
7592 #endif
7593 # define sqlite3BtreeMutexArrayEnter(X)
7594 # define sqlite3BtreeMutexArrayLeave(X)
7595 # define sqlite3BtreeMutexArrayInsert(X,Y)
7596 #endif
7597
7598
7599 #endif /* _BTREE_H_ */
7600
7601 /************** End of btree.h ***********************************************/
7602 /************** Continuing where we left off in sqliteInt.h ******************/
7603 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
7604 /************** Begin file vdbe.h ********************************************/
7605 /*
7606 ** 2001 September 15
7607 **
7608 ** The author disclaims copyright to this source code.  In place of
7609 ** a legal notice, here is a blessing:
7610 **
7611 **    May you do good and not evil.
7612 **    May you find forgiveness for yourself and forgive others.
7613 **    May you share freely, never taking more than you give.
7614 **
7615 *************************************************************************
7616 ** Header file for the Virtual DataBase Engine (VDBE)
7617 **
7618 ** This header defines the interface to the virtual database engine
7619 ** or VDBE.  The VDBE implements an abstract machine that runs a
7620 ** simple program to access and modify the underlying database.
7621 **
7622 ** $Id: vdbe.h,v 1.138 2008/08/20 22:06:48 drh Exp $
7623 */
7624 #ifndef _SQLITE_VDBE_H_
7625 #define _SQLITE_VDBE_H_
7626
7627 /*
7628 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
7629 ** in the source file sqliteVdbe.c are allowed to see the insides
7630 ** of this structure.
7631 */
7632 typedef struct Vdbe Vdbe;
7633
7634 /*
7635 ** The names of the following types declared in vdbeInt.h are required
7636 ** for the VdbeOp definition.
7637 */
7638 typedef struct VdbeFunc VdbeFunc;
7639 typedef struct Mem Mem;
7640
7641 /*
7642 ** A single instruction of the virtual machine has an opcode
7643 ** and as many as three operands.  The instruction is recorded
7644 ** as an instance of the following structure:
7645 */
7646 struct VdbeOp {
7647   u8 opcode;          /* What operation to perform */
7648   signed char p4type; /* One of the P4_xxx constants for p4 */
7649   u8 opflags;         /* Not currently used */
7650   u8 p5;              /* Fifth parameter is an unsigned character */
7651   int p1;             /* First operand */
7652   int p2;             /* Second parameter (often the jump destination) */
7653   int p3;             /* The third parameter */
7654   union {             /* forth parameter */
7655     int i;                 /* Integer value if p4type==P4_INT32 */
7656     void *p;               /* Generic pointer */
7657     char *z;               /* Pointer to data for string (char array) types */
7658     i64 *pI64;             /* Used when p4type is P4_INT64 */
7659     double *pReal;         /* Used when p4type is P4_REAL */
7660     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
7661     VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
7662     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
7663     Mem *pMem;             /* Used when p4type is P4_MEM */
7664     sqlite3_vtab *pVtab;   /* Used when p4type is P4_VTAB */
7665     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
7666     int *ai;               /* Used when p4type is P4_INTARRAY */
7667   } p4;
7668 #ifdef SQLITE_DEBUG
7669   char *zComment;          /* Comment to improve readability */
7670 #endif
7671 #ifdef VDBE_PROFILE
7672   int cnt;                 /* Number of times this instruction was executed */
7673   u64 cycles;              /* Total time spent executing this instruction */
7674 #endif
7675 };
7676 typedef struct VdbeOp VdbeOp;
7677
7678 /*
7679 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
7680 ** it takes up less space.
7681 */
7682 struct VdbeOpList {
7683   u8 opcode;          /* What operation to perform */
7684   signed char p1;     /* First operand */
7685   signed char p2;     /* Second parameter (often the jump destination) */
7686   signed char p3;     /* Third parameter */
7687 };
7688 typedef struct VdbeOpList VdbeOpList;
7689
7690 /*
7691 ** Allowed values of VdbeOp.p3type
7692 */
7693 #define P4_NOTUSED    0   /* The P4 parameter is not used */
7694 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
7695 #define P4_STATIC   (-2)  /* Pointer to a static string */
7696 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
7697 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
7698 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
7699 #define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
7700 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
7701 #define P4_TRANSIENT (-9) /* P4 is a pointer to a transient string */
7702 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
7703 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
7704 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
7705 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
7706 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
7707 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
7708
7709 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
7710 ** is made.  That copy is freed when the Vdbe is finalized.  But if the
7711 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
7712 ** gets freed when the Vdbe is finalized so it still should be obtained
7713 ** from a single sqliteMalloc().  But no copy is made and the calling
7714 ** function should *not* try to free the KeyInfo.
7715 */
7716 #define P4_KEYINFO_HANDOFF (-16)
7717 #define P4_KEYINFO_STATIC  (-17)
7718
7719 /*
7720 ** The Vdbe.aColName array contains 5n Mem structures, where n is the 
7721 ** number of columns of data returned by the statement.
7722 */
7723 #define COLNAME_NAME     0
7724 #define COLNAME_DECLTYPE 1
7725 #define COLNAME_DATABASE 2
7726 #define COLNAME_TABLE    3
7727 #define COLNAME_COLUMN   4
7728 #ifdef SQLITE_ENABLE_COLUMN_METADATA
7729 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
7730 #else
7731 # ifdef SQLITE_OMIT_DECLTYPE
7732 #   define COLNAME_N      1      /* Store only the name */
7733 # else
7734 #   define COLNAME_N      2      /* Store the name and decltype */
7735 # endif
7736 #endif
7737
7738 /*
7739 ** The following macro converts a relative address in the p2 field
7740 ** of a VdbeOp structure into a negative number so that 
7741 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
7742 ** the macro again restores the address.
7743 */
7744 #define ADDR(X)  (-1-(X))
7745
7746 /*
7747 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
7748 ** header file that defines a number for each opcode used by the VDBE.
7749 */
7750 /************** Include opcodes.h in the middle of vdbe.h ********************/
7751 /************** Begin file opcodes.h *****************************************/
7752 /* Automatically generated.  Do not edit */
7753 /* See the mkopcodeh.awk script for details */
7754 #define OP_VNext                                1
7755 #define OP_Affinity                             2
7756 #define OP_Column                               3
7757 #define OP_SetCookie                            4
7758 #define OP_Real                               125   /* same as TK_FLOAT    */
7759 #define OP_Sequence                             5
7760 #define OP_MoveGt                               6
7761 #define OP_Ge                                  72   /* same as TK_GE       */
7762 #define OP_RowKey                               7
7763 #define OP_SCopy                                8
7764 #define OP_Eq                                  68   /* same as TK_EQ       */
7765 #define OP_OpenWrite                            9
7766 #define OP_NotNull                             66   /* same as TK_NOTNULL  */
7767 #define OP_If                                  10
7768 #define OP_ToInt                              141   /* same as TK_TO_INT   */
7769 #define OP_String8                             88   /* same as TK_STRING   */
7770 #define OP_VRowid                              11
7771 #define OP_CollSeq                             12
7772 #define OP_OpenRead                            13
7773 #define OP_Expire                              14
7774 #define OP_AutoCommit                          15
7775 #define OP_Gt                                  69   /* same as TK_GT       */
7776 #define OP_Pagecount                           17
7777 #define OP_IntegrityCk                         18
7778 #define OP_Sort                                19
7779 #define OP_Copy                                20
7780 #define OP_Trace                               21
7781 #define OP_Function                            22
7782 #define OP_IfNeg                               23
7783 #define OP_And                                 61   /* same as TK_AND      */
7784 #define OP_Subtract                            79   /* same as TK_MINUS    */
7785 #define OP_Noop                                24
7786 #define OP_Return                              25
7787 #define OP_Remainder                           82   /* same as TK_REM      */
7788 #define OP_NewRowid                            26
7789 #define OP_Multiply                            80   /* same as TK_STAR     */
7790 #define OP_Variable                            27
7791 #define OP_String                              28
7792 #define OP_RealAffinity                        29
7793 #define OP_VRename                             30
7794 #define OP_ParseSchema                         31
7795 #define OP_VOpen                               32
7796 #define OP_Close                               33
7797 #define OP_CreateIndex                         34
7798 #define OP_IsUnique                            35
7799 #define OP_NotFound                            36
7800 #define OP_Int64                               37
7801 #define OP_MustBeInt                           38
7802 #define OP_Halt                                39
7803 #define OP_Rowid                               40
7804 #define OP_IdxLT                               41
7805 #define OP_AddImm                              42
7806 #define OP_Statement                           43
7807 #define OP_RowData                             44
7808 #define OP_MemMax                              45
7809 #define OP_Or                                  60   /* same as TK_OR       */
7810 #define OP_NotExists                           46
7811 #define OP_Gosub                               47
7812 #define OP_Divide                              81   /* same as TK_SLASH    */
7813 #define OP_Integer                             48
7814 #define OP_ToNumeric                          140   /* same as TK_TO_NUMERIC*/
7815 #define OP_Prev                                49
7816 #define OP_Concat                              83   /* same as TK_CONCAT   */
7817 #define OP_BitAnd                              74   /* same as TK_BITAND   */
7818 #define OP_VColumn                             50
7819 #define OP_CreateTable                         51
7820 #define OP_Last                                52
7821 #define OP_IsNull                              65   /* same as TK_ISNULL   */
7822 #define OP_IncrVacuum                          53
7823 #define OP_IdxRowid                            54
7824 #define OP_ShiftRight                          77   /* same as TK_RSHIFT   */
7825 #define OP_ResetCount                          55
7826 #define OP_FifoWrite                           56
7827 #define OP_ContextPush                         57
7828 #define OP_Yield                               58
7829 #define OP_DropTrigger                         59
7830 #define OP_DropIndex                           62
7831 #define OP_IdxGE                               63
7832 #define OP_IdxDelete                           64
7833 #define OP_Vacuum                              73
7834 #define OP_MoveLe                              84
7835 #define OP_IfNot                               85
7836 #define OP_DropTable                           86
7837 #define OP_MakeRecord                          89
7838 #define OP_ToBlob                             139   /* same as TK_TO_BLOB  */
7839 #define OP_ResultRow                           90
7840 #define OP_Delete                              91
7841 #define OP_AggFinal                            92
7842 #define OP_Compare                             93
7843 #define OP_ShiftLeft                           76   /* same as TK_LSHIFT   */
7844 #define OP_Goto                                94
7845 #define OP_TableLock                           95
7846 #define OP_FifoRead                            96
7847 #define OP_Clear                               97
7848 #define OP_MoveLt                              98
7849 #define OP_Le                                  70   /* same as TK_LE       */
7850 #define OP_VerifyCookie                        99
7851 #define OP_AggStep                            100
7852 #define OP_ToText                             138   /* same as TK_TO_TEXT  */
7853 #define OP_Not                                 16   /* same as TK_NOT      */
7854 #define OP_ToReal                             142   /* same as TK_TO_REAL  */
7855 #define OP_SetNumColumns                      101
7856 #define OP_Transaction                        102
7857 #define OP_VFilter                            103
7858 #define OP_Ne                                  67   /* same as TK_NE       */
7859 #define OP_VDestroy                           104
7860 #define OP_ContextPop                         105
7861 #define OP_BitOr                               75   /* same as TK_BITOR    */
7862 #define OP_Next                               106
7863 #define OP_IdxInsert                          107
7864 #define OP_Lt                                  71   /* same as TK_LT       */
7865 #define OP_Insert                             108
7866 #define OP_Destroy                            109
7867 #define OP_ReadCookie                         110
7868 #define OP_ForceInt                           111
7869 #define OP_LoadAnalysis                       112
7870 #define OP_Explain                            113
7871 #define OP_OpenPseudo                         114
7872 #define OP_OpenEphemeral                      115
7873 #define OP_Null                               116
7874 #define OP_Move                               117
7875 #define OP_Blob                               118
7876 #define OP_Add                                 78   /* same as TK_PLUS     */
7877 #define OP_Rewind                             119
7878 #define OP_MoveGe                             120
7879 #define OP_VBegin                             121
7880 #define OP_VUpdate                            122
7881 #define OP_IfZero                             123
7882 #define OP_BitNot                              87   /* same as TK_BITNOT   */
7883 #define OP_VCreate                            124
7884 #define OP_Found                              126
7885 #define OP_IfPos                              127
7886 #define OP_NullRow                            128
7887 #define OP_Jump                               129
7888 #define OP_Permutation                        130
7889
7890 /* The following opcode values are never used */
7891 #define OP_NotUsed_131                        131
7892 #define OP_NotUsed_132                        132
7893 #define OP_NotUsed_133                        133
7894 #define OP_NotUsed_134                        134
7895 #define OP_NotUsed_135                        135
7896 #define OP_NotUsed_136                        136
7897 #define OP_NotUsed_137                        137
7898
7899
7900 /* Properties such as "out2" or "jump" that are specified in
7901 ** comments following the "case" for each opcode in the vdbe.c
7902 ** are encoded into bitvectors as follows:
7903 */
7904 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
7905 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
7906 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
7907 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
7908 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
7909 #define OPFLG_OUT3            0x0020  /* out3:  P3 is an output */
7910 #define OPFLG_INITIALIZER {\
7911 /*   0 */ 0x00, 0x01, 0x00, 0x00, 0x10, 0x02, 0x11, 0x00,\
7912 /*   8 */ 0x00, 0x00, 0x05, 0x02, 0x00, 0x00, 0x00, 0x00,\
7913 /*  16 */ 0x04, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x05,\
7914 /*  24 */ 0x00, 0x04, 0x02, 0x02, 0x02, 0x04, 0x00, 0x00,\
7915 /*  32 */ 0x00, 0x00, 0x02, 0x11, 0x11, 0x02, 0x05, 0x00,\
7916 /*  40 */ 0x02, 0x11, 0x04, 0x00, 0x00, 0x0c, 0x11, 0x01,\
7917 /*  48 */ 0x02, 0x01, 0x00, 0x02, 0x01, 0x01, 0x02, 0x00,\
7918 /*  56 */ 0x04, 0x00, 0x00, 0x00, 0x2c, 0x2c, 0x00, 0x11,\
7919 /*  64 */ 0x00, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
7920 /*  72 */ 0x15, 0x00, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c,\
7921 /*  80 */ 0x2c, 0x2c, 0x2c, 0x2c, 0x11, 0x05, 0x00, 0x04,\
7922 /*  88 */ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00,\
7923 /*  96 */ 0x01, 0x00, 0x11, 0x00, 0x00, 0x00, 0x00, 0x01,\
7924 /* 104 */ 0x00, 0x00, 0x01, 0x08, 0x00, 0x02, 0x02, 0x05,\
7925 /* 112 */ 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x02, 0x01,\
7926 /* 120 */ 0x11, 0x00, 0x00, 0x05, 0x00, 0x02, 0x11, 0x05,\
7927 /* 128 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
7928 /* 136 */ 0x00, 0x00, 0x04, 0x04, 0x04, 0x04, 0x04,}
7929
7930 /************** End of opcodes.h *********************************************/
7931 /************** Continuing where we left off in vdbe.h ***********************/
7932
7933 /*
7934 ** Prototypes for the VDBE interface.  See comments on the implementation
7935 ** for a description of what each of these routines does.
7936 */
7937 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
7938 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
7939 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
7940 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
7941 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
7942 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
7943 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
7944 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
7945 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
7946 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
7947 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
7948 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
7949 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
7950 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
7951 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
7952 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
7953 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
7954 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
7955 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int);
7956 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
7957 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
7958 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
7959 #ifdef SQLITE_DEBUG
7960 SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
7961 #endif
7962 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
7963 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
7964 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
7965 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, int);
7966 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
7967 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
7968 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n);
7969 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
7970
7971 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
7972 SQLITE_PRIVATE int sqlite3VdbeReleaseMemory(int);
7973 #endif
7974 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,
7975                                         UnpackedRecord*,int);
7976 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
7977 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
7978
7979
7980 #ifndef NDEBUG
7981 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
7982 # define VdbeComment(X)  sqlite3VdbeComment X
7983 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
7984 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
7985 #else
7986 # define VdbeComment(X)
7987 # define VdbeNoopComment(X)
7988 #endif
7989
7990 #endif
7991
7992 /************** End of vdbe.h ************************************************/
7993 /************** Continuing where we left off in sqliteInt.h ******************/
7994 /************** Include pager.h in the middle of sqliteInt.h *****************/
7995 /************** Begin file pager.h *******************************************/
7996 /*
7997 ** 2001 September 15
7998 **
7999 ** The author disclaims copyright to this source code.  In place of
8000 ** a legal notice, here is a blessing:
8001 **
8002 **    May you do good and not evil.
8003 **    May you find forgiveness for yourself and forgive others.
8004 **    May you share freely, never taking more than you give.
8005 **
8006 *************************************************************************
8007 ** This header file defines the interface that the sqlite page cache
8008 ** subsystem.  The page cache subsystem reads and writes a file a page
8009 ** at a time and provides a journal for rollback.
8010 **
8011 ** @(#) $Id: pager.h,v 1.83 2008/09/18 17:34:44 danielk1977 Exp $
8012 */
8013
8014 #ifndef _PAGER_H_
8015 #define _PAGER_H_
8016
8017 /*
8018 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
8019 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
8020 */
8021 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
8022   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
8023 #endif
8024
8025 /*
8026 ** The type used to represent a page number.  The first page in a file
8027 ** is called page 1.  0 is used to represent "not a page".
8028 */
8029 typedef u32 Pgno;
8030
8031 /*
8032 ** Each open file is managed by a separate instance of the "Pager" structure.
8033 */
8034 typedef struct Pager Pager;
8035
8036 /*
8037 ** Handle type for pages.
8038 */
8039 typedef struct PgHdr DbPage;
8040
8041 /*
8042 ** Allowed values for the flags parameter to sqlite3PagerOpen().
8043 **
8044 ** NOTE: This values must match the corresponding BTREE_ values in btree.h.
8045 */
8046 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
8047 #define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */
8048
8049 /*
8050 ** Valid values for the second argument to sqlite3PagerLockingMode().
8051 */
8052 #define PAGER_LOCKINGMODE_QUERY      -1
8053 #define PAGER_LOCKINGMODE_NORMAL      0
8054 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
8055
8056 /*
8057 ** Valid values for the second argument to sqlite3PagerJournalMode().
8058 */
8059 #define PAGER_JOURNALMODE_QUERY      -1
8060 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
8061 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
8062 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
8063
8064 /*
8065 ** See source code comments for a detailed description of the following
8066 ** routines:
8067 */
8068 SQLITE_PRIVATE int sqlite3PagerOpen(sqlite3_vfs *, Pager **ppPager, const char*, void(*)(DbPage*), int,int,int);
8069 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, BusyHandler *pBusyHandler);
8070 SQLITE_PRIVATE void sqlite3PagerSetReiniter(Pager*, void(*)(DbPage*));
8071 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u16*);
8072 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
8073 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
8074 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
8075 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
8076 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
8077 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
8078 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
8079 SQLITE_PRIVATE int sqlite3PagerRef(DbPage*);
8080 SQLITE_PRIVATE int sqlite3PagerUnref(DbPage*);
8081 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
8082 SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*, int*);
8083 SQLITE_PRIVATE int sqlite3PagerTruncate(Pager*,Pgno);
8084 SQLITE_PRIVATE int sqlite3PagerBegin(DbPage*, int exFlag);
8085 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, Pgno, int);
8086 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
8087 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
8088 SQLITE_PRIVATE int sqlite3PagerIsreadonly(Pager*);
8089 SQLITE_PRIVATE int sqlite3PagerStmtBegin(Pager*);
8090 SQLITE_PRIVATE int sqlite3PagerStmtCommit(Pager*);
8091 SQLITE_PRIVATE int sqlite3PagerStmtRollback(Pager*);
8092 SQLITE_PRIVATE void sqlite3PagerDontRollback(DbPage*);
8093 SQLITE_PRIVATE int sqlite3PagerDontWrite(DbPage*);
8094 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
8095 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int);
8096 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
8097 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
8098 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
8099 SQLITE_PRIVATE const char *sqlite3PagerDirname(Pager*);
8100 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
8101 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
8102 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
8103 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
8104 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
8105 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
8106 SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *, int);
8107 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
8108 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
8109 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
8110
8111 #ifdef SQLITE_HAS_CODEC
8112 SQLITE_PRIVATE   void sqlite3PagerSetCodec(Pager*,void*(*)(void*,void*,Pgno,int),void*);
8113 #endif
8114
8115 #if !defined(NDEBUG) || defined(SQLITE_TEST)
8116 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
8117 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
8118 #endif
8119
8120 #ifdef SQLITE_TEST
8121 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
8122 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
8123 SQLITE_PRIVATE   int sqlite3PagerIsMemdb(Pager*);
8124 #endif
8125
8126 #ifdef SQLITE_TEST
8127 void disable_simulated_io_errors(void);
8128 void enable_simulated_io_errors(void);
8129 #else
8130 # define disable_simulated_io_errors()
8131 # define enable_simulated_io_errors()
8132 #endif
8133
8134 #endif /* _PAGER_H_ */
8135
8136 /************** End of pager.h ***********************************************/
8137 /************** Continuing where we left off in sqliteInt.h ******************/
8138 /************** Include pcache.h in the middle of sqliteInt.h ****************/
8139 /************** Begin file pcache.h ******************************************/
8140 /*
8141 ** 2008 August 05
8142 **
8143 ** The author disclaims copyright to this source code.  In place of
8144 ** a legal notice, here is a blessing:
8145 **
8146 **    May you do good and not evil.
8147 **    May you find forgiveness for yourself and forgive others.
8148 **    May you share freely, never taking more than you give.
8149 **
8150 *************************************************************************
8151 ** This header file defines the interface that the sqlite page cache
8152 ** subsystem. 
8153 **
8154 ** @(#) $Id: pcache.h,v 1.11 2008/09/18 17:34:44 danielk1977 Exp $
8155 */
8156
8157 #ifndef _PCACHE_H_
8158
8159 typedef struct PgHdr PgHdr;
8160 typedef struct PCache PCache;
8161
8162 /*
8163 ** Every page in the cache is controlled by an instance of the following
8164 ** structure.
8165 */
8166 struct PgHdr {
8167   void *pData;                   /* Content of this page */
8168   void *pExtra;                  /* Extra content */
8169   PgHdr *pDirty;                 /* Transient list of dirty pages */
8170   Pgno pgno;                     /* Page number for this page */
8171   Pager *pPager;                 /* The pager this page is part of */
8172 #ifdef SQLITE_CHECK_PAGES
8173   u32 pageHash;                  /* Hash of page content */
8174 #endif
8175   u16 flags;                     /* PGHDR flags defined below */
8176   /**********************************************************************
8177   ** Elements above are public.  All that follows is private to pcache.c
8178   ** and should not be accessed by other modules.
8179   */
8180   i16 nRef;                      /* Number of users of this page */
8181   PCache *pCache;                /* Cache that owns this page */
8182   void *apSave[2];               /* Journal entries for in-memory databases */
8183   /**********************************************************************
8184   ** Elements above are accessible at any time by the owner of the cache
8185   ** without the need for a mutex.  The elements that follow can only be
8186   ** accessed while holding the SQLITE_MUTEX_STATIC_LRU mutex.
8187   */
8188   PgHdr *pNextHash, *pPrevHash;  /* Hash collision chain for PgHdr.pgno */
8189   PgHdr *pNext, *pPrev;          /* List of clean or dirty pages */
8190   PgHdr *pNextLru, *pPrevLru;    /* Part of global LRU list */
8191 };
8192
8193 /* Bit values for PgHdr.flags */
8194 #define PGHDR_IN_JOURNAL        0x001  /* Page is in rollback journal */
8195 #define PGHDR_DIRTY             0x002  /* Page has changed */
8196 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
8197                                        ** writing this page to the database */
8198 #define PGHDR_NEED_READ         0x008  /* Content is unread */
8199 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
8200 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
8201
8202 /* Initialize and shutdown the page cache subsystem */
8203 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
8204 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
8205
8206 /* Page cache buffer management:
8207 ** These routines implement SQLITE_CONFIG_PAGECACHE.
8208 */
8209 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
8210 SQLITE_PRIVATE void *sqlite3PCacheMalloc(int sz);
8211 SQLITE_PRIVATE void sqlite3PCacheFree(void*);
8212
8213 /* Create a new pager cache.
8214 ** Under memory stress, invoke xStress to try to make pages clean.
8215 ** Only clean and unpinned pages can be reclaimed.
8216 */
8217 SQLITE_PRIVATE void sqlite3PcacheOpen(
8218   int szPage,                    /* Size of every page */
8219   int szExtra,                   /* Extra space associated with each page */
8220   int bPurgeable,                /* True if pages are on backing store */
8221   void (*xDestroy)(PgHdr *),     /* Called to destroy a page */
8222   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
8223   void *pStress,                 /* Argument to xStress */
8224   PCache *pToInit                /* Preallocated space for the PCache */
8225 );
8226
8227 /* Modify the page-size after the cache has been created. */
8228 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
8229
8230 /* Return the size in bytes of a PCache object.  Used to preallocate
8231 ** storage space.
8232 */
8233 SQLITE_PRIVATE int sqlite3PcacheSize(void);
8234
8235 /* One release per successful fetch.  Page is pinned until released.
8236 ** Reference counted. 
8237 */
8238 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
8239 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
8240
8241 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
8242 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
8243 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
8244 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
8245
8246 /* Change a page number.  Used by incr-vacuum. */
8247 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
8248
8249 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
8250 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
8251
8252 /* Routines used to implement transactions on memory-only databases. */
8253 SQLITE_PRIVATE int sqlite3PcachePreserve(PgHdr*, int);    /* Preserve current page content */
8254 SQLITE_PRIVATE void sqlite3PcacheCommit(PCache*, int);    /* Drop preserved copy */
8255 SQLITE_PRIVATE void sqlite3PcacheRollback(PCache*, int, void (*xReiniter)(PgHdr*));
8256
8257 /* Get a list of all dirty pages in the cache, sorted by page number */
8258 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
8259
8260 /* Reset and close the cache object */
8261 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
8262
8263 /* Clear flags from pages of the page cache */
8264 SQLITE_PRIVATE void sqlite3PcacheClearFlags(PCache*, int mask);
8265
8266 /* Assert flags settings on all pages.  Debugging only */
8267 #ifndef NDEBUG
8268 SQLITE_PRIVATE   void sqlite3PcacheAssertFlags(PCache*, int trueMask, int falseMask);
8269 #else
8270 # define sqlite3PcacheAssertFlags(A,B,C)
8271 #endif
8272
8273 /* Return true if the number of dirty pages is 0 or 1 */
8274 SQLITE_PRIVATE int sqlite3PcacheZeroOrOneDirtyPages(PCache*);
8275
8276 /* Discard the contents of the cache */
8277 SQLITE_PRIVATE int sqlite3PcacheClear(PCache*);
8278
8279 /* Return the total number of outstanding page references */
8280 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
8281
8282 /* Increment the reference count of an existing page */
8283 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
8284
8285 /* Return the total number of pages stored in the cache */
8286 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
8287
8288 /* Iterate through all pages currently stored in the cache. This interface
8289 ** is only available if SQLITE_CHECK_PAGES is defined when the library is 
8290 ** built.
8291 */
8292 SQLITE_PRIVATE void sqlite3PcacheIterate(PCache *pCache, void (*xIter)(PgHdr *));
8293
8294 /* Set and get the suggested cache-size for the specified pager-cache.
8295 **
8296 ** If no global maximum is configured, then the system attempts to limit
8297 ** the total number of pages cached by purgeable pager-caches to the sum
8298 ** of the suggested cache-sizes.
8299 */
8300 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
8301 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
8302
8303 /* Try to return memory used by the pcache module to the main memory heap */
8304 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
8305
8306 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
8307
8308 #endif /* _PCACHE_H_ */
8309
8310 /************** End of pcache.h **********************************************/
8311 /************** Continuing where we left off in sqliteInt.h ******************/
8312
8313 /************** Include os.h in the middle of sqliteInt.h ********************/
8314 /************** Begin file os.h **********************************************/
8315 /*
8316 ** 2001 September 16
8317 **
8318 ** The author disclaims copyright to this source code.  In place of
8319 ** a legal notice, here is a blessing:
8320 **
8321 **    May you do good and not evil.
8322 **    May you find forgiveness for yourself and forgive others.
8323 **    May you share freely, never taking more than you give.
8324 **
8325 ******************************************************************************
8326 **
8327 ** This header file (together with is companion C source-code file
8328 ** "os.c") attempt to abstract the underlying operating system so that
8329 ** the SQLite library will work on both POSIX and windows systems.
8330 **
8331 ** This header file is #include-ed by sqliteInt.h and thus ends up
8332 ** being included by every source file.
8333 **
8334 ** $Id: os.h,v 1.105 2008/06/26 10:41:19 danielk1977 Exp $
8335 */
8336 #ifndef _SQLITE_OS_H_
8337 #define _SQLITE_OS_H_
8338
8339 /*
8340 ** Figure out if we are dealing with Unix, Windows, or some other
8341 ** operating system.  After the following block of preprocess macros,
8342 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER 
8343 ** will defined to either 1 or 0.  One of the four will be 1.  The other 
8344 ** three will be 0.
8345 */
8346 #if defined(SQLITE_OS_OTHER)
8347 # if SQLITE_OS_OTHER==1
8348 #   undef SQLITE_OS_UNIX
8349 #   define SQLITE_OS_UNIX 0
8350 #   undef SQLITE_OS_WIN
8351 #   define SQLITE_OS_WIN 0
8352 #   undef SQLITE_OS_OS2
8353 #   define SQLITE_OS_OS2 0
8354 # else
8355 #   undef SQLITE_OS_OTHER
8356 # endif
8357 #endif
8358 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
8359 # define SQLITE_OS_OTHER 0
8360 # ifndef SQLITE_OS_WIN
8361 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
8362 #     define SQLITE_OS_WIN 1
8363 #     define SQLITE_OS_UNIX 0
8364 #     define SQLITE_OS_OS2 0
8365 #   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
8366 #     define SQLITE_OS_WIN 0
8367 #     define SQLITE_OS_UNIX 0
8368 #     define SQLITE_OS_OS2 1
8369 #   else
8370 #     define SQLITE_OS_WIN 0
8371 #     define SQLITE_OS_UNIX 1
8372 #     define SQLITE_OS_OS2 0
8373 #  endif
8374 # else
8375 #  define SQLITE_OS_UNIX 0
8376 #  define SQLITE_OS_OS2 0
8377 # endif
8378 #else
8379 # ifndef SQLITE_OS_WIN
8380 #  define SQLITE_OS_WIN 0
8381 # endif
8382 #endif
8383
8384 /*
8385 ** Determine if we are dealing with WindowsCE - which has a much
8386 ** reduced API.
8387 */
8388 #if defined(_WIN32_WCE)
8389 # define SQLITE_OS_WINCE 1
8390 #else
8391 # define SQLITE_OS_WINCE 0
8392 #endif
8393
8394
8395 /*
8396 ** Define the maximum size of a temporary filename
8397 */
8398 #if SQLITE_OS_WIN
8399 # include <windows.h>
8400 # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
8401 #elif SQLITE_OS_OS2
8402 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
8403 #  include <os2safe.h> /* has to be included before os2.h for linking to work */
8404 # endif
8405 # define INCL_DOSDATETIME
8406 # define INCL_DOSFILEMGR
8407 # define INCL_DOSERRORS
8408 # define INCL_DOSMISC
8409 # define INCL_DOSPROCESS
8410 # define INCL_DOSMODULEMGR
8411 # define INCL_DOSSEMAPHORES
8412 # include <os2.h>
8413 # include <uconv.h>
8414 # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
8415 #else
8416 # define SQLITE_TEMPNAME_SIZE 200
8417 #endif
8418
8419 /* If the SET_FULLSYNC macro is not defined above, then make it
8420 ** a no-op
8421 */
8422 #ifndef SET_FULLSYNC
8423 # define SET_FULLSYNC(x,y)
8424 #endif
8425
8426 /*
8427 ** The default size of a disk sector
8428 */
8429 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
8430 # define SQLITE_DEFAULT_SECTOR_SIZE 512
8431 #endif
8432
8433 /*
8434 ** Temporary files are named starting with this prefix followed by 16 random
8435 ** alphanumeric characters, and no file extension. They are stored in the
8436 ** OS's standard temporary file directory, and are deleted prior to exit.
8437 ** If sqlite is being embedded in another program, you may wish to change the
8438 ** prefix to reflect your program's name, so that if your program exits
8439 ** prematurely, old temporary files can be easily identified. This can be done
8440 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
8441 **
8442 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
8443 ** Mcafee started using SQLite in their anti-virus product and it
8444 ** started putting files with the "sqlite" name in the c:/temp folder.
8445 ** This annoyed many windows users.  Those users would then do a 
8446 ** Google search for "sqlite", find the telephone numbers of the
8447 ** developers and call to wake them up at night and complain.
8448 ** For this reason, the default name prefix is changed to be "sqlite" 
8449 ** spelled backwards.  So the temp files are still identified, but
8450 ** anybody smart enough to figure out the code is also likely smart
8451 ** enough to know that calling the developer will not help get rid
8452 ** of the file.
8453 */
8454 #ifndef SQLITE_TEMP_FILE_PREFIX
8455 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
8456 #endif
8457
8458 /*
8459 ** The following values may be passed as the second argument to
8460 ** sqlite3OsLock(). The various locks exhibit the following semantics:
8461 **
8462 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
8463 ** RESERVED:  A single process may hold a RESERVED lock on a file at
8464 **            any time. Other processes may hold and obtain new SHARED locks.
8465 ** PENDING:   A single process may hold a PENDING lock on a file at
8466 **            any one time. Existing SHARED locks may persist, but no new
8467 **            SHARED locks may be obtained by other processes.
8468 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
8469 **
8470 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
8471 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
8472 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
8473 ** sqlite3OsLock().
8474 */
8475 #define NO_LOCK         0
8476 #define SHARED_LOCK     1
8477 #define RESERVED_LOCK   2
8478 #define PENDING_LOCK    3
8479 #define EXCLUSIVE_LOCK  4
8480
8481 /*
8482 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
8483 **
8484 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
8485 ** those functions are not available.  So we use only LockFile() and
8486 ** UnlockFile().
8487 **
8488 ** LockFile() prevents not just writing but also reading by other processes.
8489 ** A SHARED_LOCK is obtained by locking a single randomly-chosen 
8490 ** byte out of a specific range of bytes. The lock byte is obtained at 
8491 ** random so two separate readers can probably access the file at the 
8492 ** same time, unless they are unlucky and choose the same lock byte.
8493 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
8494 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
8495 ** a single byte of the file that is designated as the reserved lock byte.
8496 ** A PENDING_LOCK is obtained by locking a designated byte different from
8497 ** the RESERVED_LOCK byte.
8498 **
8499 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
8500 ** which means we can use reader/writer locks.  When reader/writer locks
8501 ** are used, the lock is placed on the same range of bytes that is used
8502 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
8503 ** will support two or more Win95 readers or two or more WinNT readers.
8504 ** But a single Win95 reader will lock out all WinNT readers and a single
8505 ** WinNT reader will lock out all other Win95 readers.
8506 **
8507 ** The following #defines specify the range of bytes used for locking.
8508 ** SHARED_SIZE is the number of bytes available in the pool from which
8509 ** a random byte is selected for a shared lock.  The pool of bytes for
8510 ** shared locks begins at SHARED_FIRST. 
8511 **
8512 ** These #defines are available in sqlite_aux.h so that adaptors for
8513 ** connecting SQLite to other operating systems can use the same byte
8514 ** ranges for locking.  In particular, the same locking strategy and
8515 ** byte ranges are used for Unix.  This leaves open the possiblity of having
8516 ** clients on win95, winNT, and unix all talking to the same shared file
8517 ** and all locking correctly.  To do so would require that samba (or whatever
8518 ** tool is being used for file sharing) implements locks correctly between
8519 ** windows and unix.  I'm guessing that isn't likely to happen, but by
8520 ** using the same locking range we are at least open to the possibility.
8521 **
8522 ** Locking in windows is manditory.  For this reason, we cannot store
8523 ** actual data in the bytes used for locking.  The pager never allocates
8524 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
8525 ** that all locks will fit on a single page even at the minimum page size.
8526 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
8527 ** is set high so that we don't have to allocate an unused page except
8528 ** for very large databases.  But one should test the page skipping logic 
8529 ** by setting PENDING_BYTE low and running the entire regression suite.
8530 **
8531 ** Changing the value of PENDING_BYTE results in a subtly incompatible
8532 ** file format.  Depending on how it is changed, you might not notice
8533 ** the incompatibility right away, even running a full regression test.
8534 ** The default location of PENDING_BYTE is the first byte past the
8535 ** 1GB boundary.
8536 **
8537 */
8538 #ifndef SQLITE_TEST
8539 #define PENDING_BYTE      0x40000000  /* First byte past the 1GB boundary */
8540 #else
8541 SQLITE_API extern unsigned int sqlite3_pending_byte;
8542 #define PENDING_BYTE sqlite3_pending_byte
8543 #endif
8544
8545 #define RESERVED_BYTE     (PENDING_BYTE+1)
8546 #define SHARED_FIRST      (PENDING_BYTE+2)
8547 #define SHARED_SIZE       510
8548
8549 /* 
8550 ** Functions for accessing sqlite3_file methods 
8551 */
8552 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
8553 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
8554 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
8555 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
8556 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
8557 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
8558 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
8559 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
8560 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
8561 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
8562 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
8563 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
8564
8565 /* 
8566 ** Functions for accessing sqlite3_vfs methods 
8567 */
8568 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
8569 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
8570 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
8571 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
8572 #ifndef SQLITE_OMIT_LOAD_EXTENSION
8573 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
8574 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
8575 SQLITE_PRIVATE void *sqlite3OsDlSym(sqlite3_vfs *, void *, const char *);
8576 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
8577 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
8578 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
8579 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
8580 SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *, double*);
8581
8582 /*
8583 ** Convenience functions for opening and closing files using 
8584 ** sqlite3_malloc() to obtain space for the file-handle structure.
8585 */
8586 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
8587 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
8588
8589 #endif /* _SQLITE_OS_H_ */
8590
8591 /************** End of os.h **************************************************/
8592 /************** Continuing where we left off in sqliteInt.h ******************/
8593 /************** Include mutex.h in the middle of sqliteInt.h *****************/
8594 /************** Begin file mutex.h *******************************************/
8595 /*
8596 ** 2007 August 28
8597 **
8598 ** The author disclaims copyright to this source code.  In place of
8599 ** a legal notice, here is a blessing:
8600 **
8601 **    May you do good and not evil.
8602 **    May you find forgiveness for yourself and forgive others.
8603 **    May you share freely, never taking more than you give.
8604 **
8605 *************************************************************************
8606 **
8607 ** This file contains the common header for all mutex implementations.
8608 ** The sqliteInt.h header #includes this file so that it is available
8609 ** to all source files.  We break it out in an effort to keep the code
8610 ** better organized.
8611 **
8612 ** NOTE:  source files should *not* #include this header file directly.
8613 ** Source files should #include the sqliteInt.h file and let that file
8614 ** include this one indirectly.
8615 **
8616 ** $Id: mutex.h,v 1.8 2008/06/26 10:41:19 danielk1977 Exp $
8617 */
8618
8619
8620 #ifdef SQLITE_MUTEX_APPDEF
8621 /*
8622 ** If SQLITE_MUTEX_APPDEF is defined, then this whole module is
8623 ** omitted and equivalent functionality must be provided by the
8624 ** application that links against the SQLite library.
8625 */
8626 #else
8627 /*
8628 ** Figure out what version of the code to use.  The choices are
8629 **
8630 **   SQLITE_MUTEX_NOOP         For single-threaded applications that
8631 **                             do not desire error checking.
8632 **
8633 **   SQLITE_MUTEX_NOOP_DEBUG   For single-threaded applications with
8634 **                             error checking to help verify that mutexes
8635 **                             are being used correctly even though they
8636 **                             are not needed.  Used when SQLITE_DEBUG is
8637 **                             defined on single-threaded builds.
8638 **
8639 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
8640 **
8641 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
8642 **
8643 **   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
8644 */
8645 #define SQLITE_MUTEX_NOOP 1   /* The default */
8646 #if defined(SQLITE_DEBUG) && !SQLITE_THREADSAFE
8647 # undef SQLITE_MUTEX_NOOP
8648 # define SQLITE_MUTEX_NOOP_DEBUG
8649 #endif
8650 #if defined(SQLITE_MUTEX_NOOP) && SQLITE_THREADSAFE && SQLITE_OS_UNIX
8651 # undef SQLITE_MUTEX_NOOP
8652 # define SQLITE_MUTEX_PTHREADS
8653 #endif
8654 #if defined(SQLITE_MUTEX_NOOP) && SQLITE_THREADSAFE && SQLITE_OS_WIN
8655 # undef SQLITE_MUTEX_NOOP
8656 # define SQLITE_MUTEX_W32
8657 #endif
8658 #if defined(SQLITE_MUTEX_NOOP) && SQLITE_THREADSAFE && SQLITE_OS_OS2
8659 # undef SQLITE_MUTEX_NOOP
8660 # define SQLITE_MUTEX_OS2
8661 #endif
8662
8663 #ifdef SQLITE_MUTEX_NOOP
8664 /*
8665 ** If this is a no-op implementation, implement everything as macros.
8666 */
8667 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
8668 #define sqlite3_mutex_free(X)
8669 #define sqlite3_mutex_enter(X)
8670 #define sqlite3_mutex_try(X)      SQLITE_OK
8671 #define sqlite3_mutex_leave(X)
8672 #define sqlite3_mutex_held(X)     1
8673 #define sqlite3_mutex_notheld(X)  1
8674 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
8675 #define sqlite3MutexInit()        SQLITE_OK
8676 #define sqlite3MutexEnd()
8677 #endif
8678
8679 #endif /* SQLITE_MUTEX_APPDEF */
8680
8681 /************** End of mutex.h ***********************************************/
8682 /************** Continuing where we left off in sqliteInt.h ******************/
8683
8684
8685 /*
8686 ** Each database file to be accessed by the system is an instance
8687 ** of the following structure.  There are normally two of these structures
8688 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
8689 ** aDb[1] is the database file used to hold temporary tables.  Additional
8690 ** databases may be attached.
8691 */
8692 struct Db {
8693   char *zName;         /* Name of this database */
8694   Btree *pBt;          /* The B*Tree structure for this database file */
8695   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
8696   u8 safety_level;     /* How aggressive at synching data to disk */
8697   void *pAux;               /* Auxiliary data.  Usually NULL */
8698   void (*xFreeAux)(void*);  /* Routine to free pAux */
8699   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
8700 };
8701
8702 /*
8703 ** An instance of the following structure stores a database schema.
8704 **
8705 ** If there are no virtual tables configured in this schema, the
8706 ** Schema.db variable is set to NULL. After the first virtual table
8707 ** has been added, it is set to point to the database connection 
8708 ** used to create the connection. Once a virtual table has been
8709 ** added to the Schema structure and the Schema.db variable populated, 
8710 ** only that database connection may use the Schema to prepare 
8711 ** statements.
8712 */
8713 struct Schema {
8714   int schema_cookie;   /* Database schema version number for this file */
8715   Hash tblHash;        /* All tables indexed by name */
8716   Hash idxHash;        /* All (named) indices indexed by name */
8717   Hash trigHash;       /* All triggers indexed by name */
8718   Hash aFKey;          /* Foreign keys indexed by to-table */
8719   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
8720   u8 file_format;      /* Schema format version for this file */
8721   u8 enc;              /* Text encoding used by this database */
8722   u16 flags;           /* Flags associated with this schema */
8723   int cache_size;      /* Number of pages to use in the cache */
8724 #ifndef SQLITE_OMIT_VIRTUALTABLE
8725   sqlite3 *db;         /* "Owner" connection. See comment above */
8726 #endif
8727 };
8728
8729 /*
8730 ** These macros can be used to test, set, or clear bits in the 
8731 ** Db.flags field.
8732 */
8733 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
8734 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
8735 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
8736 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
8737
8738 /*
8739 ** Allowed values for the DB.flags field.
8740 **
8741 ** The DB_SchemaLoaded flag is set after the database schema has been
8742 ** read into internal hash tables.
8743 **
8744 ** DB_UnresetViews means that one or more views have column names that
8745 ** have been filled out.  If the schema changes, these column names might
8746 ** changes and so the view will need to be reset.
8747 */
8748 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
8749 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
8750 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
8751
8752 /*
8753 ** The number of different kinds of things that can be limited
8754 ** using the sqlite3_limit() interface.
8755 */
8756 #define SQLITE_N_LIMIT (SQLITE_LIMIT_VARIABLE_NUMBER+1)
8757
8758 /*
8759 ** Lookaside malloc is a set of fixed-size buffers that can be used
8760 ** to satisify small transient memory allocation requests for objects
8761 ** associated with a particular database connection.  The use of
8762 ** lookaside malloc provides a significant performance enhancement
8763 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
8764 ** SQL statements.
8765 **
8766 ** The Lookaside structure holds configuration information about the
8767 ** lookaside malloc subsystem.  Each available memory allocation in
8768 ** the lookaside subsystem is stored on a linked list of LookasideSlot
8769 ** objects.
8770 */
8771 struct Lookaside {
8772   u16 sz;                 /* Size of each buffer in bytes */
8773   u8 bEnabled;            /* True if use lookaside.  False to ignore it */
8774   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
8775   int nOut;               /* Number of buffers currently checked out */
8776   int mxOut;              /* Highwater mark for nOut */
8777   LookasideSlot *pFree;   /* List of available buffers */
8778   void *pStart;           /* First byte of available memory space */
8779   void *pEnd;             /* First byte past end of available space */
8780 };
8781 struct LookasideSlot {
8782   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
8783 };
8784
8785 /*
8786 ** A hash table for function definitions.
8787 **
8788 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
8789 ** Collisions are on the FuncDef.pHash chain.
8790 */
8791 struct FuncDefHash {
8792   FuncDef *a[23];       /* Hash table for functions */
8793 };
8794
8795 /*
8796 ** Each database is an instance of the following structure.
8797 **
8798 ** The sqlite.lastRowid records the last insert rowid generated by an
8799 ** insert statement.  Inserts on views do not affect its value.  Each
8800 ** trigger has its own context, so that lastRowid can be updated inside
8801 ** triggers as usual.  The previous value will be restored once the trigger
8802 ** exits.  Upon entering a before or instead of trigger, lastRowid is no
8803 ** longer (since after version 2.8.12) reset to -1.
8804 **
8805 ** The sqlite.nChange does not count changes within triggers and keeps no
8806 ** context.  It is reset at start of sqlite3_exec.
8807 ** The sqlite.lsChange represents the number of changes made by the last
8808 ** insert, update, or delete statement.  It remains constant throughout the
8809 ** length of a statement and is then updated by OP_SetCounts.  It keeps a
8810 ** context stack just like lastRowid so that the count of changes
8811 ** within a trigger is not seen outside the trigger.  Changes to views do not
8812 ** affect the value of lsChange.
8813 ** The sqlite.csChange keeps track of the number of current changes (since
8814 ** the last statement) and is used to update sqlite_lsChange.
8815 **
8816 ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
8817 ** store the most recent error code and, if applicable, string. The
8818 ** internal function sqlite3Error() is used to set these variables
8819 ** consistently.
8820 */
8821 struct sqlite3 {
8822   sqlite3_vfs *pVfs;            /* OS Interface */
8823   int nDb;                      /* Number of backends currently in use */
8824   Db *aDb;                      /* All backends */
8825   int flags;                    /* Miscellanous flags. See below */
8826   int openFlags;                /* Flags passed to sqlite3_vfs.xOpen() */
8827   int errCode;                  /* Most recent error code (SQLITE_*) */
8828   int errMask;                  /* & result codes with this before returning */
8829   u8 autoCommit;                /* The auto-commit flag. */
8830   u8 temp_store;                /* 1: file 2: memory 0: default */
8831   u8 mallocFailed;              /* True if we have seen a malloc failure */
8832   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
8833   u8 dfltJournalMode;           /* Default journal mode for attached dbs */
8834   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
8835   int nextPagesize;             /* Pagesize after VACUUM if >0 */
8836   int nTable;                   /* Number of tables in the database */
8837   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
8838   i64 lastRowid;                /* ROWID of most recent insert (see above) */
8839   i64 priorNewRowid;            /* Last randomly generated ROWID */
8840   int magic;                    /* Magic number for detect library misuse */
8841   int nChange;                  /* Value returned by sqlite3_changes() */
8842   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
8843   sqlite3_mutex *mutex;         /* Connection mutex */
8844   int aLimit[SQLITE_N_LIMIT];   /* Limits */
8845   struct sqlite3InitInfo {      /* Information used during initialization */
8846     int iDb;                    /* When back is being initialized */
8847     int newTnum;                /* Rootpage of table being initialized */
8848     u8 busy;                    /* TRUE if currently initializing */
8849   } init;
8850   int nExtension;               /* Number of loaded extensions */
8851   void **aExtension;            /* Array of shared libraray handles */
8852   struct Vdbe *pVdbe;           /* List of active virtual machines */
8853   int activeVdbeCnt;            /* Number of vdbes currently executing */
8854   void (*xTrace)(void*,const char*);        /* Trace function */
8855   void *pTraceArg;                          /* Argument to the trace function */
8856   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
8857   void *pProfileArg;                        /* Argument to profile function */
8858   void *pCommitArg;                 /* Argument to xCommitCallback() */   
8859   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
8860   void *pRollbackArg;               /* Argument to xRollbackCallback() */   
8861   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
8862   void *pUpdateArg;
8863   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
8864   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
8865   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
8866   void *pCollNeededArg;
8867   sqlite3_value *pErr;          /* Most recent error message */
8868   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
8869   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
8870   union {
8871     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
8872     double notUsed1;            /* Spacer */
8873   } u1;
8874   Lookaside lookaside;          /* Lookaside malloc configuration */
8875 #ifndef SQLITE_OMIT_AUTHORIZATION
8876   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
8877                                 /* Access authorization function */
8878   void *pAuthArg;               /* 1st argument to the access auth function */
8879 #endif
8880 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
8881   int (*xProgress)(void *);     /* The progress callback */
8882   void *pProgressArg;           /* Argument to the progress callback */
8883   int nProgressOps;             /* Number of opcodes for progress callback */
8884 #endif
8885 #ifndef SQLITE_OMIT_VIRTUALTABLE
8886   Hash aModule;                 /* populated by sqlite3_create_module() */
8887   Table *pVTab;                 /* vtab with active Connect/Create method */
8888   sqlite3_vtab **aVTrans;       /* Virtual tables with open transactions */
8889   int nVTrans;                  /* Allocated size of aVTrans */
8890 #endif
8891   FuncDefHash aFunc;            /* Hash table of connection functions */
8892   Hash aCollSeq;                /* All collating sequences */
8893   BusyHandler busyHandler;      /* Busy callback */
8894   int busyTimeout;              /* Busy handler timeout, in msec */
8895   Db aDbStatic[2];              /* Static space for the 2 default backends */
8896 #ifdef SQLITE_SSE
8897   sqlite3_stmt *pFetch;         /* Used by SSE to fetch stored statements */
8898 #endif
8899 };
8900
8901 /*
8902 ** A macro to discover the encoding of a database.
8903 */
8904 #define ENC(db) ((db)->aDb[0].pSchema->enc)
8905
8906 /*
8907 ** Possible values for the sqlite.flags and or Db.flags fields.
8908 **
8909 ** On sqlite.flags, the SQLITE_InTrans value means that we have
8910 ** executed a BEGIN.  On Db.flags, SQLITE_InTrans means a statement
8911 ** transaction is active on that particular database file.
8912 */
8913 #define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
8914 #define SQLITE_InTrans        0x00000008  /* True if in a transaction */
8915 #define SQLITE_InternChanges  0x00000010  /* Uncommitted Hash table changes */
8916 #define SQLITE_FullColNames   0x00000020  /* Show full column names on SELECT */
8917 #define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
8918 #define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
8919                                           /*   DELETE, or UPDATE and return */
8920                                           /*   the count using a callback. */
8921 #define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
8922                                           /*   result set is empty */
8923 #define SQLITE_SqlTrace       0x00000200  /* Debug print SQL as it executes */
8924 #define SQLITE_VdbeListing    0x00000400  /* Debug listings of VDBE programs */
8925 #define SQLITE_WriteSchema    0x00000800  /* OK to update SQLITE_MASTER */
8926 #define SQLITE_NoReadlock     0x00001000  /* Readlocks are omitted when 
8927                                           ** accessing read-only databases */
8928 #define SQLITE_IgnoreChecks   0x00002000  /* Do not enforce check constraints */
8929 #define SQLITE_ReadUncommitted 0x00004000 /* For shared-cache mode */
8930 #define SQLITE_LegacyFileFmt  0x00008000  /* Create new databases in format 1 */
8931 #define SQLITE_FullFSync      0x00010000  /* Use full fsync on the backend */
8932 #define SQLITE_LoadExtension  0x00020000  /* Enable load_extension */
8933
8934 #define SQLITE_RecoveryMode   0x00040000  /* Ignore schema errors */
8935 #define SQLITE_SharedCache    0x00080000  /* Cache sharing is enabled */
8936 #define SQLITE_Vtab           0x00100000  /* There exists a virtual table */
8937
8938 /*
8939 ** Possible values for the sqlite.magic field.
8940 ** The numbers are obtained at random and have no special meaning, other
8941 ** than being distinct from one another.
8942 */
8943 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
8944 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
8945 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
8946 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
8947 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
8948
8949 /*
8950 ** Each SQL function is defined by an instance of the following
8951 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
8952 ** hash table.  When multiple functions have the same name, the hash table
8953 ** points to a linked list of these structures.
8954 */
8955 struct FuncDef {
8956   i8 nArg;             /* Number of arguments.  -1 means unlimited */
8957   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
8958   u8 needCollSeq;      /* True if sqlite3GetFuncCollSeq() might be called */
8959   u8 flags;            /* Some combination of SQLITE_FUNC_* */
8960   void *pUserData;     /* User data parameter */
8961   FuncDef *pNext;      /* Next function with same name */
8962   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
8963   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
8964   void (*xFinalize)(sqlite3_context*);                /* Aggregate finializer */
8965   char *zName;         /* SQL name of the function. */
8966   FuncDef *pHash;      /* Next with a different name but the same hash */
8967 };
8968
8969 /*
8970 ** Possible values for FuncDef.flags
8971 */
8972 #define SQLITE_FUNC_LIKE     0x01  /* Candidate for the LIKE optimization */
8973 #define SQLITE_FUNC_CASE     0x02  /* Case-sensitive LIKE-type function */
8974 #define SQLITE_FUNC_EPHEM    0x04  /* Ephermeral.  Delete with VDBE */
8975
8976 /*
8977 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
8978 ** used to create the initializers for the FuncDef structures.
8979 **
8980 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
8981 **     Used to create a scalar function definition of a function zName 
8982 **     implemented by C function xFunc that accepts nArg arguments. The
8983 **     value passed as iArg is cast to a (void*) and made available
8984 **     as the user-data (sqlite3_user_data()) for the function. If 
8985 **     argument bNC is true, then the FuncDef.needCollate flag is set.
8986 **
8987 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
8988 **     Used to create an aggregate function definition implemented by
8989 **     the C functions xStep and xFinal. The first four parameters
8990 **     are interpreted in the same way as the first 4 parameters to
8991 **     FUNCTION().
8992 **
8993 **   LIKEFUNC(zName, nArg, pArg, flags)
8994 **     Used to create a scalar function definition of a function zName 
8995 **     that accepts nArg arguments and is implemented by a call to C 
8996 **     function likeFunc. Argument pArg is cast to a (void *) and made
8997 **     available as the function user-data (sqlite3_user_data()). The
8998 **     FuncDef.flags variable is set to the value passed as the flags
8999 **     parameter.
9000 */
9001 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
9002   {nArg, SQLITE_UTF8, bNC, 0, SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName}
9003 #define LIKEFUNC(zName, nArg, arg, flags) \
9004   {nArg, SQLITE_UTF8, 0, flags, (void *)arg, 0, likeFunc, 0, 0, #zName}
9005 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
9006   {nArg, SQLITE_UTF8, nc, 0, SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal, #zName}
9007
9008
9009 /*
9010 ** Each SQLite module (virtual table definition) is defined by an
9011 ** instance of the following structure, stored in the sqlite3.aModule
9012 ** hash table.
9013 */
9014 struct Module {
9015   const sqlite3_module *pModule;       /* Callback pointers */
9016   const char *zName;                   /* Name passed to create_module() */
9017   void *pAux;                          /* pAux passed to create_module() */
9018   void (*xDestroy)(void *);            /* Module destructor function */
9019 };
9020
9021 /*
9022 ** information about each column of an SQL table is held in an instance
9023 ** of this structure.
9024 */
9025 struct Column {
9026   char *zName;     /* Name of this column */
9027   Expr *pDflt;     /* Default value of this column */
9028   char *zType;     /* Data type for this column */
9029   char *zColl;     /* Collating sequence.  If NULL, use the default */
9030   u8 notNull;      /* True if there is a NOT NULL constraint */
9031   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
9032   char affinity;   /* One of the SQLITE_AFF_... values */
9033 #ifndef SQLITE_OMIT_VIRTUALTABLE
9034   u8 isHidden;     /* True if this column is 'hidden' */
9035 #endif
9036 };
9037
9038 /*
9039 ** A "Collating Sequence" is defined by an instance of the following
9040 ** structure. Conceptually, a collating sequence consists of a name and
9041 ** a comparison routine that defines the order of that sequence.
9042 **
9043 ** There may two seperate implementations of the collation function, one
9044 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
9045 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
9046 ** native byte order. When a collation sequence is invoked, SQLite selects
9047 ** the version that will require the least expensive encoding
9048 ** translations, if any.
9049 **
9050 ** The CollSeq.pUser member variable is an extra parameter that passed in
9051 ** as the first argument to the UTF-8 comparison function, xCmp.
9052 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
9053 ** xCmp16.
9054 **
9055 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
9056 ** collating sequence is undefined.  Indices built on an undefined
9057 ** collating sequence may not be read or written.
9058 */
9059 struct CollSeq {
9060   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
9061   u8 enc;               /* Text encoding handled by xCmp() */
9062   u8 type;              /* One of the SQLITE_COLL_... values below */
9063   void *pUser;          /* First argument to xCmp() */
9064   int (*xCmp)(void*,int, const void*, int, const void*);
9065   void (*xDel)(void*);  /* Destructor for pUser */
9066 };
9067
9068 /*
9069 ** Allowed values of CollSeq.type:
9070 */
9071 #define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
9072 #define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
9073 #define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
9074 #define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
9075
9076 /*
9077 ** A sort order can be either ASC or DESC.
9078 */
9079 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
9080 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
9081
9082 /*
9083 ** Column affinity types.
9084 **
9085 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
9086 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
9087 ** the speed a little by numbering the values consecutively.  
9088 **
9089 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
9090 ** when multiple affinity types are concatenated into a string and
9091 ** used as the P4 operand, they will be more readable.
9092 **
9093 ** Note also that the numeric types are grouped together so that testing
9094 ** for a numeric type is a single comparison.
9095 */
9096 #define SQLITE_AFF_TEXT     'a'
9097 #define SQLITE_AFF_NONE     'b'
9098 #define SQLITE_AFF_NUMERIC  'c'
9099 #define SQLITE_AFF_INTEGER  'd'
9100 #define SQLITE_AFF_REAL     'e'
9101
9102 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
9103
9104 /*
9105 ** The SQLITE_AFF_MASK values masks off the significant bits of an
9106 ** affinity value. 
9107 */
9108 #define SQLITE_AFF_MASK     0x67
9109
9110 /*
9111 ** Additional bit values that can be ORed with an affinity without
9112 ** changing the affinity.
9113 */
9114 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
9115 #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
9116
9117 /*
9118 ** Each SQL table is represented in memory by an instance of the
9119 ** following structure.
9120 **
9121 ** Table.zName is the name of the table.  The case of the original
9122 ** CREATE TABLE statement is stored, but case is not significant for
9123 ** comparisons.
9124 **
9125 ** Table.nCol is the number of columns in this table.  Table.aCol is a
9126 ** pointer to an array of Column structures, one for each column.
9127 **
9128 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
9129 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
9130 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
9131 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
9132 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
9133 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
9134 ** the table has any PRIMARY KEY, INTEGER or otherwise.
9135 **
9136 ** Table.tnum is the page number for the root BTree page of the table in the
9137 ** database file.  If Table.iDb is the index of the database table backend
9138 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
9139 ** holds temporary tables and indices.  If TF_Ephemeral is set
9140 ** then the table is stored in a file that is automatically deleted
9141 ** when the VDBE cursor to the table is closed.  In this case Table.tnum 
9142 ** refers VDBE cursor number that holds the table open, not to the root
9143 ** page number.  Transient tables are used to hold the results of a
9144 ** sub-query that appears instead of a real table name in the FROM clause 
9145 ** of a SELECT statement.
9146 */
9147 struct Table {
9148   sqlite3 *db;         /* Associated database connection.  Might be NULL. */
9149   char *zName;         /* Name of the table or view */
9150   int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
9151   int nCol;            /* Number of columns in this table */
9152   Column *aCol;        /* Information about each column */
9153   Index *pIndex;       /* List of SQL indexes on this table. */
9154   int tnum;            /* Root BTree node for this table (see note above) */
9155   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
9156   u16 nRef;            /* Number of pointers to this Table */
9157   u8 tabFlags;         /* Mask of TF_* values */
9158   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
9159   Trigger *pTrigger;   /* List of SQL triggers on this table */
9160   FKey *pFKey;         /* Linked list of all foreign keys in this table */
9161   char *zColAff;       /* String defining the affinity of each column */
9162 #ifndef SQLITE_OMIT_CHECK
9163   Expr *pCheck;        /* The AND of all CHECK constraints */
9164 #endif
9165 #ifndef SQLITE_OMIT_ALTERTABLE
9166   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
9167 #endif
9168 #ifndef SQLITE_OMIT_VIRTUALTABLE
9169   Module *pMod;        /* Pointer to the implementation of the module */
9170   sqlite3_vtab *pVtab; /* Pointer to the module instance */
9171   int nModuleArg;      /* Number of arguments to the module */
9172   char **azModuleArg;  /* Text of all module args. [0] is module name */
9173 #endif
9174   Schema *pSchema;     /* Schema that contains this table */
9175   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
9176 };
9177
9178 /*
9179 ** Allowed values for Tabe.tabFlags.
9180 */
9181 #define TF_Readonly        0x01    /* Read-only system table */
9182 #define TF_Ephemeral       0x02    /* An emphermal table */
9183 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
9184 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
9185 #define TF_Virtual         0x10    /* Is a virtual table */
9186 #define TF_NeedMetadata    0x20    /* aCol[].zType and aCol[].pColl missing */
9187
9188
9189
9190 /*
9191 ** Test to see whether or not a table is a virtual table.  This is
9192 ** done as a macro so that it will be optimized out when virtual
9193 ** table support is omitted from the build.
9194 */
9195 #ifndef SQLITE_OMIT_VIRTUALTABLE
9196 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
9197 #  define IsHiddenColumn(X) ((X)->isHidden)
9198 #else
9199 #  define IsVirtual(X)      0
9200 #  define IsHiddenColumn(X) 0
9201 #endif
9202
9203 /*
9204 ** Each foreign key constraint is an instance of the following structure.
9205 **
9206 ** A foreign key is associated with two tables.  The "from" table is
9207 ** the table that contains the REFERENCES clause that creates the foreign
9208 ** key.  The "to" table is the table that is named in the REFERENCES clause.
9209 ** Consider this example:
9210 **
9211 **     CREATE TABLE ex1(
9212 **       a INTEGER PRIMARY KEY,
9213 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
9214 **     );
9215 **
9216 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
9217 **
9218 ** Each REFERENCES clause generates an instance of the following structure
9219 ** which is attached to the from-table.  The to-table need not exist when
9220 ** the from-table is created.  The existance of the to-table is not checked
9221 ** until an attempt is made to insert data into the from-table.
9222 **
9223 ** The sqlite.aFKey hash table stores pointers to this structure
9224 ** given the name of a to-table.  For each to-table, all foreign keys
9225 ** associated with that table are on a linked list using the FKey.pNextTo
9226 ** field.
9227 */
9228 struct FKey {
9229   Table *pFrom;     /* The table that constains the REFERENCES clause */
9230   FKey *pNextFrom;  /* Next foreign key in pFrom */
9231   char *zTo;        /* Name of table that the key points to */
9232   FKey *pNextTo;    /* Next foreign key that points to zTo */
9233   int nCol;         /* Number of columns in this key */
9234   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
9235     int iFrom;         /* Index of column in pFrom */
9236     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
9237   } *aCol;          /* One entry for each of nCol column s */
9238   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
9239   u8 updateConf;    /* How to resolve conflicts that occur on UPDATE */
9240   u8 deleteConf;    /* How to resolve conflicts that occur on DELETE */
9241   u8 insertConf;    /* How to resolve conflicts that occur on INSERT */
9242 };
9243
9244 /*
9245 ** SQLite supports many different ways to resolve a constraint
9246 ** error.  ROLLBACK processing means that a constraint violation
9247 ** causes the operation in process to fail and for the current transaction
9248 ** to be rolled back.  ABORT processing means the operation in process
9249 ** fails and any prior changes from that one operation are backed out,
9250 ** but the transaction is not rolled back.  FAIL processing means that
9251 ** the operation in progress stops and returns an error code.  But prior
9252 ** changes due to the same operation are not backed out and no rollback
9253 ** occurs.  IGNORE means that the particular row that caused the constraint
9254 ** error is not inserted or updated.  Processing continues and no error
9255 ** is returned.  REPLACE means that preexisting database rows that caused
9256 ** a UNIQUE constraint violation are removed so that the new insert or
9257 ** update can proceed.  Processing continues and no error is reported.
9258 **
9259 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
9260 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
9261 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
9262 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
9263 ** referenced table row is propagated into the row that holds the
9264 ** foreign key.
9265 ** 
9266 ** The following symbolic values are used to record which type
9267 ** of action to take.
9268 */
9269 #define OE_None     0   /* There is no constraint to check */
9270 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
9271 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
9272 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
9273 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
9274 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
9275
9276 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
9277 #define OE_SetNull  7   /* Set the foreign key value to NULL */
9278 #define OE_SetDflt  8   /* Set the foreign key value to its default */
9279 #define OE_Cascade  9   /* Cascade the changes */
9280
9281 #define OE_Default  99  /* Do whatever the default action is */
9282
9283
9284 /*
9285 ** An instance of the following structure is passed as the first
9286 ** argument to sqlite3VdbeKeyCompare and is used to control the 
9287 ** comparison of the two index keys.
9288 */
9289 struct KeyInfo {
9290   sqlite3 *db;        /* The database connection */
9291   u8 enc;             /* Text encoding - one of the TEXT_Utf* values */
9292   u16 nField;         /* Number of entries in aColl[] */
9293   u8 *aSortOrder;     /* If defined an aSortOrder[i] is true, sort DESC */
9294   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
9295 };
9296
9297 /*
9298 ** An instance of the following structure holds information about a
9299 ** single index record that has already been parsed out into individual
9300 ** values.
9301 **
9302 ** A record is an object that contains one or more fields of data.
9303 ** Records are used to store the content of a table row and to store
9304 ** the key of an index.  A blob encoding of a record is created by
9305 ** the OP_MakeRecord opcode of the VDBE and is disassemblied by the
9306 ** OP_Column opcode.
9307 **
9308 ** This structure holds a record that has already been disassembled
9309 ** into its constitutent fields.
9310 */
9311 struct UnpackedRecord {
9312   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
9313   u16 nField;         /* Number of entries in apMem[] */
9314   u16 flags;          /* Boolean settings.  UNPACKED_... below */
9315   Mem *aMem;          /* Values */
9316 };
9317
9318 /*
9319 ** Allowed values of UnpackedRecord.flags
9320 */
9321 #define UNPACKED_NEED_FREE     0x0001  /* Memory is from sqlite3Malloc() */
9322 #define UNPACKED_NEED_DESTROY  0x0002  /* apMem[]s should all be destroyed */
9323 #define UNPACKED_IGNORE_ROWID  0x0004  /* Ignore trailing rowid on key1 */
9324 #define UNPACKED_INCRKEY       0x0008  /* Make this key an epsilon larger */
9325 #define UNPACKED_PREFIX_MATCH  0x0010  /* A prefix match is considered OK */
9326
9327 /*
9328 ** Each SQL index is represented in memory by an
9329 ** instance of the following structure.
9330 **
9331 ** The columns of the table that are to be indexed are described
9332 ** by the aiColumn[] field of this structure.  For example, suppose
9333 ** we have the following table and index:
9334 **
9335 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
9336 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
9337 **
9338 ** In the Table structure describing Ex1, nCol==3 because there are
9339 ** three columns in the table.  In the Index structure describing
9340 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
9341 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
9342 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
9343 ** The second column to be indexed (c1) has an index of 0 in
9344 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
9345 **
9346 ** The Index.onError field determines whether or not the indexed columns
9347 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
9348 ** it means this is not a unique index.  Otherwise it is a unique index
9349 ** and the value of Index.onError indicate the which conflict resolution 
9350 ** algorithm to employ whenever an attempt is made to insert a non-unique
9351 ** element.
9352 */
9353 struct Index {
9354   char *zName;     /* Name of this index */
9355   int nColumn;     /* Number of columns in the table used by this index */
9356   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
9357   unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
9358   Table *pTable;   /* The SQL table being indexed */
9359   int tnum;        /* Page containing root of this index in database file */
9360   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
9361   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
9362   char *zColAff;   /* String defining the affinity of each column */
9363   Index *pNext;    /* The next index associated with the same table */
9364   Schema *pSchema; /* Schema containing this index */
9365   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
9366   char **azColl;   /* Array of collation sequence names for index */
9367 };
9368
9369 /*
9370 ** Each token coming out of the lexer is an instance of
9371 ** this structure.  Tokens are also used as part of an expression.
9372 **
9373 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
9374 ** may contain random values.  Do not make any assuptions about Token.dyn
9375 ** and Token.n when Token.z==0.
9376 */
9377 struct Token {
9378   const unsigned char *z; /* Text of the token.  Not NULL-terminated! */
9379   unsigned dyn  : 1;      /* True for malloced memory, false for static */
9380   unsigned n    : 31;     /* Number of characters in this token */
9381 };
9382
9383 /*
9384 ** An instance of this structure contains information needed to generate
9385 ** code for a SELECT that contains aggregate functions.
9386 **
9387 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
9388 ** pointer to this structure.  The Expr.iColumn field is the index in
9389 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
9390 ** code for that node.
9391 **
9392 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
9393 ** original Select structure that describes the SELECT statement.  These
9394 ** fields do not need to be freed when deallocating the AggInfo structure.
9395 */
9396 struct AggInfo {
9397   u8 directMode;          /* Direct rendering mode means take data directly
9398                           ** from source tables rather than from accumulators */
9399   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
9400                           ** than the source table */
9401   int sortingIdx;         /* Cursor number of the sorting index */
9402   ExprList *pGroupBy;     /* The group by clause */
9403   int nSortingColumn;     /* Number of columns in the sorting index */
9404   struct AggInfo_col {    /* For each column used in source tables */
9405     Table *pTab;             /* Source table */
9406     int iTable;              /* Cursor number of the source table */
9407     int iColumn;             /* Column number within the source table */
9408     int iSorterColumn;       /* Column number in the sorting index */
9409     int iMem;                /* Memory location that acts as accumulator */
9410     Expr *pExpr;             /* The original expression */
9411   } *aCol;
9412   int nColumn;            /* Number of used entries in aCol[] */
9413   int nColumnAlloc;       /* Number of slots allocated for aCol[] */
9414   int nAccumulator;       /* Number of columns that show through to the output.
9415                           ** Additional columns are used only as parameters to
9416                           ** aggregate functions */
9417   struct AggInfo_func {   /* For each aggregate function */
9418     Expr *pExpr;             /* Expression encoding the function */
9419     FuncDef *pFunc;          /* The aggregate function implementation */
9420     int iMem;                /* Memory location that acts as accumulator */
9421     int iDistinct;           /* Ephermeral table used to enforce DISTINCT */
9422   } *aFunc;
9423   int nFunc;              /* Number of entries in aFunc[] */
9424   int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
9425 };
9426
9427 /*
9428 ** Each node of an expression in the parse tree is an instance
9429 ** of this structure.
9430 **
9431 ** Expr.op is the opcode.  The integer parser token codes are reused
9432 ** as opcodes here.  For example, the parser defines TK_GE to be an integer
9433 ** code representing the ">=" operator.  This same integer code is reused
9434 ** to represent the greater-than-or-equal-to operator in the expression
9435 ** tree.
9436 **
9437 ** Expr.pRight and Expr.pLeft are subexpressions.  Expr.pList is a list
9438 ** of argument if the expression is a function.
9439 **
9440 ** Expr.token is the operator token for this node.  For some expressions
9441 ** that have subexpressions, Expr.token can be the complete text that gave
9442 ** rise to the Expr.  In the latter case, the token is marked as being
9443 ** a compound token.
9444 **
9445 ** An expression of the form ID or ID.ID refers to a column in a table.
9446 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
9447 ** the integer cursor number of a VDBE cursor pointing to that table and
9448 ** Expr.iColumn is the column number for the specific column.  If the
9449 ** expression is used as a result in an aggregate SELECT, then the
9450 ** value is also stored in the Expr.iAgg column in the aggregate so that
9451 ** it can be accessed after all aggregates are computed.
9452 **
9453 ** If the expression is a function, the Expr.iTable is an integer code
9454 ** representing which function.  If the expression is an unbound variable
9455 ** marker (a question mark character '?' in the original SQL) then the
9456 ** Expr.iTable holds the index number for that variable.
9457 **
9458 ** If the expression is a subquery then Expr.iColumn holds an integer
9459 ** register number containing the result of the subquery.  If the
9460 ** subquery gives a constant result, then iTable is -1.  If the subquery
9461 ** gives a different answer at different times during statement processing
9462 ** then iTable is the address of a subroutine that computes the subquery.
9463 **
9464 ** The Expr.pSelect field points to a SELECT statement.  The SELECT might
9465 ** be the right operand of an IN operator.  Or, if a scalar SELECT appears
9466 ** in an expression the opcode is TK_SELECT and Expr.pSelect is the only
9467 ** operand.
9468 **
9469 ** If the Expr is of type OP_Column, and the table it is selecting from
9470 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
9471 ** corresponding table definition.
9472 */
9473 struct Expr {
9474   u8 op;                 /* Operation performed by this node */
9475   char affinity;         /* The affinity of the column or 0 if not a column */
9476   u16 flags;             /* Various flags.  See below */
9477   CollSeq *pColl;        /* The collation type of the column or 0 */
9478   Expr *pLeft, *pRight;  /* Left and right subnodes */
9479   ExprList *pList;       /* A list of expressions used as function arguments
9480                          ** or in "<expr> IN (<expr-list)" */
9481   Token token;           /* An operand token */
9482   Token span;            /* Complete text of the expression */
9483   int iTable, iColumn;   /* When op==TK_COLUMN, then this expr node means the
9484                          ** iColumn-th field of the iTable-th table. */
9485   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
9486   int iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
9487   int iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
9488   Select *pSelect;       /* When the expression is a sub-select.  Also the
9489                          ** right side of "<expr> IN (<select>)" */
9490   Table *pTab;           /* Table for TK_COLUMN expressions. */
9491 #if SQLITE_MAX_EXPR_DEPTH>0
9492   int nHeight;           /* Height of the tree headed by this node */
9493 #endif
9494 };
9495
9496 /*
9497 ** The following are the meanings of bits in the Expr.flags field.
9498 */
9499 #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
9500 #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
9501 #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
9502 #define EP_Error      0x0008  /* Expression contains one or more errors */
9503 #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
9504 #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
9505 #define EP_Dequoted   0x0040  /* True if the string has been dequoted */
9506 #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
9507 #define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
9508 #define EP_AnyAff     0x0200  /* Can take a cached column of any affinity */
9509 #define EP_FixedDest  0x0400  /* Result needed in a specific register */
9510 #define EP_IntValue   0x0800  /* Integer value contained in iTable */
9511 /*
9512 ** These macros can be used to test, set, or clear bits in the 
9513 ** Expr.flags field.
9514 */
9515 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
9516 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
9517 #define ExprSetProperty(E,P)     (E)->flags|=(P)
9518 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
9519
9520 /*
9521 ** A list of expressions.  Each expression may optionally have a
9522 ** name.  An expr/name combination can be used in several ways, such
9523 ** as the list of "expr AS ID" fields following a "SELECT" or in the
9524 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
9525 ** also be used as the argument to a function, in which case the a.zName
9526 ** field is not used.
9527 */
9528 struct ExprList {
9529   int nExpr;             /* Number of expressions on the list */
9530   int nAlloc;            /* Number of entries allocated below */
9531   int iECursor;          /* VDBE Cursor associated with this ExprList */
9532   struct ExprList_item {
9533     Expr *pExpr;           /* The list of expressions */
9534     char *zName;           /* Token associated with this expression */
9535     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
9536     u8 done;               /* A flag to indicate when processing is finished */
9537     u16 iCol;              /* For ORDER BY, column number in result set */
9538     u16 iAlias;            /* Index into Parse.aAlias[] for zName */
9539   } *a;                  /* One entry for each expression */
9540 };
9541
9542 /*
9543 ** An instance of this structure can hold a simple list of identifiers,
9544 ** such as the list "a,b,c" in the following statements:
9545 **
9546 **      INSERT INTO t(a,b,c) VALUES ...;
9547 **      CREATE INDEX idx ON t(a,b,c);
9548 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
9549 **
9550 ** The IdList.a.idx field is used when the IdList represents the list of
9551 ** column names after a table name in an INSERT statement.  In the statement
9552 **
9553 **     INSERT INTO t(a,b,c) ...
9554 **
9555 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
9556 */
9557 struct IdList {
9558   struct IdList_item {
9559     char *zName;      /* Name of the identifier */
9560     int idx;          /* Index in some Table.aCol[] of a column named zName */
9561   } *a;
9562   int nId;         /* Number of identifiers on the list */
9563   int nAlloc;      /* Number of entries allocated for a[] below */
9564 };
9565
9566 /*
9567 ** The bitmask datatype defined below is used for various optimizations.
9568 **
9569 ** Changing this from a 64-bit to a 32-bit type limits the number of
9570 ** tables in a join to 32 instead of 64.  But it also reduces the size
9571 ** of the library by 738 bytes on ix86.
9572 */
9573 typedef u64 Bitmask;
9574
9575 /*
9576 ** The following structure describes the FROM clause of a SELECT statement.
9577 ** Each table or subquery in the FROM clause is a separate element of
9578 ** the SrcList.a[] array.
9579 **
9580 ** With the addition of multiple database support, the following structure
9581 ** can also be used to describe a particular table such as the table that
9582 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
9583 ** such a table must be a simple name: ID.  But in SQLite, the table can
9584 ** now be identified by a database name, a dot, then the table name: ID.ID.
9585 **
9586 ** The jointype starts out showing the join type between the current table
9587 ** and the next table on the list.  The parser builds the list this way.
9588 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
9589 ** jointype expresses the join between the table and the previous table.
9590 */
9591 struct SrcList {
9592   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
9593   i16 nAlloc;      /* Number of entries allocated in a[] below */
9594   struct SrcList_item {
9595     char *zDatabase;  /* Name of database holding this table */
9596     char *zName;      /* Name of the table */
9597     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
9598     Table *pTab;      /* An SQL table corresponding to zName */
9599     Select *pSelect;  /* A SELECT statement used in place of a table name */
9600     u8 isPopulated;   /* Temporary table associated with SELECT is populated */
9601     u8 jointype;      /* Type of join between this able and the previous */
9602     int iCursor;      /* The VDBE cursor number used to access this table */
9603     Expr *pOn;        /* The ON clause of a join */
9604     IdList *pUsing;   /* The USING clause of a join */
9605     Bitmask colUsed;  /* Bit N (1<<N) set if column N or pTab is used */
9606   } a[1];             /* One entry for each identifier on the list */
9607 };
9608
9609 /*
9610 ** Permitted values of the SrcList.a.jointype field
9611 */
9612 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
9613 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
9614 #define JT_NATURAL   0x0004    /* True for a "natural" join */
9615 #define JT_LEFT      0x0008    /* Left outer join */
9616 #define JT_RIGHT     0x0010    /* Right outer join */
9617 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
9618 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
9619
9620 /*
9621 ** For each nested loop in a WHERE clause implementation, the WhereInfo
9622 ** structure contains a single instance of this structure.  This structure
9623 ** is intended to be private the the where.c module and should not be
9624 ** access or modified by other modules.
9625 **
9626 ** The pIdxInfo and pBestIdx fields are used to help pick the best
9627 ** index on a virtual table.  The pIdxInfo pointer contains indexing
9628 ** information for the i-th table in the FROM clause before reordering.
9629 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
9630 ** The pBestIdx pointer is a copy of pIdxInfo for the i-th table after
9631 ** FROM clause ordering.  This is a little confusing so I will repeat
9632 ** it in different words.  WhereInfo.a[i].pIdxInfo is index information 
9633 ** for WhereInfo.pTabList.a[i].  WhereInfo.a[i].pBestInfo is the
9634 ** index information for the i-th loop of the join.  pBestInfo is always
9635 ** either NULL or a copy of some pIdxInfo.  So for cleanup it is 
9636 ** sufficient to free all of the pIdxInfo pointers.
9637 ** 
9638 */
9639 struct WhereLevel {
9640   int iFrom;            /* Which entry in the FROM clause */
9641   int flags;            /* Flags associated with this level */
9642   int iMem;             /* First memory cell used by this level */
9643   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
9644   Index *pIdx;          /* Index used.  NULL if no index */
9645   int iTabCur;          /* The VDBE cursor used to access the table */
9646   int iIdxCur;          /* The VDBE cursor used to acesss pIdx */
9647   int brk;              /* Jump here to break out of the loop */
9648   int nxt;              /* Jump here to start the next IN combination */
9649   int cont;             /* Jump here to continue with the next loop cycle */
9650   int top;              /* First instruction of interior of the loop */
9651   int op, p1, p2;       /* Opcode used to terminate the loop */
9652   int nEq;              /* Number of == or IN constraints on this loop */
9653   int nIn;              /* Number of IN operators constraining this loop */
9654   struct InLoop {
9655     int iCur;              /* The VDBE cursor used by this IN operator */
9656     int topAddr;           /* Top of the IN loop */
9657   } *aInLoop;           /* Information about each nested IN operator */
9658   sqlite3_index_info *pBestIdx;  /* Index information for this level */
9659
9660   /* The following field is really not part of the current level.  But
9661   ** we need a place to cache index information for each table in the
9662   ** FROM clause and the WhereLevel structure is a convenient place.
9663   */
9664   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
9665 };
9666
9667 /*
9668 ** Flags appropriate for the wflags parameter of sqlite3WhereBegin().
9669 */
9670 #define WHERE_ORDERBY_NORMAL     0   /* No-op */
9671 #define WHERE_ORDERBY_MIN        1   /* ORDER BY processing for min() func */
9672 #define WHERE_ORDERBY_MAX        2   /* ORDER BY processing for max() func */
9673 #define WHERE_ONEPASS_DESIRED    4   /* Want to do one-pass UPDATE/DELETE */
9674
9675 /*
9676 ** The WHERE clause processing routine has two halves.  The
9677 ** first part does the start of the WHERE loop and the second
9678 ** half does the tail of the WHERE loop.  An instance of
9679 ** this structure is returned by the first half and passed
9680 ** into the second half to give some continuity.
9681 */
9682 struct WhereInfo {
9683   Parse *pParse;       /* Parsing and code generating context */
9684   u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
9685   SrcList *pTabList;   /* List of tables in the join */
9686   int iTop;            /* The very beginning of the WHERE loop */
9687   int iContinue;       /* Jump here to continue with next record */
9688   int iBreak;          /* Jump here to break out of the loop */
9689   int nLevel;          /* Number of nested loop */
9690   sqlite3_index_info **apInfo;  /* Array of pointers to index info structures */
9691   WhereLevel a[1];     /* Information about each nest loop in the WHERE */
9692 };
9693
9694 /*
9695 ** A NameContext defines a context in which to resolve table and column
9696 ** names.  The context consists of a list of tables (the pSrcList) field and
9697 ** a list of named expression (pEList).  The named expression list may
9698 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
9699 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
9700 ** pEList corresponds to the result set of a SELECT and is NULL for
9701 ** other statements.
9702 **
9703 ** NameContexts can be nested.  When resolving names, the inner-most 
9704 ** context is searched first.  If no match is found, the next outer
9705 ** context is checked.  If there is still no match, the next context
9706 ** is checked.  This process continues until either a match is found
9707 ** or all contexts are check.  When a match is found, the nRef member of
9708 ** the context containing the match is incremented. 
9709 **
9710 ** Each subquery gets a new NameContext.  The pNext field points to the
9711 ** NameContext in the parent query.  Thus the process of scanning the
9712 ** NameContext list corresponds to searching through successively outer
9713 ** subqueries looking for a match.
9714 */
9715 struct NameContext {
9716   Parse *pParse;       /* The parser */
9717   SrcList *pSrcList;   /* One or more tables used to resolve names */
9718   ExprList *pEList;    /* Optional list of named expressions */
9719   int nRef;            /* Number of names resolved by this context */
9720   int nErr;            /* Number of errors encountered while resolving names */
9721   u8 allowAgg;         /* Aggregate functions allowed here */
9722   u8 hasAgg;           /* True if aggregates are seen */
9723   u8 isCheck;          /* True if resolving names in a CHECK constraint */
9724   int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
9725   AggInfo *pAggInfo;   /* Information about aggregates at this level */
9726   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
9727 };
9728
9729 /*
9730 ** An instance of the following structure contains all information
9731 ** needed to generate code for a single SELECT statement.
9732 **
9733 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
9734 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
9735 ** limit and nOffset to the value of the offset (or 0 if there is not
9736 ** offset).  But later on, nLimit and nOffset become the memory locations
9737 ** in the VDBE that record the limit and offset counters.
9738 **
9739 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
9740 ** These addresses must be stored so that we can go back and fill in
9741 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
9742 ** the number of columns in P2 can be computed at the same time
9743 ** as the OP_OpenEphm instruction is coded because not
9744 ** enough information about the compound query is known at that point.
9745 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
9746 ** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
9747 ** sequences for the ORDER BY clause.
9748 */
9749 struct Select {
9750   ExprList *pEList;      /* The fields of the result */
9751   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
9752   char affinity;         /* MakeRecord with this affinity for SRT_Set */
9753   u16 selFlags;          /* Various SF_* values */
9754   SrcList *pSrc;         /* The FROM clause */
9755   Expr *pWhere;          /* The WHERE clause */
9756   ExprList *pGroupBy;    /* The GROUP BY clause */
9757   Expr *pHaving;         /* The HAVING clause */
9758   ExprList *pOrderBy;    /* The ORDER BY clause */
9759   Select *pPrior;        /* Prior select in a compound select statement */
9760   Select *pNext;         /* Next select to the left in a compound */
9761   Select *pRightmost;    /* Right-most select in a compound select statement */
9762   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
9763   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
9764   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
9765   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
9766 };
9767
9768 /*
9769 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
9770 ** "Select Flag".
9771 */
9772 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
9773 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
9774 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
9775 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
9776 #define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
9777 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
9778
9779
9780 /*
9781 ** The results of a select can be distributed in several ways.  The
9782 ** "SRT" prefix means "SELECT Result Type".
9783 */
9784 #define SRT_Union        1  /* Store result as keys in an index */
9785 #define SRT_Except       2  /* Remove result from a UNION index */
9786 #define SRT_Exists       3  /* Store 1 if the result is not empty */
9787 #define SRT_Discard      4  /* Do not save the results anywhere */
9788
9789 /* The ORDER BY clause is ignored for all of the above */
9790 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
9791
9792 #define SRT_Output       5  /* Output each row of result */
9793 #define SRT_Mem          6  /* Store result in a memory cell */
9794 #define SRT_Set          7  /* Store results as keys in an index */
9795 #define SRT_Table        8  /* Store result as data with an automatic rowid */
9796 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
9797 #define SRT_Coroutine   10  /* Generate a single row of result */
9798
9799 /*
9800 ** A structure used to customize the behaviour of sqlite3Select(). See
9801 ** comments above sqlite3Select() for details.
9802 */
9803 typedef struct SelectDest SelectDest;
9804 struct SelectDest {
9805   u8 eDest;         /* How to dispose of the results */
9806   u8 affinity;      /* Affinity used when eDest==SRT_Set */
9807   int iParm;        /* A parameter used by the eDest disposal method */
9808   int iMem;         /* Base register where results are written */
9809   int nMem;         /* Number of registers allocated */
9810 };
9811
9812 /*
9813 ** An SQL parser context.  A copy of this structure is passed through
9814 ** the parser and down into all the parser action routine in order to
9815 ** carry around information that is global to the entire parse.
9816 **
9817 ** The structure is divided into two parts.  When the parser and code
9818 ** generate call themselves recursively, the first part of the structure
9819 ** is constant but the second part is reset at the beginning and end of
9820 ** each recursion.
9821 **
9822 ** The nTableLock and aTableLock variables are only used if the shared-cache 
9823 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
9824 ** used to store the set of table-locks required by the statement being
9825 ** compiled. Function sqlite3TableLock() is used to add entries to the
9826 ** list.
9827 */
9828 struct Parse {
9829   sqlite3 *db;         /* The main database structure */
9830   int rc;              /* Return code from execution */
9831   char *zErrMsg;       /* An error message */
9832   Vdbe *pVdbe;         /* An engine for executing database bytecode */
9833   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
9834   u8 nameClash;        /* A permanent table name clashes with temp table name */
9835   u8 checkSchema;      /* Causes schema cookie check after an error */
9836   u8 nested;           /* Number of nested calls to the parser/code generator */
9837   u8 parseError;       /* True after a parsing error.  Ticket #1794 */
9838   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
9839   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
9840   int aTempReg[8];     /* Holding area for temporary registers */
9841   int nRangeReg;       /* Size of the temporary register block */
9842   int iRangeReg;       /* First register in temporary register block */
9843   int nErr;            /* Number of errors seen */
9844   int nTab;            /* Number of previously allocated VDBE cursors */
9845   int nMem;            /* Number of memory cells used so far */
9846   int nSet;            /* Number of sets used so far */
9847   int ckBase;          /* Base register of data during check constraints */
9848   int disableColCache; /* True to disable adding to column cache */
9849   int nColCache;       /* Number of entries in the column cache */
9850   int iColCache;       /* Next entry of the cache to replace */
9851   struct yColCache {
9852     int iTable;           /* Table cursor number */
9853     int iColumn;          /* Table column number */
9854     char affChange;       /* True if this register has had an affinity change */
9855     int iReg;             /* Register holding value of this column */
9856   } aColCache[10];     /* One for each valid column cache entry */
9857   u32 writeMask;       /* Start a write transaction on these databases */
9858   u32 cookieMask;      /* Bitmask of schema verified databases */
9859   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
9860   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
9861 #ifndef SQLITE_OMIT_SHARED_CACHE
9862   int nTableLock;        /* Number of locks in aTableLock */
9863   TableLock *aTableLock; /* Required table locks for shared-cache mode */
9864 #endif
9865   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
9866   int regRoot;         /* Register holding root page number for new objects */
9867
9868   /* Above is constant between recursions.  Below is reset before and after
9869   ** each recursion */
9870
9871   int nVar;            /* Number of '?' variables seen in the SQL so far */
9872   int nVarExpr;        /* Number of used slots in apVarExpr[] */
9873   int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
9874   Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
9875   int nAlias;          /* Number of aliased result set columns */
9876   int *aAlias;         /* Register used to hold aliased result */
9877   u8 explain;          /* True if the EXPLAIN flag is found on the query */
9878   Token sErrToken;     /* The token at which the error occurred */
9879   Token sNameToken;    /* Token with unqualified schema object name */
9880   Token sLastToken;    /* The last token parsed */
9881   const char *zSql;    /* All SQL text */
9882   const char *zTail;   /* All SQL text past the last semicolon parsed */
9883   Table *pNewTable;    /* A table being constructed by CREATE TABLE */
9884   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
9885   TriggerStack *trigStack;  /* Trigger actions being coded */
9886   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
9887 #ifndef SQLITE_OMIT_VIRTUALTABLE
9888   Token sArg;                /* Complete text of a module argument */
9889   u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
9890   int nVtabLock;             /* Number of virtual tables to lock */
9891   Table **apVtabLock;        /* Pointer to virtual tables needing locking */
9892 #endif
9893   int nHeight;            /* Expression tree height of current sub-select */
9894   Table *pZombieTab;      /* List of Table objects to delete after code gen */
9895 };
9896
9897 #ifdef SQLITE_OMIT_VIRTUALTABLE
9898   #define IN_DECLARE_VTAB 0
9899 #else
9900   #define IN_DECLARE_VTAB (pParse->declareVtab)
9901 #endif
9902
9903 /*
9904 ** An instance of the following structure can be declared on a stack and used
9905 ** to save the Parse.zAuthContext value so that it can be restored later.
9906 */
9907 struct AuthContext {
9908   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
9909   Parse *pParse;              /* The Parse structure */
9910 };
9911
9912 /*
9913 ** Bitfield flags for P2 value in OP_Insert and OP_Delete
9914 */
9915 #define OPFLAG_NCHANGE   1    /* Set to update db->nChange */
9916 #define OPFLAG_LASTROWID 2    /* Set to update db->lastRowid */
9917 #define OPFLAG_ISUPDATE  4    /* This OP_Insert is an sql UPDATE */
9918 #define OPFLAG_APPEND    8    /* This is likely to be an append */
9919
9920 /*
9921  * Each trigger present in the database schema is stored as an instance of
9922  * struct Trigger. 
9923  *
9924  * Pointers to instances of struct Trigger are stored in two ways.
9925  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the 
9926  *    database). This allows Trigger structures to be retrieved by name.
9927  * 2. All triggers associated with a single table form a linked list, using the
9928  *    pNext member of struct Trigger. A pointer to the first element of the
9929  *    linked list is stored as the "pTrigger" member of the associated
9930  *    struct Table.
9931  *
9932  * The "step_list" member points to the first element of a linked list
9933  * containing the SQL statements specified as the trigger program.
9934  */
9935 struct Trigger {
9936   char *name;             /* The name of the trigger                        */
9937   char *table;            /* The table or view to which the trigger applies */
9938   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
9939   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
9940   Expr *pWhen;            /* The WHEN clause of the expresion (may be NULL) */
9941   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
9942                              the <column-list> is stored here */
9943   Token nameToken;        /* Token containing zName. Use during parsing only */
9944   Schema *pSchema;        /* Schema containing the trigger */
9945   Schema *pTabSchema;     /* Schema containing the table */
9946   TriggerStep *step_list; /* Link list of trigger program steps             */
9947   Trigger *pNext;         /* Next trigger associated with the table */
9948 };
9949
9950 /*
9951 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
9952 ** determine which. 
9953 **
9954 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
9955 ** In that cases, the constants below can be ORed together.
9956 */
9957 #define TRIGGER_BEFORE  1
9958 #define TRIGGER_AFTER   2
9959
9960 /*
9961  * An instance of struct TriggerStep is used to store a single SQL statement
9962  * that is a part of a trigger-program. 
9963  *
9964  * Instances of struct TriggerStep are stored in a singly linked list (linked
9965  * using the "pNext" member) referenced by the "step_list" member of the 
9966  * associated struct Trigger instance. The first element of the linked list is
9967  * the first step of the trigger-program.
9968  * 
9969  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
9970  * "SELECT" statement. The meanings of the other members is determined by the 
9971  * value of "op" as follows:
9972  *
9973  * (op == TK_INSERT)
9974  * orconf    -> stores the ON CONFLICT algorithm
9975  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
9976  *              this stores a pointer to the SELECT statement. Otherwise NULL.
9977  * target    -> A token holding the name of the table to insert into.
9978  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
9979  *              this stores values to be inserted. Otherwise NULL.
9980  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
9981  *              statement, then this stores the column-names to be
9982  *              inserted into.
9983  *
9984  * (op == TK_DELETE)
9985  * target    -> A token holding the name of the table to delete from.
9986  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
9987  *              Otherwise NULL.
9988  * 
9989  * (op == TK_UPDATE)
9990  * target    -> A token holding the name of the table to update rows of.
9991  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
9992  *              Otherwise NULL.
9993  * pExprList -> A list of the columns to update and the expressions to update
9994  *              them to. See sqlite3Update() documentation of "pChanges"
9995  *              argument.
9996  * 
9997  */
9998 struct TriggerStep {
9999   int op;              /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
10000   int orconf;          /* OE_Rollback etc. */
10001   Trigger *pTrig;      /* The trigger that this step is a part of */
10002
10003   Select *pSelect;     /* Valid for SELECT and sometimes 
10004                           INSERT steps (when pExprList == 0) */
10005   Token target;        /* Valid for DELETE, UPDATE, INSERT steps */
10006   Expr *pWhere;        /* Valid for DELETE, UPDATE steps */
10007   ExprList *pExprList; /* Valid for UPDATE statements and sometimes 
10008                            INSERT steps (when pSelect == 0)         */
10009   IdList *pIdList;     /* Valid for INSERT statements only */
10010   TriggerStep *pNext;  /* Next in the link-list */
10011   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
10012 };
10013
10014 /*
10015  * An instance of struct TriggerStack stores information required during code
10016  * generation of a single trigger program. While the trigger program is being
10017  * coded, its associated TriggerStack instance is pointed to by the
10018  * "pTriggerStack" member of the Parse structure.
10019  *
10020  * The pTab member points to the table that triggers are being coded on. The 
10021  * newIdx member contains the index of the vdbe cursor that points at the temp
10022  * table that stores the new.* references. If new.* references are not valid
10023  * for the trigger being coded (for example an ON DELETE trigger), then newIdx
10024  * is set to -1. The oldIdx member is analogous to newIdx, for old.* references.
10025  *
10026  * The ON CONFLICT policy to be used for the trigger program steps is stored 
10027  * as the orconf member. If this is OE_Default, then the ON CONFLICT clause 
10028  * specified for individual triggers steps is used.
10029  *
10030  * struct TriggerStack has a "pNext" member, to allow linked lists to be
10031  * constructed. When coding nested triggers (triggers fired by other triggers)
10032  * each nested trigger stores its parent trigger's TriggerStack as the "pNext" 
10033  * pointer. Once the nested trigger has been coded, the pNext value is restored
10034  * to the pTriggerStack member of the Parse stucture and coding of the parent
10035  * trigger continues.
10036  *
10037  * Before a nested trigger is coded, the linked list pointed to by the 
10038  * pTriggerStack is scanned to ensure that the trigger is not about to be coded
10039  * recursively. If this condition is detected, the nested trigger is not coded.
10040  */
10041 struct TriggerStack {
10042   Table *pTab;         /* Table that triggers are currently being coded on */
10043   int newIdx;          /* Index of vdbe cursor to "new" temp table */
10044   int oldIdx;          /* Index of vdbe cursor to "old" temp table */
10045   u32 newColMask;
10046   u32 oldColMask;
10047   int orconf;          /* Current orconf policy */
10048   int ignoreJump;      /* where to jump to for a RAISE(IGNORE) */
10049   Trigger *pTrigger;   /* The trigger currently being coded */
10050   TriggerStack *pNext; /* Next trigger down on the trigger stack */
10051 };
10052
10053 /*
10054 ** The following structure contains information used by the sqliteFix...
10055 ** routines as they walk the parse tree to make database references
10056 ** explicit.  
10057 */
10058 typedef struct DbFixer DbFixer;
10059 struct DbFixer {
10060   Parse *pParse;      /* The parsing context.  Error messages written here */
10061   const char *zDb;    /* Make sure all objects are contained in this database */
10062   const char *zType;  /* Type of the container - used for error messages */
10063   const Token *pName; /* Name of the container - used for error messages */
10064 };
10065
10066 /*
10067 ** An objected used to accumulate the text of a string where we
10068 ** do not necessarily know how big the string will be in the end.
10069 */
10070 struct StrAccum {
10071   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
10072   char *zBase;         /* A base allocation.  Not from malloc. */
10073   char *zText;         /* The string collected so far */
10074   int  nChar;          /* Length of the string so far */
10075   int  nAlloc;         /* Amount of space allocated in zText */
10076   int  mxAlloc;        /* Maximum allowed string length */
10077   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
10078   u8   useMalloc;      /* True if zText is enlargable using realloc */
10079   u8   tooBig;         /* Becomes true if string size exceeds limits */
10080 };
10081
10082 /*
10083 ** A pointer to this structure is used to communicate information
10084 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
10085 */
10086 typedef struct {
10087   sqlite3 *db;        /* The database being initialized */
10088   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
10089   char **pzErrMsg;    /* Error message stored here */
10090   int rc;             /* Result code stored here */
10091 } InitData;
10092
10093 /*
10094 ** Structure containing global configuration data for the SQLite library.
10095 **
10096 ** This structure also contains some state information.
10097 */
10098 struct Sqlite3Config {
10099   int bMemstat;                     /* True to enable memory status */
10100   int bCoreMutex;                   /* True to enable core mutexing */
10101   int bFullMutex;                   /* True to enable full mutexing */
10102   int mxStrlen;                     /* Maximum string length */
10103   int szLookaside;                  /* Default lookaside buffer size */
10104   int nLookaside;                   /* Default lookaside buffer count */
10105   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
10106   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
10107   void *pHeap;                      /* Heap storage space */
10108   int nHeap;                        /* Size of pHeap[] */
10109   int mnReq, mxReq;                 /* Min and max heap requests sizes */
10110   void *pScratch;                   /* Scratch memory */
10111   int szScratch;                    /* Size of each scratch buffer */
10112   int nScratch;                     /* Number of scratch buffers */
10113   void *pPage;                      /* Page cache memory */
10114   int szPage;                       /* Size of each page in pPage[] */
10115   int nPage;                        /* Number of pages in pPage[] */
10116   int isInit;                       /* True after initialization has finished */
10117   int inProgress;                   /* True while initialization in progress */
10118   int isMallocInit;                 /* True after malloc is initialized */
10119   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
10120   int nRefInitMutex;                /* Number of users of pInitMutex */
10121   int nSmall;                       /* alloc size threshold used by mem6.c */
10122   int mxParserStack;                /* maximum depth of the parser stack */
10123   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
10124 };
10125
10126 /*
10127 ** Context pointer passed down through the tree-walk.
10128 */
10129 struct Walker {
10130   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
10131   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
10132   Parse *pParse;                            /* Parser context.  */
10133   union {                                   /* Extra data for callback */
10134     NameContext *pNC;                          /* Naming context */
10135     int i;                                     /* Integer value */
10136   } u;
10137 };
10138
10139 /* Forward declarations */
10140 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
10141 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
10142 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
10143 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
10144 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
10145
10146 /*
10147 ** Return code from the parse-tree walking primitives and their
10148 ** callbacks.
10149 */
10150 #define WRC_Continue    0
10151 #define WRC_Prune       1
10152 #define WRC_Abort       2
10153
10154 /*
10155 ** Assuming zIn points to the first byte of a UTF-8 character,
10156 ** advance zIn to point to the first byte of the next UTF-8 character.
10157 */
10158 #define SQLITE_SKIP_UTF8(zIn) {                        \
10159   if( (*(zIn++))>=0xc0 ){                              \
10160     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
10161   }                                                    \
10162 }
10163
10164 /*
10165 ** The SQLITE_CORRUPT_BKPT macro can be either a constant (for production
10166 ** builds) or a function call (for debugging).  If it is a function call,
10167 ** it allows the operator to set a breakpoint at the spot where database
10168 ** corruption is first detected.
10169 */
10170 #ifdef SQLITE_DEBUG
10171 SQLITE_PRIVATE   int sqlite3Corrupt(void);
10172 # define SQLITE_CORRUPT_BKPT sqlite3Corrupt()
10173 #else
10174 # define SQLITE_CORRUPT_BKPT SQLITE_CORRUPT
10175 #endif
10176
10177 /*
10178 ** Internal function prototypes
10179 */
10180 SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
10181 SQLITE_PRIVATE int sqlite3StrNICmp(const char *, const char *, int);
10182 SQLITE_PRIVATE int sqlite3IsNumber(const char*, int*, u8);
10183 SQLITE_PRIVATE int sqlite3Strlen(sqlite3*, const char*);
10184
10185 SQLITE_PRIVATE int sqlite3MallocInit(void);
10186 SQLITE_PRIVATE void sqlite3MallocEnd(void);
10187 SQLITE_PRIVATE void *sqlite3Malloc(int);
10188 SQLITE_PRIVATE void *sqlite3MallocZero(int);
10189 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
10190 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
10191 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
10192 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
10193 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
10194 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
10195 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
10196 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
10197 SQLITE_PRIVATE int sqlite3MallocSize(void*);
10198 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
10199 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
10200 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
10201 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
10202 SQLITE_PRIVATE void sqlite3PageFree(void*);
10203 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
10204 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetDefault(void);
10205 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
10206 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
10207 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys6(void);
10208 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
10209 SQLITE_PRIVATE int sqlite3MemoryAlarm(void (*)(void*, sqlite3_int64, int), void*, sqlite3_int64);
10210
10211 #ifndef SQLITE_MUTEX_NOOP
10212 SQLITE_PRIVATE   sqlite3_mutex_methods *sqlite3DefaultMutex(void);
10213 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
10214 SQLITE_PRIVATE   int sqlite3MutexInit(void);
10215 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
10216 #endif
10217
10218 SQLITE_PRIVATE int sqlite3StatusValue(int);
10219 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
10220 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
10221
10222 SQLITE_PRIVATE int sqlite3IsNaN(double);
10223
10224 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
10225 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
10226 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
10227 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
10228 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
10229 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
10230 #endif
10231 #if defined(SQLITE_TEST)
10232 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
10233 #endif
10234 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
10235 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
10236 SQLITE_PRIVATE void sqlite3ErrorClear(Parse*);
10237 SQLITE_PRIVATE void sqlite3Dequote(char*);
10238 SQLITE_PRIVATE void sqlite3DequoteExpr(sqlite3*, Expr*);
10239 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
10240 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
10241 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
10242 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
10243 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
10244 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
10245 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
10246 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*, int, Expr*, Expr*, const Token*);
10247 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
10248 SQLITE_PRIVATE Expr *sqlite3RegisterExpr(Parse*,Token*);
10249 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
10250 SQLITE_PRIVATE void sqlite3ExprSpan(Expr*,Token*,Token*);
10251 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
10252 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
10253 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
10254 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*,Token*);
10255 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
10256 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
10257 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
10258 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
10259 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
10260 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
10261 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
10262 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
10263 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
10264 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
10265 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
10266 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
10267 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
10268 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
10269 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
10270 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,Expr*);
10271 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
10272 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
10273
10274 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
10275 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
10276 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
10277 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32);
10278 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
10279 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
10280
10281 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
10282
10283 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
10284 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
10285 #else
10286 # define sqlite3ViewGetColumnNames(A,B) 0
10287 #endif
10288
10289 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
10290 SQLITE_PRIVATE void sqlite3DeleteTable(Table*);
10291 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
10292 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
10293 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
10294 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
10295 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
10296 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*, Token*,
10297                                       Select*, Expr*, IdList*);
10298 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
10299 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
10300 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
10301 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
10302 SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
10303                         Token*, int, int);
10304 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
10305 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
10306 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
10307                          Expr*,ExprList*,int,Expr*,Expr*);
10308 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
10309 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
10310 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
10311 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
10312 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
10313 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
10314 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u8);
10315 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
10316 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, int);
10317 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
10318 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
10319 SQLITE_PRIVATE void sqlite3ExprClearColumnCache(Parse*, int);
10320 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
10321 SQLITE_PRIVATE int sqlite3ExprWritableRegister(Parse*,int,int);
10322 SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse*,int,int);
10323 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
10324 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
10325 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
10326 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
10327 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
10328 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
10329 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
10330 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
10331 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
10332 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
10333 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
10334 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
10335 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
10336 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
10337 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
10338 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
10339 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
10340 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
10341 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
10342 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
10343 SQLITE_PRIVATE Expr *sqlite3CreateIdExpr(Parse *, const char*);
10344 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
10345 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
10346 SQLITE_PRIVATE void sqlite3PrngResetState(void);
10347 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
10348 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
10349 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
10350 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
10351 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
10352 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
10353 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
10354 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
10355 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
10356 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
10357 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int);
10358 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
10359 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
10360 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
10361                                      int*,int,int,int,int);
10362 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*,int,int,int,int);
10363 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
10364 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
10365 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*);
10366 SQLITE_PRIVATE void sqlite3TokenCopy(sqlite3*,Token*, Token*);
10367 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*);
10368 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*);
10369 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
10370 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*);
10371 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
10372 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
10373 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
10374 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
10375 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
10376 SQLITE_PRIVATE int sqlite3GetBuiltinFunction(const char *, int, FuncDef **);
10377 #ifdef SQLITE_DEBUG
10378 SQLITE_PRIVATE   int sqlite3SafetyOn(sqlite3*);
10379 SQLITE_PRIVATE   int sqlite3SafetyOff(sqlite3*);
10380 #else
10381 # define sqlite3SafetyOn(A) 0
10382 # define sqlite3SafetyOff(A) 0
10383 #endif
10384 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
10385 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
10386 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
10387
10388 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
10389 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
10390 #endif
10391
10392 #ifndef SQLITE_OMIT_TRIGGER
10393 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
10394                            Expr*,int, int);
10395 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
10396 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
10397 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
10398 SQLITE_PRIVATE   int sqlite3TriggersExist(Parse*, Table*, int, ExprList*);
10399 SQLITE_PRIVATE   int sqlite3CodeRowTrigger(Parse*, int, ExprList*, int, Table *, int, int, 
10400                            int, int, u32*, u32*);
10401   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
10402 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
10403 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
10404 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
10405                                         ExprList*,Select*,int);
10406 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, int);
10407 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
10408 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
10409 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
10410 #else
10411 # define sqlite3TriggersExist(A,B,C,D,E,F) 0
10412 # define sqlite3DeleteTrigger(A,B)
10413 # define sqlite3DropTriggerPtr(A,B)
10414 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
10415 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I,J,K) 0
10416 #endif
10417
10418 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
10419 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
10420 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
10421 #ifndef SQLITE_OMIT_AUTHORIZATION
10422 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
10423 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
10424 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
10425 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
10426 #else
10427 # define sqlite3AuthRead(a,b,c,d)
10428 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
10429 # define sqlite3AuthContextPush(a,b,c)
10430 # define sqlite3AuthContextPop(a)  ((void)(a))
10431 #endif
10432 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
10433 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
10434 SQLITE_PRIVATE int sqlite3BtreeFactory(const sqlite3 *db, const char *zFilename,
10435                        int omitJournal, int nCache, int flags, Btree **ppBtree);
10436 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
10437 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
10438 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
10439 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
10440 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
10441 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
10442 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*);
10443 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
10444 SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *, int);
10445 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
10446 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
10447 SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8*, const u8**);
10448
10449 /*
10450 ** Routines to read and write variable-length integers.  These used to
10451 ** be defined locally, but now we use the varint routines in the util.c
10452 ** file.  Code should use the MACRO forms below, as the Varint32 versions
10453 ** are coded to assume the single byte case is already handled (which 
10454 ** the MACRO form does).
10455 */
10456 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
10457 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
10458 SQLITE_PRIVATE int sqlite3GetVarint(const unsigned char *, u64 *);
10459 SQLITE_PRIVATE int sqlite3GetVarint32(const unsigned char *, u32 *);
10460 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
10461
10462 /*
10463 ** The header of a record consists of a sequence variable-length integers.
10464 ** These integers are almost always small and are encoded as a single byte.
10465 ** The following macros take advantage this fact to provide a fast encode
10466 ** and decode of the integers in a record header.  It is faster for the common
10467 ** case where the integer is a single byte.  It is a little slower when the
10468 ** integer is two or more bytes.  But overall it is faster.
10469 **
10470 ** The following expressions are equivalent:
10471 **
10472 **     x = sqlite3GetVarint32( A, &B );
10473 **     x = sqlite3PutVarint32( A, B );
10474 **
10475 **     x = getVarint32( A, B );
10476 **     x = putVarint32( A, B );
10477 **
10478 */
10479 #define getVarint32(A,B)  ((*(A)<(unsigned char)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), &(B)))
10480 #define putVarint32(A,B)  (((B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
10481 #define getVarint    sqlite3GetVarint
10482 #define putVarint    sqlite3PutVarint
10483
10484
10485 SQLITE_PRIVATE void sqlite3IndexAffinityStr(Vdbe *, Index *);
10486 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
10487 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
10488 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
10489 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
10490 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*);
10491 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
10492 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
10493 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
10494 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
10495 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
10496 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char *,int,int);
10497 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName);
10498 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
10499 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *, Token *);
10500 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
10501 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
10502 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
10503
10504 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
10505 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
10506 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, 
10507                         void(*)(void*));
10508 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
10509 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
10510 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int);
10511 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
10512 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
10513 #ifndef SQLITE_AMALGAMATION
10514 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
10515 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
10516 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
10517 #endif
10518 SQLITE_PRIVATE void sqlite3RootPageMoved(Db*, int, int);
10519 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
10520 SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3*);
10521 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
10522 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
10523 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
10524 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
10525 SQLITE_PRIVATE void sqlite3CodeSubselect(Parse *, Expr *, int);
10526 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
10527 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
10528 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
10529 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
10530 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int);
10531 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
10532 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
10533 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, CollSeq *, const char *, int);
10534 SQLITE_PRIVATE char sqlite3AffinityType(const Token*);
10535 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
10536 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
10537 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
10538 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
10539 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
10540 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
10541 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
10542 SQLITE_PRIVATE void sqlite3AttachFunctions(sqlite3 *);
10543 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
10544 SQLITE_PRIVATE void sqlite3SchemaFree(void *);
10545 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
10546 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
10547 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
10548 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
10549   void (*)(sqlite3_context*,int,sqlite3_value **),
10550   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
10551 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
10552 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
10553
10554 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
10555 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
10556 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
10557 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
10558 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
10559
10560 /*
10561 ** The interface to the LEMON-generated parser
10562 */
10563 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
10564 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
10565 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
10566 #ifdef YYTRACKMAXSTACKDEPTH
10567 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
10568 #endif
10569
10570 SQLITE_PRIVATE int sqlite3AutoLoadExtensions(sqlite3*);
10571 #ifndef SQLITE_OMIT_LOAD_EXTENSION
10572 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
10573 #else
10574 # define sqlite3CloseExtensions(X)
10575 #endif
10576
10577 #ifndef SQLITE_OMIT_SHARED_CACHE
10578 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
10579 #else
10580   #define sqlite3TableLock(v,w,x,y,z)
10581 #endif
10582
10583 #ifdef SQLITE_TEST
10584 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
10585 #endif
10586
10587 #ifdef SQLITE_OMIT_VIRTUALTABLE
10588 #  define sqlite3VtabClear(X)
10589 #  define sqlite3VtabSync(X,Y) SQLITE_OK
10590 #  define sqlite3VtabRollback(X)
10591 #  define sqlite3VtabCommit(X)
10592 #else
10593 SQLITE_PRIVATE    void sqlite3VtabClear(Table*);
10594 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
10595 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
10596 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
10597 #endif
10598 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
10599 SQLITE_PRIVATE void sqlite3VtabLock(sqlite3_vtab*);
10600 SQLITE_PRIVATE void sqlite3VtabUnlock(sqlite3*, sqlite3_vtab*);
10601 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
10602 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
10603 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
10604 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
10605 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
10606 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
10607 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
10608 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, sqlite3_vtab *);
10609 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
10610 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
10611 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
10612 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
10613 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
10614 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
10615
10616
10617 /*
10618 ** Available fault injectors.  Should be numbered beginning with 0.
10619 */
10620 #define SQLITE_FAULTINJECTOR_MALLOC     0
10621 #define SQLITE_FAULTINJECTOR_COUNT      1
10622
10623 /*
10624 ** The interface to the code in fault.c used for identifying "benign"
10625 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
10626 ** is not defined.
10627 */
10628 #ifndef SQLITE_OMIT_BUILTIN_TEST
10629 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
10630 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
10631 #else
10632   #define sqlite3BeginBenignMalloc()
10633   #define sqlite3EndBenignMalloc()
10634 #endif
10635
10636 #define IN_INDEX_ROWID           1
10637 #define IN_INDEX_EPH             2
10638 #define IN_INDEX_INDEX           3
10639 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
10640
10641 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
10642 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
10643 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
10644 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
10645 #else
10646   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
10647 #endif
10648
10649 #if SQLITE_MAX_EXPR_DEPTH>0
10650 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
10651 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
10652 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
10653 #else
10654   #define sqlite3ExprSetHeight(x,y)
10655   #define sqlite3SelectExprHeight(x) 0
10656   #define sqlite3ExprCheckHeight(x,y)
10657 #endif
10658
10659 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
10660 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
10661
10662 #ifdef SQLITE_SSE
10663 #include "sseInt.h"
10664 #endif
10665
10666 #ifdef SQLITE_DEBUG
10667 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
10668 #endif
10669
10670 /*
10671 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
10672 ** sqlite3IoTrace is a pointer to a printf-like routine used to
10673 ** print I/O tracing messages. 
10674 */
10675 #ifdef SQLITE_ENABLE_IOTRACE
10676 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
10677 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
10678 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
10679 #else
10680 # define IOTRACE(A)
10681 # define sqlite3VdbeIOTraceSql(X)
10682 #endif
10683
10684 #endif
10685
10686 /************** End of sqliteInt.h *******************************************/
10687 /************** Begin file global.c ******************************************/
10688 /*
10689 ** 2008 June 13
10690 **
10691 ** The author disclaims copyright to this source code.  In place of
10692 ** a legal notice, here is a blessing:
10693 **
10694 **    May you do good and not evil.
10695 **    May you find forgiveness for yourself and forgive others.
10696 **    May you share freely, never taking more than you give.
10697 **
10698 *************************************************************************
10699 **
10700 ** This file contains definitions of global variables and contants.
10701 **
10702 ** $Id: global.c,v 1.8 2008/09/04 17:17:39 danielk1977 Exp $
10703 */
10704
10705
10706 /* An array to map all upper-case characters into their corresponding
10707 ** lower-case character. 
10708 **
10709 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
10710 ** handle case conversions for the UTF character set since the tables
10711 ** involved are nearly as big or bigger than SQLite itself.
10712 */
10713 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
10714 #ifdef SQLITE_ASCII
10715       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
10716      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
10717      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
10718      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
10719     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
10720     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
10721     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
10722     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
10723     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
10724     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
10725     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
10726     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
10727     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
10728     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
10729     252,253,254,255
10730 #endif
10731 #ifdef SQLITE_EBCDIC
10732       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
10733      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
10734      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
10735      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
10736      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
10737      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
10738      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
10739     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
10740     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
10741     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
10742     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
10743     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
10744     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
10745     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
10746     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
10747     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
10748 #endif
10749 };
10750
10751 /*
10752 ** The following singleton contains the global configuration for
10753 ** the SQLite library.
10754 */
10755 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
10756    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
10757    1,                         /* bCoreMutex */
10758    SQLITE_THREADSAFE==1,      /* bFullMutex */
10759    0x7ffffffe,                /* mxStrlen */
10760    100,                       /* szLookaside */
10761    500,                       /* nLookaside */
10762    /* Other fields all default to zero */
10763 };
10764
10765
10766 /*
10767 ** Hash table for global functions - functions common to all
10768 ** database connections.  After initialization, this table is
10769 ** read-only.
10770 */
10771 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
10772
10773 /************** End of global.c **********************************************/
10774 /************** Begin file status.c ******************************************/
10775 /*
10776 ** 2008 June 18
10777 **
10778 ** The author disclaims copyright to this source code.  In place of
10779 ** a legal notice, here is a blessing:
10780 **
10781 **    May you do good and not evil.
10782 **    May you find forgiveness for yourself and forgive others.
10783 **    May you share freely, never taking more than you give.
10784 **
10785 *************************************************************************
10786 **
10787 ** This module implements the sqlite3_status() interface and related
10788 ** functionality.
10789 **
10790 ** $Id: status.c,v 1.9 2008/09/02 00:52:52 drh Exp $
10791 */
10792
10793 /*
10794 ** Variables in which to record status information.
10795 */
10796 typedef struct sqlite3StatType sqlite3StatType;
10797 static SQLITE_WSD struct sqlite3StatType {
10798   int nowValue[9];         /* Current value */
10799   int mxValue[9];          /* Maximum value */
10800 } sqlite3Stat = { {0,}, {0,} };
10801
10802
10803 /* The "wsdStat" macro will resolve to the status information
10804 ** state vector.  If writable static data is unsupported on the target,
10805 ** we have to locate the state vector at run-time.  In the more common
10806 ** case where writable static data is supported, wsdStat can refer directly
10807 ** to the "sqlite3Stat" state vector declared above.
10808 */
10809 #ifdef SQLITE_OMIT_WSD
10810 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
10811 # define wsdStat x[0]
10812 #else
10813 # define wsdStatInit
10814 # define wsdStat sqlite3Stat
10815 #endif
10816
10817 /*
10818 ** Return the current value of a status parameter.
10819 */
10820 SQLITE_PRIVATE int sqlite3StatusValue(int op){
10821   wsdStatInit;
10822   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
10823   return wsdStat.nowValue[op];
10824 }
10825
10826 /*
10827 ** Add N to the value of a status record.  It is assumed that the
10828 ** caller holds appropriate locks.
10829 */
10830 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
10831   wsdStatInit;
10832   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
10833   wsdStat.nowValue[op] += N;
10834   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
10835     wsdStat.mxValue[op] = wsdStat.nowValue[op];
10836   }
10837 }
10838
10839 /*
10840 ** Set the value of a status to X.
10841 */
10842 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
10843   wsdStatInit;
10844   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
10845   wsdStat.nowValue[op] = X;
10846   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
10847     wsdStat.mxValue[op] = wsdStat.nowValue[op];
10848   }
10849 }
10850
10851 /*
10852 ** Query status information.
10853 **
10854 ** This implementation assumes that reading or writing an aligned
10855 ** 32-bit integer is an atomic operation.  If that assumption is not true,
10856 ** then this routine is not threadsafe.
10857 */
10858 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
10859   wsdStatInit;
10860   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
10861     return SQLITE_MISUSE;
10862   }
10863   *pCurrent = wsdStat.nowValue[op];
10864   *pHighwater = wsdStat.mxValue[op];
10865   if( resetFlag ){
10866     wsdStat.mxValue[op] = wsdStat.nowValue[op];
10867   }
10868   return SQLITE_OK;
10869 }
10870
10871 /*
10872 ** Query status information for a single database connection
10873 */
10874 SQLITE_API int sqlite3_db_status(
10875   sqlite3 *db,          /* The database connection whose status is desired */
10876   int op,               /* Status verb */
10877   int *pCurrent,        /* Write current value here */
10878   int *pHighwater,      /* Write high-water mark here */
10879   int resetFlag         /* Reset high-water mark if true */
10880 ){
10881   switch( op ){
10882     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
10883       *pCurrent = db->lookaside.nOut;
10884       *pHighwater = db->lookaside.mxOut;
10885       if( resetFlag ){
10886         db->lookaside.mxOut = db->lookaside.nOut;
10887       }
10888       break;
10889     }
10890     default: {
10891       return SQLITE_ERROR;
10892     }
10893   }
10894   return SQLITE_OK;
10895 }
10896
10897 /************** End of status.c **********************************************/
10898 /************** Begin file date.c ********************************************/
10899 /*
10900 ** 2003 October 31
10901 **
10902 ** The author disclaims copyright to this source code.  In place of
10903 ** a legal notice, here is a blessing:
10904 **
10905 **    May you do good and not evil.
10906 **    May you find forgiveness for yourself and forgive others.
10907 **    May you share freely, never taking more than you give.
10908 **
10909 *************************************************************************
10910 ** This file contains the C functions that implement date and time
10911 ** functions for SQLite.  
10912 **
10913 ** There is only one exported symbol in this file - the function
10914 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
10915 ** All other code has file scope.
10916 **
10917 ** $Id: date.c,v 1.90 2008/09/03 17:11:16 drh Exp $
10918 **
10919 ** SQLite processes all times and dates as Julian Day numbers.  The
10920 ** dates and times are stored as the number of days since noon
10921 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
10922 ** calendar system. 
10923 **
10924 ** 1970-01-01 00:00:00 is JD 2440587.5
10925 ** 2000-01-01 00:00:00 is JD 2451544.5
10926 **
10927 ** This implemention requires years to be expressed as a 4-digit number
10928 ** which means that only dates between 0000-01-01 and 9999-12-31 can
10929 ** be represented, even though julian day numbers allow a much wider
10930 ** range of dates.
10931 **
10932 ** The Gregorian calendar system is used for all dates and times,
10933 ** even those that predate the Gregorian calendar.  Historians usually
10934 ** use the Julian calendar for dates prior to 1582-10-15 and for some
10935 ** dates afterwards, depending on locale.  Beware of this difference.
10936 **
10937 ** The conversion algorithms are implemented based on descriptions
10938 ** in the following text:
10939 **
10940 **      Jean Meeus
10941 **      Astronomical Algorithms, 2nd Edition, 1998
10942 **      ISBM 0-943396-61-1
10943 **      Willmann-Bell, Inc
10944 **      Richmond, Virginia (USA)
10945 */
10946 #include <ctype.h>
10947 #include <time.h>
10948
10949 #ifndef SQLITE_OMIT_DATETIME_FUNCS
10950
10951 /*
10952 ** On recent Windows platforms, the localtime_s() function is available
10953 ** as part of the "Secure CRT". It is essentially equivalent to 
10954 ** localtime_r() available under most POSIX platforms, except that the 
10955 ** order of the parameters is reversed.
10956 **
10957 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
10958 **
10959 ** If the user has not indicated to use localtime_r() or localtime_s()
10960 ** already, check for an MSVC build environment that provides 
10961 ** localtime_s().
10962 */
10963 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
10964      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
10965 #define HAVE_LOCALTIME_S 1
10966 #endif
10967
10968 /*
10969 ** A structure for holding a single date and time.
10970 */
10971 typedef struct DateTime DateTime;
10972 struct DateTime {
10973   sqlite3_int64 iJD; /* The julian day number times 86400000 */
10974   int Y, M, D;       /* Year, month, and day */
10975   int h, m;          /* Hour and minutes */
10976   int tz;            /* Timezone offset in minutes */
10977   double s;          /* Seconds */
10978   char validYMD;     /* True if Y,M,D are valid */
10979   char validHMS;     /* True if h,m,s are valid */
10980   char validJD;      /* True if iJD is valid */
10981   char validTZ;      /* True if tz is valid */
10982 };
10983
10984
10985 /*
10986 ** Convert zDate into one or more integers.  Additional arguments
10987 ** come in groups of 5 as follows:
10988 **
10989 **       N       number of digits in the integer
10990 **       min     minimum allowed value of the integer
10991 **       max     maximum allowed value of the integer
10992 **       nextC   first character after the integer
10993 **       pVal    where to write the integers value.
10994 **
10995 ** Conversions continue until one with nextC==0 is encountered.
10996 ** The function returns the number of successful conversions.
10997 */
10998 static int getDigits(const char *zDate, ...){
10999   va_list ap;
11000   int val;
11001   int N;
11002   int min;
11003   int max;
11004   int nextC;
11005   int *pVal;
11006   int cnt = 0;
11007   va_start(ap, zDate);
11008   do{
11009     N = va_arg(ap, int);
11010     min = va_arg(ap, int);
11011     max = va_arg(ap, int);
11012     nextC = va_arg(ap, int);
11013     pVal = va_arg(ap, int*);
11014     val = 0;
11015     while( N-- ){
11016       if( !isdigit(*(u8*)zDate) ){
11017         goto end_getDigits;
11018       }
11019       val = val*10 + *zDate - '0';
11020       zDate++;
11021     }
11022     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
11023       goto end_getDigits;
11024     }
11025     *pVal = val;
11026     zDate++;
11027     cnt++;
11028   }while( nextC );
11029 end_getDigits:
11030   va_end(ap);
11031   return cnt;
11032 }
11033
11034 /*
11035 ** Read text from z[] and convert into a floating point number.  Return
11036 ** the number of digits converted.
11037 */
11038 #define getValue sqlite3AtoF
11039
11040 /*
11041 ** Parse a timezone extension on the end of a date-time.
11042 ** The extension is of the form:
11043 **
11044 **        (+/-)HH:MM
11045 **
11046 ** Or the "zulu" notation:
11047 **
11048 **        Z
11049 **
11050 ** If the parse is successful, write the number of minutes
11051 ** of change in p->tz and return 0.  If a parser error occurs,
11052 ** return non-zero.
11053 **
11054 ** A missing specifier is not considered an error.
11055 */
11056 static int parseTimezone(const char *zDate, DateTime *p){
11057   int sgn = 0;
11058   int nHr, nMn;
11059   int c;
11060   while( isspace(*(u8*)zDate) ){ zDate++; }
11061   p->tz = 0;
11062   c = *zDate;
11063   if( c=='-' ){
11064     sgn = -1;
11065   }else if( c=='+' ){
11066     sgn = +1;
11067   }else if( c=='Z' || c=='z' ){
11068     zDate++;
11069     goto zulu_time;
11070   }else{
11071     return c!=0;
11072   }
11073   zDate++;
11074   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
11075     return 1;
11076   }
11077   zDate += 5;
11078   p->tz = sgn*(nMn + nHr*60);
11079 zulu_time:
11080   while( isspace(*(u8*)zDate) ){ zDate++; }
11081   return *zDate!=0;
11082 }
11083
11084 /*
11085 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
11086 ** The HH, MM, and SS must each be exactly 2 digits.  The
11087 ** fractional seconds FFFF can be one or more digits.
11088 **
11089 ** Return 1 if there is a parsing error and 0 on success.
11090 */
11091 static int parseHhMmSs(const char *zDate, DateTime *p){
11092   int h, m, s;
11093   double ms = 0.0;
11094   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
11095     return 1;
11096   }
11097   zDate += 5;
11098   if( *zDate==':' ){
11099     zDate++;
11100     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
11101       return 1;
11102     }
11103     zDate += 2;
11104     if( *zDate=='.' && isdigit((u8)zDate[1]) ){
11105       double rScale = 1.0;
11106       zDate++;
11107       while( isdigit(*(u8*)zDate) ){
11108         ms = ms*10.0 + *zDate - '0';
11109         rScale *= 10.0;
11110         zDate++;
11111       }
11112       ms /= rScale;
11113     }
11114   }else{
11115     s = 0;
11116   }
11117   p->validJD = 0;
11118   p->validHMS = 1;
11119   p->h = h;
11120   p->m = m;
11121   p->s = s + ms;
11122   if( parseTimezone(zDate, p) ) return 1;
11123   p->validTZ = p->tz!=0;
11124   return 0;
11125 }
11126
11127 /*
11128 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
11129 ** that the YYYY-MM-DD is according to the Gregorian calendar.
11130 **
11131 ** Reference:  Meeus page 61
11132 */
11133 static void computeJD(DateTime *p){
11134   int Y, M, D, A, B, X1, X2;
11135
11136   if( p->validJD ) return;
11137   if( p->validYMD ){
11138     Y = p->Y;
11139     M = p->M;
11140     D = p->D;
11141   }else{
11142     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
11143     M = 1;
11144     D = 1;
11145   }
11146   if( M<=2 ){
11147     Y--;
11148     M += 12;
11149   }
11150   A = Y/100;
11151   B = 2 - A + (A/4);
11152   X1 = 365.25*(Y+4716);
11153   X2 = 30.6001*(M+1);
11154   p->iJD = (X1 + X2 + D + B - 1524.5)*86400000;
11155   p->validJD = 1;
11156   if( p->validHMS ){
11157     p->iJD += p->h*3600000 + p->m*60000 + p->s*1000;
11158     if( p->validTZ ){
11159       p->iJD -= p->tz*60000;
11160       p->validYMD = 0;
11161       p->validHMS = 0;
11162       p->validTZ = 0;
11163     }
11164   }
11165 }
11166
11167 /*
11168 ** Parse dates of the form
11169 **
11170 **     YYYY-MM-DD HH:MM:SS.FFF
11171 **     YYYY-MM-DD HH:MM:SS
11172 **     YYYY-MM-DD HH:MM
11173 **     YYYY-MM-DD
11174 **
11175 ** Write the result into the DateTime structure and return 0
11176 ** on success and 1 if the input string is not a well-formed
11177 ** date.
11178 */
11179 static int parseYyyyMmDd(const char *zDate, DateTime *p){
11180   int Y, M, D, neg;
11181
11182   if( zDate[0]=='-' ){
11183     zDate++;
11184     neg = 1;
11185   }else{
11186     neg = 0;
11187   }
11188   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
11189     return 1;
11190   }
11191   zDate += 10;
11192   while( isspace(*(u8*)zDate) || 'T'==*(u8*)zDate ){ zDate++; }
11193   if( parseHhMmSs(zDate, p)==0 ){
11194     /* We got the time */
11195   }else if( *zDate==0 ){
11196     p->validHMS = 0;
11197   }else{
11198     return 1;
11199   }
11200   p->validJD = 0;
11201   p->validYMD = 1;
11202   p->Y = neg ? -Y : Y;
11203   p->M = M;
11204   p->D = D;
11205   if( p->validTZ ){
11206     computeJD(p);
11207   }
11208   return 0;
11209 }
11210
11211 /*
11212 ** Set the time to the current time reported by the VFS
11213 */
11214 static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
11215   double r;
11216   sqlite3 *db = sqlite3_context_db_handle(context);
11217   sqlite3OsCurrentTime(db->pVfs, &r);
11218   p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
11219   p->validJD = 1;
11220 }
11221
11222 /*
11223 ** Attempt to parse the given string into a Julian Day Number.  Return
11224 ** the number of errors.
11225 **
11226 ** The following are acceptable forms for the input string:
11227 **
11228 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
11229 **      DDDD.DD 
11230 **      now
11231 **
11232 ** In the first form, the +/-HH:MM is always optional.  The fractional
11233 ** seconds extension (the ".FFF") is optional.  The seconds portion
11234 ** (":SS.FFF") is option.  The year and date can be omitted as long
11235 ** as there is a time string.  The time string can be omitted as long
11236 ** as there is a year and date.
11237 */
11238 static int parseDateOrTime(
11239   sqlite3_context *context, 
11240   const char *zDate, 
11241   DateTime *p
11242 ){
11243   if( parseYyyyMmDd(zDate,p)==0 ){
11244     return 0;
11245   }else if( parseHhMmSs(zDate, p)==0 ){
11246     return 0;
11247   }else if( sqlite3StrICmp(zDate,"now")==0){
11248     setDateTimeToCurrent(context, p);
11249     return 0;
11250   }else if( sqlite3IsNumber(zDate, 0, SQLITE_UTF8) ){
11251     double r;
11252     getValue(zDate, &r);
11253     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
11254     p->validJD = 1;
11255     return 0;
11256   }
11257   return 1;
11258 }
11259
11260 /*
11261 ** Compute the Year, Month, and Day from the julian day number.
11262 */
11263 static void computeYMD(DateTime *p){
11264   int Z, A, B, C, D, E, X1;
11265   if( p->validYMD ) return;
11266   if( !p->validJD ){
11267     p->Y = 2000;
11268     p->M = 1;
11269     p->D = 1;
11270   }else{
11271     Z = (p->iJD + 43200000)/86400000;
11272     A = (Z - 1867216.25)/36524.25;
11273     A = Z + 1 + A - (A/4);
11274     B = A + 1524;
11275     C = (B - 122.1)/365.25;
11276     D = 365.25*C;
11277     E = (B-D)/30.6001;
11278     X1 = 30.6001*E;
11279     p->D = B - D - X1;
11280     p->M = E<14 ? E-1 : E-13;
11281     p->Y = p->M>2 ? C - 4716 : C - 4715;
11282   }
11283   p->validYMD = 1;
11284 }
11285
11286 /*
11287 ** Compute the Hour, Minute, and Seconds from the julian day number.
11288 */
11289 static void computeHMS(DateTime *p){
11290   int s;
11291   if( p->validHMS ) return;
11292   computeJD(p);
11293   s = (p->iJD + 43200000) % 86400000;
11294   p->s = s/1000.0;
11295   s = p->s;
11296   p->s -= s;
11297   p->h = s/3600;
11298   s -= p->h*3600;
11299   p->m = s/60;
11300   p->s += s - p->m*60;
11301   p->validHMS = 1;
11302 }
11303
11304 /*
11305 ** Compute both YMD and HMS
11306 */
11307 static void computeYMD_HMS(DateTime *p){
11308   computeYMD(p);
11309   computeHMS(p);
11310 }
11311
11312 /*
11313 ** Clear the YMD and HMS and the TZ
11314 */
11315 static void clearYMD_HMS_TZ(DateTime *p){
11316   p->validYMD = 0;
11317   p->validHMS = 0;
11318   p->validTZ = 0;
11319 }
11320
11321 #ifndef SQLITE_OMIT_LOCALTIME
11322 /*
11323 ** Compute the difference (in milliseconds)
11324 ** between localtime and UTC (a.k.a. GMT)
11325 ** for the time value p where p is in UTC.
11326 */
11327 static int localtimeOffset(DateTime *p){
11328   DateTime x, y;
11329   time_t t;
11330   x = *p;
11331   computeYMD_HMS(&x);
11332   if( x.Y<1971 || x.Y>=2038 ){
11333     x.Y = 2000;
11334     x.M = 1;
11335     x.D = 1;
11336     x.h = 0;
11337     x.m = 0;
11338     x.s = 0.0;
11339   } else {
11340     int s = x.s + 0.5;
11341     x.s = s;
11342   }
11343   x.tz = 0;
11344   x.validJD = 0;
11345   computeJD(&x);
11346   t = x.iJD/1000 - 2440587.5*86400.0;
11347 #ifdef HAVE_LOCALTIME_R
11348   {
11349     struct tm sLocal;
11350     localtime_r(&t, &sLocal);
11351     y.Y = sLocal.tm_year + 1900;
11352     y.M = sLocal.tm_mon + 1;
11353     y.D = sLocal.tm_mday;
11354     y.h = sLocal.tm_hour;
11355     y.m = sLocal.tm_min;
11356     y.s = sLocal.tm_sec;
11357   }
11358 #elif defined(HAVE_LOCALTIME_S)
11359   {
11360     struct tm sLocal;
11361     localtime_s(&sLocal, &t);
11362     y.Y = sLocal.tm_year + 1900;
11363     y.M = sLocal.tm_mon + 1;
11364     y.D = sLocal.tm_mday;
11365     y.h = sLocal.tm_hour;
11366     y.m = sLocal.tm_min;
11367     y.s = sLocal.tm_sec;
11368   }
11369 #else
11370   {
11371     struct tm *pTm;
11372     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
11373     pTm = localtime(&t);
11374     y.Y = pTm->tm_year + 1900;
11375     y.M = pTm->tm_mon + 1;
11376     y.D = pTm->tm_mday;
11377     y.h = pTm->tm_hour;
11378     y.m = pTm->tm_min;
11379     y.s = pTm->tm_sec;
11380     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
11381   }
11382 #endif
11383   y.validYMD = 1;
11384   y.validHMS = 1;
11385   y.validJD = 0;
11386   y.validTZ = 0;
11387   computeJD(&y);
11388   return y.iJD - x.iJD;
11389 }
11390 #endif /* SQLITE_OMIT_LOCALTIME */
11391
11392 /*
11393 ** Process a modifier to a date-time stamp.  The modifiers are
11394 ** as follows:
11395 **
11396 **     NNN days
11397 **     NNN hours
11398 **     NNN minutes
11399 **     NNN.NNNN seconds
11400 **     NNN months
11401 **     NNN years
11402 **     start of month
11403 **     start of year
11404 **     start of week
11405 **     start of day
11406 **     weekday N
11407 **     unixepoch
11408 **     localtime
11409 **     utc
11410 **
11411 ** Return 0 on success and 1 if there is any kind of error.
11412 */
11413 static int parseModifier(const char *zMod, DateTime *p){
11414   int rc = 1;
11415   int n;
11416   double r;
11417   char *z, zBuf[30];
11418   z = zBuf;
11419   for(n=0; n<sizeof(zBuf)-1 && zMod[n]; n++){
11420     z[n] = tolower(zMod[n]);
11421   }
11422   z[n] = 0;
11423   switch( z[0] ){
11424 #ifndef SQLITE_OMIT_LOCALTIME
11425     case 'l': {
11426       /*    localtime
11427       **
11428       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
11429       ** show local time.
11430       */
11431       if( strcmp(z, "localtime")==0 ){
11432         computeJD(p);
11433         p->iJD += localtimeOffset(p);
11434         clearYMD_HMS_TZ(p);
11435         rc = 0;
11436       }
11437       break;
11438     }
11439 #endif
11440     case 'u': {
11441       /*
11442       **    unixepoch
11443       **
11444       ** Treat the current value of p->iJD as the number of
11445       ** seconds since 1970.  Convert to a real julian day number.
11446       */
11447       if( strcmp(z, "unixepoch")==0 && p->validJD ){
11448         p->iJD = p->iJD/86400.0 + 2440587.5*86400000.0;
11449         clearYMD_HMS_TZ(p);
11450         rc = 0;
11451       }
11452 #ifndef SQLITE_OMIT_LOCALTIME
11453       else if( strcmp(z, "utc")==0 ){
11454         double c1;
11455         computeJD(p);
11456         c1 = localtimeOffset(p);
11457         p->iJD -= c1;
11458         clearYMD_HMS_TZ(p);
11459         p->iJD += c1 - localtimeOffset(p);
11460         rc = 0;
11461       }
11462 #endif
11463       break;
11464     }
11465     case 'w': {
11466       /*
11467       **    weekday N
11468       **
11469       ** Move the date to the same time on the next occurrence of
11470       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
11471       ** date is already on the appropriate weekday, this is a no-op.
11472       */
11473       if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
11474                  && (n=r)==r && n>=0 && r<7 ){
11475         sqlite3_int64 Z;
11476         computeYMD_HMS(p);
11477         p->validTZ = 0;
11478         p->validJD = 0;
11479         computeJD(p);
11480         Z = ((p->iJD + 129600000)/86400000) % 7;
11481         if( Z>n ) Z -= 7;
11482         p->iJD += (n - Z)*86400000;
11483         clearYMD_HMS_TZ(p);
11484         rc = 0;
11485       }
11486       break;
11487     }
11488     case 's': {
11489       /*
11490       **    start of TTTTT
11491       **
11492       ** Move the date backwards to the beginning of the current day,
11493       ** or month or year.
11494       */
11495       if( strncmp(z, "start of ", 9)!=0 ) break;
11496       z += 9;
11497       computeYMD(p);
11498       p->validHMS = 1;
11499       p->h = p->m = 0;
11500       p->s = 0.0;
11501       p->validTZ = 0;
11502       p->validJD = 0;
11503       if( strcmp(z,"month")==0 ){
11504         p->D = 1;
11505         rc = 0;
11506       }else if( strcmp(z,"year")==0 ){
11507         computeYMD(p);
11508         p->M = 1;
11509         p->D = 1;
11510         rc = 0;
11511       }else if( strcmp(z,"day")==0 ){
11512         rc = 0;
11513       }
11514       break;
11515     }
11516     case '+':
11517     case '-':
11518     case '0':
11519     case '1':
11520     case '2':
11521     case '3':
11522     case '4':
11523     case '5':
11524     case '6':
11525     case '7':
11526     case '8':
11527     case '9': {
11528       n = getValue(z, &r);
11529       assert( n>=1 );
11530       if( z[n]==':' ){
11531         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
11532         ** specified number of hours, minutes, seconds, and fractional seconds
11533         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
11534         ** omitted.
11535         */
11536         const char *z2 = z;
11537         DateTime tx;
11538         sqlite3_int64 day;
11539         if( !isdigit(*(u8*)z2) ) z2++;
11540         memset(&tx, 0, sizeof(tx));
11541         if( parseHhMmSs(z2, &tx) ) break;
11542         computeJD(&tx);
11543         tx.iJD -= 43200000;
11544         day = tx.iJD/86400000;
11545         tx.iJD -= day*86400000;
11546         if( z[0]=='-' ) tx.iJD = -tx.iJD;
11547         computeJD(p);
11548         clearYMD_HMS_TZ(p);
11549         p->iJD += tx.iJD;
11550         rc = 0;
11551         break;
11552       }
11553       z += n;
11554       while( isspace(*(u8*)z) ) z++;
11555       n = strlen(z);
11556       if( n>10 || n<3 ) break;
11557       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
11558       computeJD(p);
11559       rc = 0;
11560       if( n==3 && strcmp(z,"day")==0 ){
11561         p->iJD += r*86400000.0 + 0.5;
11562       }else if( n==4 && strcmp(z,"hour")==0 ){
11563         p->iJD += r*(86400000.0/24.0) + 0.5;
11564       }else if( n==6 && strcmp(z,"minute")==0 ){
11565         p->iJD += r*(86400000.0/(24.0*60.0)) + 0.5;
11566       }else if( n==6 && strcmp(z,"second")==0 ){
11567         p->iJD += r*(86400000.0/(24.0*60.0*60.0)) + 0.5;
11568       }else if( n==5 && strcmp(z,"month")==0 ){
11569         int x, y;
11570         computeYMD_HMS(p);
11571         p->M += r;
11572         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
11573         p->Y += x;
11574         p->M -= x*12;
11575         p->validJD = 0;
11576         computeJD(p);
11577         y = r;
11578         if( y!=r ){
11579           p->iJD += (r - y)*30.0*86400000.0 + 0.5;
11580         }
11581       }else if( n==4 && strcmp(z,"year")==0 ){
11582         computeYMD_HMS(p);
11583         p->Y += r;
11584         p->validJD = 0;
11585         computeJD(p);
11586       }else{
11587         rc = 1;
11588       }
11589       clearYMD_HMS_TZ(p);
11590       break;
11591     }
11592     default: {
11593       break;
11594     }
11595   }
11596   return rc;
11597 }
11598
11599 /*
11600 ** Process time function arguments.  argv[0] is a date-time stamp.
11601 ** argv[1] and following are modifiers.  Parse them all and write
11602 ** the resulting time into the DateTime structure p.  Return 0
11603 ** on success and 1 if there are any errors.
11604 **
11605 ** If there are zero parameters (if even argv[0] is undefined)
11606 ** then assume a default value of "now" for argv[0].
11607 */
11608 static int isDate(
11609   sqlite3_context *context, 
11610   int argc, 
11611   sqlite3_value **argv, 
11612   DateTime *p
11613 ){
11614   int i;
11615   const unsigned char *z;
11616   int eType;
11617   memset(p, 0, sizeof(*p));
11618   if( argc==0 ){
11619     setDateTimeToCurrent(context, p);
11620   }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
11621                    || eType==SQLITE_INTEGER ){
11622     p->iJD = sqlite3_value_double(argv[0])*86400000.0 + 0.5;
11623     p->validJD = 1;
11624   }else{
11625     z = sqlite3_value_text(argv[0]);
11626     if( !z || parseDateOrTime(context, (char*)z, p) ){
11627       return 1;
11628     }
11629   }
11630   for(i=1; i<argc; i++){
11631     if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
11632       return 1;
11633     }
11634   }
11635   return 0;
11636 }
11637
11638
11639 /*
11640 ** The following routines implement the various date and time functions
11641 ** of SQLite.
11642 */
11643
11644 /*
11645 **    julianday( TIMESTRING, MOD, MOD, ...)
11646 **
11647 ** Return the julian day number of the date specified in the arguments
11648 */
11649 static void juliandayFunc(
11650   sqlite3_context *context,
11651   int argc,
11652   sqlite3_value **argv
11653 ){
11654   DateTime x;
11655   if( isDate(context, argc, argv, &x)==0 ){
11656     computeJD(&x);
11657     sqlite3_result_double(context, x.iJD/86400000.0);
11658   }
11659 }
11660
11661 /*
11662 **    datetime( TIMESTRING, MOD, MOD, ...)
11663 **
11664 ** Return YYYY-MM-DD HH:MM:SS
11665 */
11666 static void datetimeFunc(
11667   sqlite3_context *context,
11668   int argc,
11669   sqlite3_value **argv
11670 ){
11671   DateTime x;
11672   if( isDate(context, argc, argv, &x)==0 ){
11673     char zBuf[100];
11674     computeYMD_HMS(&x);
11675     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
11676                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
11677     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
11678   }
11679 }
11680
11681 /*
11682 **    time( TIMESTRING, MOD, MOD, ...)
11683 **
11684 ** Return HH:MM:SS
11685 */
11686 static void timeFunc(
11687   sqlite3_context *context,
11688   int argc,
11689   sqlite3_value **argv
11690 ){
11691   DateTime x;
11692   if( isDate(context, argc, argv, &x)==0 ){
11693     char zBuf[100];
11694     computeHMS(&x);
11695     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
11696     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
11697   }
11698 }
11699
11700 /*
11701 **    date( TIMESTRING, MOD, MOD, ...)
11702 **
11703 ** Return YYYY-MM-DD
11704 */
11705 static void dateFunc(
11706   sqlite3_context *context,
11707   int argc,
11708   sqlite3_value **argv
11709 ){
11710   DateTime x;
11711   if( isDate(context, argc, argv, &x)==0 ){
11712     char zBuf[100];
11713     computeYMD(&x);
11714     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
11715     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
11716   }
11717 }
11718
11719 /*
11720 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
11721 **
11722 ** Return a string described by FORMAT.  Conversions as follows:
11723 **
11724 **   %d  day of month
11725 **   %f  ** fractional seconds  SS.SSS
11726 **   %H  hour 00-24
11727 **   %j  day of year 000-366
11728 **   %J  ** Julian day number
11729 **   %m  month 01-12
11730 **   %M  minute 00-59
11731 **   %s  seconds since 1970-01-01
11732 **   %S  seconds 00-59
11733 **   %w  day of week 0-6  sunday==0
11734 **   %W  week of year 00-53
11735 **   %Y  year 0000-9999
11736 **   %%  %
11737 */
11738 static void strftimeFunc(
11739   sqlite3_context *context,
11740   int argc,
11741   sqlite3_value **argv
11742 ){
11743   DateTime x;
11744   u64 n;
11745   int i, j;
11746   char *z;
11747   sqlite3 *db;
11748   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
11749   char zBuf[100];
11750   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
11751   db = sqlite3_context_db_handle(context);
11752   for(i=0, n=1; zFmt[i]; i++, n++){
11753     if( zFmt[i]=='%' ){
11754       switch( zFmt[i+1] ){
11755         case 'd':
11756         case 'H':
11757         case 'm':
11758         case 'M':
11759         case 'S':
11760         case 'W':
11761           n++;
11762           /* fall thru */
11763         case 'w':
11764         case '%':
11765           break;
11766         case 'f':
11767           n += 8;
11768           break;
11769         case 'j':
11770           n += 3;
11771           break;
11772         case 'Y':
11773           n += 8;
11774           break;
11775         case 's':
11776         case 'J':
11777           n += 50;
11778           break;
11779         default:
11780           return;  /* ERROR.  return a NULL */
11781       }
11782       i++;
11783     }
11784   }
11785   if( n<sizeof(zBuf) ){
11786     z = zBuf;
11787   }else if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
11788     sqlite3_result_error_toobig(context);
11789     return;
11790   }else{
11791     z = sqlite3DbMallocRaw(db, n);
11792     if( z==0 ){
11793       sqlite3_result_error_nomem(context);
11794       return;
11795     }
11796   }
11797   computeJD(&x);
11798   computeYMD_HMS(&x);
11799   for(i=j=0; zFmt[i]; i++){
11800     if( zFmt[i]!='%' ){
11801       z[j++] = zFmt[i];
11802     }else{
11803       i++;
11804       switch( zFmt[i] ){
11805         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
11806         case 'f': {
11807           double s = x.s;
11808           if( s>59.999 ) s = 59.999;
11809           sqlite3_snprintf(7, &z[j],"%06.3f", s);
11810           j += strlen(&z[j]);
11811           break;
11812         }
11813         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
11814         case 'W': /* Fall thru */
11815         case 'j': {
11816           int nDay;             /* Number of days since 1st day of year */
11817           DateTime y = x;
11818           y.validJD = 0;
11819           y.M = 1;
11820           y.D = 1;
11821           computeJD(&y);
11822           nDay = (x.iJD - y.iJD)/86400000.0 + 0.5;
11823           if( zFmt[i]=='W' ){
11824             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
11825             wd = ((x.iJD+43200000)/86400000) % 7;
11826             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
11827             j += 2;
11828           }else{
11829             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
11830             j += 3;
11831           }
11832           break;
11833         }
11834         case 'J': {
11835           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
11836           j+=strlen(&z[j]);
11837           break;
11838         }
11839         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
11840         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
11841         case 's': {
11842           sqlite3_snprintf(30,&z[j],"%d",
11843                            (int)(x.iJD/1000.0 - 210866760000.0));
11844           j += strlen(&z[j]);
11845           break;
11846         }
11847         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
11848         case 'w':  z[j++] = (((x.iJD+129600000)/86400000) % 7) + '0'; break;
11849         case 'Y':  sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=strlen(&z[j]);break;
11850         default:   z[j++] = '%'; break;
11851       }
11852     }
11853   }
11854   z[j] = 0;
11855   sqlite3_result_text(context, z, -1,
11856                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
11857 }
11858
11859 /*
11860 ** current_time()
11861 **
11862 ** This function returns the same value as time('now').
11863 */
11864 static void ctimeFunc(
11865   sqlite3_context *context,
11866   int argc,
11867   sqlite3_value **argv
11868 ){
11869   timeFunc(context, 0, 0);
11870 }
11871
11872 /*
11873 ** current_date()
11874 **
11875 ** This function returns the same value as date('now').
11876 */
11877 static void cdateFunc(
11878   sqlite3_context *context,
11879   int argc,
11880   sqlite3_value **argv
11881 ){
11882   dateFunc(context, 0, 0);
11883 }
11884
11885 /*
11886 ** current_timestamp()
11887 **
11888 ** This function returns the same value as datetime('now').
11889 */
11890 static void ctimestampFunc(
11891   sqlite3_context *context,
11892   int argc,
11893   sqlite3_value **argv
11894 ){
11895   datetimeFunc(context, 0, 0);
11896 }
11897 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
11898
11899 #ifdef SQLITE_OMIT_DATETIME_FUNCS
11900 /*
11901 ** If the library is compiled to omit the full-scale date and time
11902 ** handling (to get a smaller binary), the following minimal version
11903 ** of the functions current_time(), current_date() and current_timestamp()
11904 ** are included instead. This is to support column declarations that
11905 ** include "DEFAULT CURRENT_TIME" etc.
11906 **
11907 ** This function uses the C-library functions time(), gmtime()
11908 ** and strftime(). The format string to pass to strftime() is supplied
11909 ** as the user-data for the function.
11910 */
11911 static void currentTimeFunc(
11912   sqlite3_context *context,
11913   int argc,
11914   sqlite3_value **argv
11915 ){
11916   time_t t;
11917   char *zFormat = (char *)sqlite3_user_data(context);
11918   sqlite3 *db;
11919   double rT;
11920   char zBuf[20];
11921
11922   db = sqlite3_context_db_handle(context);
11923   sqlite3OsCurrentTime(db->pVfs, &rT);
11924   t = 86400.0*(rT - 2440587.5) + 0.5;
11925 #ifdef HAVE_GMTIME_R
11926   {
11927     struct tm sNow;
11928     gmtime_r(&t, &sNow);
11929     strftime(zBuf, 20, zFormat, &sNow);
11930   }
11931 #else
11932   {
11933     struct tm *pTm;
11934     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
11935     pTm = gmtime(&t);
11936     strftime(zBuf, 20, zFormat, pTm);
11937     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
11938   }
11939 #endif
11940
11941   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
11942 }
11943 #endif
11944
11945 /*
11946 ** This function registered all of the above C functions as SQL
11947 ** functions.  This should be the only routine in this file with
11948 ** external linkage.
11949 */
11950 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
11951   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
11952 #ifndef SQLITE_OMIT_DATETIME_FUNCS
11953     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
11954     FUNCTION(date,             -1, 0, 0, dateFunc      ),
11955     FUNCTION(time,             -1, 0, 0, timeFunc      ),
11956     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
11957     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
11958     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
11959     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
11960     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
11961 #else
11962     FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
11963     FUNCTION(current_timestamp, 0, "%Y-%m-%d",          0, currentTimeFunc),
11964     FUNCTION(current_date,      0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
11965 #endif
11966   };
11967   int i;
11968   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
11969   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
11970
11971   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
11972     sqlite3FuncDefInsert(pHash, &aFunc[i]);
11973   }
11974 }
11975
11976 /************** End of date.c ************************************************/
11977 /************** Begin file os.c **********************************************/
11978 /*
11979 ** 2005 November 29
11980 **
11981 ** The author disclaims copyright to this source code.  In place of
11982 ** a legal notice, here is a blessing:
11983 **
11984 **    May you do good and not evil.
11985 **    May you find forgiveness for yourself and forgive others.
11986 **    May you share freely, never taking more than you give.
11987 **
11988 ******************************************************************************
11989 **
11990 ** This file contains OS interface code that is common to all
11991 ** architectures.
11992 **
11993 ** $Id: os.c,v 1.122 2008/09/02 17:18:52 danielk1977 Exp $
11994 */
11995 #define _SQLITE_OS_C_ 1
11996 #undef _SQLITE_OS_C_
11997
11998 /*
11999 ** The default SQLite sqlite3_vfs implementations do not allocate
12000 ** memory (actually, os_unix.c allocates a small amount of memory
12001 ** from within OsOpen()), but some third-party implementations may.
12002 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
12003 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
12004 **
12005 ** The following functions are instrumented for malloc() failure 
12006 ** testing:
12007 **
12008 **     sqlite3OsOpen()
12009 **     sqlite3OsRead()
12010 **     sqlite3OsWrite()
12011 **     sqlite3OsSync()
12012 **     sqlite3OsLock()
12013 **
12014 */
12015 #if defined(SQLITE_TEST) && (SQLITE_OS_WIN==0) && 0
12016   #define DO_OS_MALLOC_TEST if (1) {            \
12017     void *pTstAlloc = sqlite3Malloc(10);       \
12018     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;  \
12019     sqlite3_free(pTstAlloc);                    \
12020   }
12021 #else
12022   #define DO_OS_MALLOC_TEST
12023 #endif
12024
12025 /*
12026 ** The following routines are convenience wrappers around methods
12027 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
12028 ** of this would be completely automatic if SQLite were coded using
12029 ** C++ instead of plain old C.
12030 */
12031 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
12032   int rc = SQLITE_OK;
12033   if( pId->pMethods ){
12034     rc = pId->pMethods->xClose(pId);
12035     pId->pMethods = 0;
12036   }
12037   return rc;
12038 }
12039 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
12040   DO_OS_MALLOC_TEST;
12041   return id->pMethods->xRead(id, pBuf, amt, offset);
12042 }
12043 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
12044   DO_OS_MALLOC_TEST;
12045   return id->pMethods->xWrite(id, pBuf, amt, offset);
12046 }
12047 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
12048   return id->pMethods->xTruncate(id, size);
12049 }
12050 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
12051   DO_OS_MALLOC_TEST;
12052   return id->pMethods->xSync(id, flags);
12053 }
12054 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
12055   DO_OS_MALLOC_TEST;
12056   return id->pMethods->xFileSize(id, pSize);
12057 }
12058 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
12059   DO_OS_MALLOC_TEST;
12060   return id->pMethods->xLock(id, lockType);
12061 }
12062 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
12063   return id->pMethods->xUnlock(id, lockType);
12064 }
12065 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
12066   DO_OS_MALLOC_TEST;
12067   return id->pMethods->xCheckReservedLock(id, pResOut);
12068 }
12069 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
12070   return id->pMethods->xFileControl(id, op, pArg);
12071 }
12072 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
12073   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
12074   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
12075 }
12076 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
12077   return id->pMethods->xDeviceCharacteristics(id);
12078 }
12079
12080 /*
12081 ** The next group of routines are convenience wrappers around the
12082 ** VFS methods.
12083 */
12084 SQLITE_PRIVATE int sqlite3OsOpen(
12085   sqlite3_vfs *pVfs, 
12086   const char *zPath, 
12087   sqlite3_file *pFile, 
12088   int flags, 
12089   int *pFlagsOut
12090 ){
12091   DO_OS_MALLOC_TEST;
12092   return pVfs->xOpen(pVfs, zPath, pFile, flags, pFlagsOut);
12093 }
12094 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
12095   return pVfs->xDelete(pVfs, zPath, dirSync);
12096 }
12097 SQLITE_PRIVATE int sqlite3OsAccess(
12098   sqlite3_vfs *pVfs, 
12099   const char *zPath, 
12100   int flags, 
12101   int *pResOut
12102 ){
12103   DO_OS_MALLOC_TEST;
12104   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
12105 }
12106 SQLITE_PRIVATE int sqlite3OsFullPathname(
12107   sqlite3_vfs *pVfs, 
12108   const char *zPath, 
12109   int nPathOut, 
12110   char *zPathOut
12111 ){
12112   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
12113 }
12114 #ifndef SQLITE_OMIT_LOAD_EXTENSION
12115 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
12116   return pVfs->xDlOpen(pVfs, zPath);
12117 }
12118 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
12119   pVfs->xDlError(pVfs, nByte, zBufOut);
12120 }
12121 SQLITE_PRIVATE void *sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
12122   return pVfs->xDlSym(pVfs, pHandle, zSymbol);
12123 }
12124 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
12125   pVfs->xDlClose(pVfs, pHandle);
12126 }
12127 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
12128 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
12129   return pVfs->xRandomness(pVfs, nByte, zBufOut);
12130 }
12131 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
12132   return pVfs->xSleep(pVfs, nMicro);
12133 }
12134 SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
12135   return pVfs->xCurrentTime(pVfs, pTimeOut);
12136 }
12137
12138 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
12139   sqlite3_vfs *pVfs, 
12140   const char *zFile, 
12141   sqlite3_file **ppFile, 
12142   int flags,
12143   int *pOutFlags
12144 ){
12145   int rc = SQLITE_NOMEM;
12146   sqlite3_file *pFile;
12147   pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
12148   if( pFile ){
12149     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
12150     if( rc!=SQLITE_OK ){
12151       sqlite3_free(pFile);
12152     }else{
12153       *ppFile = pFile;
12154     }
12155   }
12156   return rc;
12157 }
12158 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
12159   int rc = SQLITE_OK;
12160   assert( pFile );
12161   rc = sqlite3OsClose(pFile);
12162   sqlite3_free(pFile);
12163   return rc;
12164 }
12165
12166 /*
12167 ** The list of all registered VFS implementations.
12168 */
12169 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
12170 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
12171
12172 /*
12173 ** Locate a VFS by name.  If no name is given, simply return the
12174 ** first VFS on the list.
12175 */
12176 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
12177   sqlite3_vfs *pVfs = 0;
12178 #ifndef SQLITE_MUTEX_NOOP
12179   sqlite3_mutex *mutex;
12180 #endif
12181 #ifndef SQLITE_OMIT_AUTOINIT
12182   int rc = sqlite3_initialize();
12183   if( rc ) return 0;
12184 #endif
12185 #ifndef SQLITE_MUTEX_NOOP
12186   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
12187 #endif
12188   sqlite3_mutex_enter(mutex);
12189   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
12190     if( zVfs==0 ) break;
12191     if( strcmp(zVfs, pVfs->zName)==0 ) break;
12192   }
12193   sqlite3_mutex_leave(mutex);
12194   return pVfs;
12195 }
12196
12197 /*
12198 ** Unlink a VFS from the linked list
12199 */
12200 static void vfsUnlink(sqlite3_vfs *pVfs){
12201   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
12202   if( pVfs==0 ){
12203     /* No-op */
12204   }else if( vfsList==pVfs ){
12205     vfsList = pVfs->pNext;
12206   }else if( vfsList ){
12207     sqlite3_vfs *p = vfsList;
12208     while( p->pNext && p->pNext!=pVfs ){
12209       p = p->pNext;
12210     }
12211     if( p->pNext==pVfs ){
12212       p->pNext = pVfs->pNext;
12213     }
12214   }
12215 }
12216
12217 /*
12218 ** Register a VFS with the system.  It is harmless to register the same
12219 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
12220 ** true.
12221 */
12222 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
12223   sqlite3_mutex *mutex = 0;
12224 #ifndef SQLITE_OMIT_AUTOINIT
12225   int rc = sqlite3_initialize();
12226   if( rc ) return rc;
12227 #endif
12228   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
12229   sqlite3_mutex_enter(mutex);
12230   vfsUnlink(pVfs);
12231   if( makeDflt || vfsList==0 ){
12232     pVfs->pNext = vfsList;
12233     vfsList = pVfs;
12234   }else{
12235     pVfs->pNext = vfsList->pNext;
12236     vfsList->pNext = pVfs;
12237   }
12238   assert(vfsList);
12239   sqlite3_mutex_leave(mutex);
12240   return SQLITE_OK;
12241 }
12242
12243 /*
12244 ** Unregister a VFS so that it is no longer accessible.
12245 */
12246 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
12247 #ifndef SQLITE_MUTEX_NOOP
12248   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
12249 #endif
12250   sqlite3_mutex_enter(mutex);
12251   vfsUnlink(pVfs);
12252   sqlite3_mutex_leave(mutex);
12253   return SQLITE_OK;
12254 }
12255
12256 /************** End of os.c **************************************************/
12257 /************** Begin file fault.c *******************************************/
12258 /*
12259 ** 2008 Jan 22
12260 **
12261 ** The author disclaims copyright to this source code.  In place of
12262 ** a legal notice, here is a blessing:
12263 **
12264 **    May you do good and not evil.
12265 **    May you find forgiveness for yourself and forgive others.
12266 **    May you share freely, never taking more than you give.
12267 **
12268 *************************************************************************
12269 **
12270 ** $Id: fault.c,v 1.11 2008/09/02 00:52:52 drh Exp $
12271 */
12272
12273 /*
12274 ** This file contains code to support the concept of "benign" 
12275 ** malloc failures (when the xMalloc() or xRealloc() method of the
12276 ** sqlite3_mem_methods structure fails to allocate a block of memory
12277 ** and returns 0). 
12278 **
12279 ** Most malloc failures are non-benign. After they occur, SQLite
12280 ** abandons the current operation and returns an error code (usually
12281 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
12282 ** fatal. For example, if a malloc fails while resizing a hash table, this 
12283 ** is completely recoverable simply by not carrying out the resize. The 
12284 ** hash table will continue to function normally.  So a malloc failure 
12285 ** during a hash table resize is a benign fault.
12286 */
12287
12288
12289 #ifndef SQLITE_OMIT_BUILTIN_TEST
12290
12291 /*
12292 ** Global variables.
12293 */
12294 typedef struct BenignMallocHooks BenignMallocHooks;
12295 static SQLITE_WSD struct BenignMallocHooks {
12296   void (*xBenignBegin)(void);
12297   void (*xBenignEnd)(void);
12298 } sqlite3Hooks = { 0, 0 };
12299
12300 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
12301 ** structure.  If writable static data is unsupported on the target,
12302 ** we have to locate the state vector at run-time.  In the more common
12303 ** case where writable static data is supported, wsdHooks can refer directly
12304 ** to the "sqlite3Hooks" state vector declared above.
12305 */
12306 #ifdef SQLITE_OMIT_WSD
12307 # define wsdHooksInit \
12308   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
12309 # define wsdHooks x[0]
12310 #else
12311 # define wsdHooksInit
12312 # define wsdHooks sqlite3Hooks
12313 #endif
12314
12315
12316 /*
12317 ** Register hooks to call when sqlite3BeginBenignMalloc() and
12318 ** sqlite3EndBenignMalloc() are called, respectively.
12319 */
12320 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
12321   void (*xBenignBegin)(void),
12322   void (*xBenignEnd)(void)
12323 ){
12324   wsdHooksInit;
12325   wsdHooks.xBenignBegin = xBenignBegin;
12326   wsdHooks.xBenignEnd = xBenignEnd;
12327 }
12328
12329 /*
12330 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
12331 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
12332 ** indicates that subsequent malloc failures are non-benign.
12333 */
12334 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
12335   wsdHooksInit;
12336   if( wsdHooks.xBenignBegin ){
12337     wsdHooks.xBenignBegin();
12338   }
12339 }
12340 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
12341   wsdHooksInit;
12342   if( wsdHooks.xBenignEnd ){
12343     wsdHooks.xBenignEnd();
12344   }
12345 }
12346
12347 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
12348
12349 /************** End of fault.c ***********************************************/
12350 /************** Begin file mem1.c ********************************************/
12351 /*
12352 ** 2007 August 14
12353 **
12354 ** The author disclaims copyright to this source code.  In place of
12355 ** a legal notice, here is a blessing:
12356 **
12357 **    May you do good and not evil.
12358 **    May you find forgiveness for yourself and forgive others.
12359 **    May you share freely, never taking more than you give.
12360 **
12361 *************************************************************************
12362 **
12363 ** This file contains low-level memory allocation drivers for when
12364 ** SQLite will use the standard C-library malloc/realloc/free interface
12365 ** to obtain the memory it needs.
12366 **
12367 ** This file contains implementations of the low-level memory allocation
12368 ** routines specified in the sqlite3_mem_methods object.
12369 **
12370 ** $Id: mem1.c,v 1.26 2008/09/01 18:34:20 danielk1977 Exp $
12371 */
12372
12373 /*
12374 ** This version of the memory allocator is the default.  It is
12375 ** used when no other memory allocator is specified using compile-time
12376 ** macros.
12377 */
12378 #ifdef SQLITE_SYSTEM_MALLOC
12379
12380 /*
12381 ** Like malloc(), but remember the size of the allocation
12382 ** so that we can find it later using sqlite3MemSize().
12383 **
12384 ** For this low-level routine, we are guaranteed that nByte>0 because
12385 ** cases of nByte<=0 will be intercepted and dealt with by higher level
12386 ** routines.
12387 */
12388 static void *sqlite3MemMalloc(int nByte){
12389   sqlite3_int64 *p;
12390   assert( nByte>0 );
12391   nByte = (nByte+7)&~7;
12392   p = malloc( nByte+8 );
12393   if( p ){
12394     p[0] = nByte;
12395     p++;
12396   }
12397   return (void *)p;
12398 }
12399
12400 /*
12401 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
12402 ** or sqlite3MemRealloc().
12403 **
12404 ** For this low-level routine, we already know that pPrior!=0 since
12405 ** cases where pPrior==0 will have been intecepted and dealt with
12406 ** by higher-level routines.
12407 */
12408 static void sqlite3MemFree(void *pPrior){
12409   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
12410   assert( pPrior!=0 );
12411   p--;
12412   free(p);
12413 }
12414
12415 /*
12416 ** Like realloc().  Resize an allocation previously obtained from
12417 ** sqlite3MemMalloc().
12418 **
12419 ** For this low-level interface, we know that pPrior!=0.  Cases where
12420 ** pPrior==0 while have been intercepted by higher-level routine and
12421 ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
12422 ** cases where nByte<=0 will have been intercepted by higher-level
12423 ** routines and redirected to xFree.
12424 */
12425 static void *sqlite3MemRealloc(void *pPrior, int nByte){
12426   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
12427   assert( pPrior!=0 && nByte>0 );
12428   nByte = (nByte+7)&~7;
12429   p = (sqlite3_int64*)pPrior;
12430   p--;
12431   p = realloc(p, nByte+8 );
12432   if( p ){
12433     p[0] = nByte;
12434     p++;
12435   }
12436   return (void*)p;
12437 }
12438
12439 /*
12440 ** Report the allocated size of a prior return from xMalloc()
12441 ** or xRealloc().
12442 */
12443 static int sqlite3MemSize(void *pPrior){
12444   sqlite3_int64 *p;
12445   if( pPrior==0 ) return 0;
12446   p = (sqlite3_int64*)pPrior;
12447   p--;
12448   return p[0];
12449 }
12450
12451 /*
12452 ** Round up a request size to the next valid allocation size.
12453 */
12454 static int sqlite3MemRoundup(int n){
12455   return (n+7) & ~7;
12456 }
12457
12458 /*
12459 ** Initialize this module.
12460 */
12461 static int sqlite3MemInit(void *NotUsed){
12462   return SQLITE_OK;
12463 }
12464
12465 /*
12466 ** Deinitialize this module.
12467 */
12468 static void sqlite3MemShutdown(void *NotUsed){
12469   return;
12470 }
12471
12472 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetDefault(void){
12473   static const sqlite3_mem_methods defaultMethods = {
12474      sqlite3MemMalloc,
12475      sqlite3MemFree,
12476      sqlite3MemRealloc,
12477      sqlite3MemSize,
12478      sqlite3MemRoundup,
12479      sqlite3MemInit,
12480      sqlite3MemShutdown,
12481      0
12482   };
12483   return &defaultMethods;
12484 }
12485
12486 /*
12487 ** This routine is the only routine in this file with external linkage.
12488 **
12489 ** Populate the low-level memory allocation function pointers in
12490 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
12491 */
12492 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
12493   sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetDefault());
12494 }
12495
12496 #endif /* SQLITE_SYSTEM_MALLOC */
12497
12498 /************** End of mem1.c ************************************************/
12499 /************** Begin file mem2.c ********************************************/
12500 /*
12501 ** 2007 August 15
12502 **
12503 ** The author disclaims copyright to this source code.  In place of
12504 ** a legal notice, here is a blessing:
12505 **
12506 **    May you do good and not evil.
12507 **    May you find forgiveness for yourself and forgive others.
12508 **    May you share freely, never taking more than you give.
12509 **
12510 *************************************************************************
12511 **
12512 ** This file contains low-level memory allocation drivers for when
12513 ** SQLite will use the standard C-library malloc/realloc/free interface
12514 ** to obtain the memory it needs while adding lots of additional debugging
12515 ** information to each allocation in order to help detect and fix memory
12516 ** leaks and memory usage errors.
12517 **
12518 ** This file contains implementations of the low-level memory allocation
12519 ** routines specified in the sqlite3_mem_methods object.
12520 **
12521 ** $Id: mem2.c,v 1.39 2008/09/01 18:34:20 danielk1977 Exp $
12522 */
12523
12524 /*
12525 ** This version of the memory allocator is used only if the
12526 ** SQLITE_MEMDEBUG macro is defined
12527 */
12528 #ifdef SQLITE_MEMDEBUG
12529
12530 /*
12531 ** The backtrace functionality is only available with GLIBC
12532 */
12533 #ifdef __GLIBC__
12534   extern int backtrace(void**,int);
12535   extern void backtrace_symbols_fd(void*const*,int,int);
12536 #else
12537 # define backtrace(A,B) 1
12538 # define backtrace_symbols_fd(A,B,C)
12539 #endif
12540
12541 /*
12542 ** Each memory allocation looks like this:
12543 **
12544 **  ------------------------------------------------------------------------
12545 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
12546 **  ------------------------------------------------------------------------
12547 **
12548 ** The application code sees only a pointer to the allocation.  We have
12549 ** to back up from the allocation pointer to find the MemBlockHdr.  The
12550 ** MemBlockHdr tells us the size of the allocation and the number of
12551 ** backtrace pointers.  There is also a guard word at the end of the
12552 ** MemBlockHdr.
12553 */
12554 struct MemBlockHdr {
12555   i64 iSize;                          /* Size of this allocation */
12556   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
12557   char nBacktrace;                    /* Number of backtraces on this alloc */
12558   char nBacktraceSlots;               /* Available backtrace slots */
12559   short nTitle;                       /* Bytes of title; includes '\0' */
12560   int iForeGuard;                     /* Guard word for sanity */
12561 };
12562
12563 /*
12564 ** Guard words
12565 */
12566 #define FOREGUARD 0x80F5E153
12567 #define REARGUARD 0xE4676B53
12568
12569 /*
12570 ** Number of malloc size increments to track.
12571 */
12572 #define NCSIZE  1000
12573
12574 /*
12575 ** All of the static variables used by this module are collected
12576 ** into a single structure named "mem".  This is to keep the
12577 ** static variables organized and to reduce namespace pollution
12578 ** when this module is combined with other in the amalgamation.
12579 */
12580 static struct {
12581   
12582   /*
12583   ** Mutex to control access to the memory allocation subsystem.
12584   */
12585   sqlite3_mutex *mutex;
12586
12587   /*
12588   ** Head and tail of a linked list of all outstanding allocations
12589   */
12590   struct MemBlockHdr *pFirst;
12591   struct MemBlockHdr *pLast;
12592   
12593   /*
12594   ** The number of levels of backtrace to save in new allocations.
12595   */
12596   int nBacktrace;
12597   void (*xBacktrace)(int, int, void **);
12598
12599   /*
12600   ** Title text to insert in front of each block
12601   */
12602   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
12603   char zTitle[100];  /* The title text */
12604
12605   /* 
12606   ** sqlite3MallocDisallow() increments the following counter.
12607   ** sqlite3MallocAllow() decrements it.
12608   */
12609   int disallow; /* Do not allow memory allocation */
12610
12611   /*
12612   ** Gather statistics on the sizes of memory allocations.
12613   ** nAlloc[i] is the number of allocation attempts of i*8
12614   ** bytes.  i==NCSIZE is the number of allocation attempts for
12615   ** sizes more than NCSIZE*8 bytes.
12616   */
12617   int nAlloc[NCSIZE];      /* Total number of allocations */
12618   int nCurrent[NCSIZE];    /* Current number of allocations */
12619   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
12620
12621 } mem;
12622
12623
12624 /*
12625 ** Adjust memory usage statistics
12626 */
12627 static void adjustStats(int iSize, int increment){
12628   int i = ((iSize+7)&~7)/8;
12629   if( i>NCSIZE-1 ){
12630     i = NCSIZE - 1;
12631   }
12632   if( increment>0 ){
12633     mem.nAlloc[i]++;
12634     mem.nCurrent[i]++;
12635     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
12636       mem.mxCurrent[i] = mem.nCurrent[i];
12637     }
12638   }else{
12639     mem.nCurrent[i]--;
12640     assert( mem.nCurrent[i]>=0 );
12641   }
12642 }
12643
12644 /*
12645 ** Given an allocation, find the MemBlockHdr for that allocation.
12646 **
12647 ** This routine checks the guards at either end of the allocation and
12648 ** if they are incorrect it asserts.
12649 */
12650 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
12651   struct MemBlockHdr *p;
12652   int *pInt;
12653   u8 *pU8;
12654   int nReserve;
12655
12656   p = (struct MemBlockHdr*)pAllocation;
12657   p--;
12658   assert( p->iForeGuard==FOREGUARD );
12659   nReserve = (p->iSize+7)&~7;
12660   pInt = (int*)pAllocation;
12661   pU8 = (u8*)pAllocation;
12662   assert( pInt[nReserve/sizeof(int)]==REARGUARD );
12663   assert( (nReserve-0)<=p->iSize || pU8[nReserve-1]==0x65 );
12664   assert( (nReserve-1)<=p->iSize || pU8[nReserve-2]==0x65 );
12665   assert( (nReserve-2)<=p->iSize || pU8[nReserve-3]==0x65 );
12666   return p;
12667 }
12668
12669 /*
12670 ** Return the number of bytes currently allocated at address p.
12671 */
12672 static int sqlite3MemSize(void *p){
12673   struct MemBlockHdr *pHdr;
12674   if( !p ){
12675     return 0;
12676   }
12677   pHdr = sqlite3MemsysGetHeader(p);
12678   return pHdr->iSize;
12679 }
12680
12681 /*
12682 ** Initialize the memory allocation subsystem.
12683 */
12684 static int sqlite3MemInit(void *NotUsed){
12685   if( !sqlite3GlobalConfig.bMemstat ){
12686     /* If memory status is enabled, then the malloc.c wrapper will already
12687     ** hold the STATIC_MEM mutex when the routines here are invoked. */
12688     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
12689   }
12690   return SQLITE_OK;
12691 }
12692
12693 /*
12694 ** Deinitialize the memory allocation subsystem.
12695 */
12696 static void sqlite3MemShutdown(void *NotUsed){
12697   mem.mutex = 0;
12698 }
12699
12700 /*
12701 ** Round up a request size to the next valid allocation size.
12702 */
12703 static int sqlite3MemRoundup(int n){
12704   return (n+7) & ~7;
12705 }
12706
12707 /*
12708 ** Allocate nByte bytes of memory.
12709 */
12710 static void *sqlite3MemMalloc(int nByte){
12711   struct MemBlockHdr *pHdr;
12712   void **pBt;
12713   char *z;
12714   int *pInt;
12715   void *p = 0;
12716   int totalSize;
12717   int nReserve;
12718   sqlite3_mutex_enter(mem.mutex);
12719   assert( mem.disallow==0 );
12720   nReserve = (nByte+7)&~7;
12721   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
12722                mem.nBacktrace*sizeof(void*) + mem.nTitle;
12723   p = malloc(totalSize);
12724   if( p ){
12725     z = p;
12726     pBt = (void**)&z[mem.nTitle];
12727     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
12728     pHdr->pNext = 0;
12729     pHdr->pPrev = mem.pLast;
12730     if( mem.pLast ){
12731       mem.pLast->pNext = pHdr;
12732     }else{
12733       mem.pFirst = pHdr;
12734     }
12735     mem.pLast = pHdr;
12736     pHdr->iForeGuard = FOREGUARD;
12737     pHdr->nBacktraceSlots = mem.nBacktrace;
12738     pHdr->nTitle = mem.nTitle;
12739     if( mem.nBacktrace ){
12740       void *aAddr[40];
12741       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
12742       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
12743       if( mem.xBacktrace ){
12744         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
12745       }
12746     }else{
12747       pHdr->nBacktrace = 0;
12748     }
12749     if( mem.nTitle ){
12750       memcpy(z, mem.zTitle, mem.nTitle);
12751     }
12752     pHdr->iSize = nByte;
12753     adjustStats(nByte, +1);
12754     pInt = (int*)&pHdr[1];
12755     pInt[nReserve/sizeof(int)] = REARGUARD;
12756     memset(pInt, 0x65, nReserve);
12757     p = (void*)pInt;
12758   }
12759   sqlite3_mutex_leave(mem.mutex);
12760   return p; 
12761 }
12762
12763 /*
12764 ** Free memory.
12765 */
12766 static void sqlite3MemFree(void *pPrior){
12767   struct MemBlockHdr *pHdr;
12768   void **pBt;
12769   char *z;
12770   assert( sqlite3GlobalConfig.bMemstat || mem.mutex!=0 );
12771   pHdr = sqlite3MemsysGetHeader(pPrior);
12772   pBt = (void**)pHdr;
12773   pBt -= pHdr->nBacktraceSlots;
12774   sqlite3_mutex_enter(mem.mutex);
12775   if( pHdr->pPrev ){
12776     assert( pHdr->pPrev->pNext==pHdr );
12777     pHdr->pPrev->pNext = pHdr->pNext;
12778   }else{
12779     assert( mem.pFirst==pHdr );
12780     mem.pFirst = pHdr->pNext;
12781   }
12782   if( pHdr->pNext ){
12783     assert( pHdr->pNext->pPrev==pHdr );
12784     pHdr->pNext->pPrev = pHdr->pPrev;
12785   }else{
12786     assert( mem.pLast==pHdr );
12787     mem.pLast = pHdr->pPrev;
12788   }
12789   z = (char*)pBt;
12790   z -= pHdr->nTitle;
12791   adjustStats(pHdr->iSize, -1);
12792   memset(z, 0x2b, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
12793                   pHdr->iSize + sizeof(int) + pHdr->nTitle);
12794   free(z);
12795   sqlite3_mutex_leave(mem.mutex);  
12796 }
12797
12798 /*
12799 ** Change the size of an existing memory allocation.
12800 **
12801 ** For this debugging implementation, we *always* make a copy of the
12802 ** allocation into a new place in memory.  In this way, if the 
12803 ** higher level code is using pointer to the old allocation, it is 
12804 ** much more likely to break and we are much more liking to find
12805 ** the error.
12806 */
12807 static void *sqlite3MemRealloc(void *pPrior, int nByte){
12808   struct MemBlockHdr *pOldHdr;
12809   void *pNew;
12810   assert( mem.disallow==0 );
12811   pOldHdr = sqlite3MemsysGetHeader(pPrior);
12812   pNew = sqlite3MemMalloc(nByte);
12813   if( pNew ){
12814     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
12815     if( nByte>pOldHdr->iSize ){
12816       memset(&((char*)pNew)[pOldHdr->iSize], 0x2b, nByte - pOldHdr->iSize);
12817     }
12818     sqlite3MemFree(pPrior);
12819   }
12820   return pNew;
12821 }
12822
12823
12824 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetDefault(void){
12825   static const sqlite3_mem_methods defaultMethods = {
12826      sqlite3MemMalloc,
12827      sqlite3MemFree,
12828      sqlite3MemRealloc,
12829      sqlite3MemSize,
12830      sqlite3MemRoundup,
12831      sqlite3MemInit,
12832      sqlite3MemShutdown,
12833      0
12834   };
12835   return &defaultMethods;
12836 }
12837
12838 /*
12839 ** Populate the low-level memory allocation function pointers in
12840 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
12841 */
12842 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
12843   sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetDefault());
12844 }
12845
12846 /*
12847 ** Set the number of backtrace levels kept for each allocation.
12848 ** A value of zero turns off backtracing.  The number is always rounded
12849 ** up to a multiple of 2.
12850 */
12851 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
12852   if( depth<0 ){ depth = 0; }
12853   if( depth>20 ){ depth = 20; }
12854   depth = (depth+1)&0xfe;
12855   mem.nBacktrace = depth;
12856 }
12857
12858 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
12859   mem.xBacktrace = xBacktrace;
12860 }
12861
12862 /*
12863 ** Set the title string for subsequent allocations.
12864 */
12865 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
12866   int n = strlen(zTitle) + 1;
12867   sqlite3_mutex_enter(mem.mutex);
12868   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
12869   memcpy(mem.zTitle, zTitle, n);
12870   mem.zTitle[n] = 0;
12871   mem.nTitle = (n+7)&~7;
12872   sqlite3_mutex_leave(mem.mutex);
12873 }
12874
12875 SQLITE_PRIVATE void sqlite3MemdebugSync(){
12876   struct MemBlockHdr *pHdr;
12877   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
12878     void **pBt = (void**)pHdr;
12879     pBt -= pHdr->nBacktraceSlots;
12880     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
12881   }
12882 }
12883
12884 /*
12885 ** Open the file indicated and write a log of all unfreed memory 
12886 ** allocations into that log.
12887 */
12888 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
12889   FILE *out;
12890   struct MemBlockHdr *pHdr;
12891   void **pBt;
12892   int i;
12893   out = fopen(zFilename, "w");
12894   if( out==0 ){
12895     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
12896                     zFilename);
12897     return;
12898   }
12899   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
12900     char *z = (char*)pHdr;
12901     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
12902     fprintf(out, "**** %lld bytes at %p from %s ****\n", 
12903             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
12904     if( pHdr->nBacktrace ){
12905       fflush(out);
12906       pBt = (void**)pHdr;
12907       pBt -= pHdr->nBacktraceSlots;
12908       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
12909       fprintf(out, "\n");
12910     }
12911   }
12912   fprintf(out, "COUNTS:\n");
12913   for(i=0; i<NCSIZE-1; i++){
12914     if( mem.nAlloc[i] ){
12915       fprintf(out, "   %5d: %10d %10d %10d\n", 
12916             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
12917     }
12918   }
12919   if( mem.nAlloc[NCSIZE-1] ){
12920     fprintf(out, "   %5d: %10d %10d %10d\n",
12921              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
12922              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
12923   }
12924   fclose(out);
12925 }
12926
12927 /*
12928 ** Return the number of times sqlite3MemMalloc() has been called.
12929 */
12930 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
12931   int i;
12932   int nTotal = 0;
12933   for(i=0; i<NCSIZE; i++){
12934     nTotal += mem.nAlloc[i];
12935   }
12936   return nTotal;
12937 }
12938
12939
12940 #endif /* SQLITE_MEMDEBUG */
12941
12942 /************** End of mem2.c ************************************************/
12943 /************** Begin file mem3.c ********************************************/
12944 /*
12945 ** 2007 October 14
12946 **
12947 ** The author disclaims copyright to this source code.  In place of
12948 ** a legal notice, here is a blessing:
12949 **
12950 **    May you do good and not evil.
12951 **    May you find forgiveness for yourself and forgive others.
12952 **    May you share freely, never taking more than you give.
12953 **
12954 *************************************************************************
12955 ** This file contains the C functions that implement a memory
12956 ** allocation subsystem for use by SQLite. 
12957 **
12958 ** This version of the memory allocation subsystem omits all
12959 ** use of malloc(). The SQLite user supplies a block of memory
12960 ** before calling sqlite3_initialize() from which allocations
12961 ** are made and returned by the xMalloc() and xRealloc() 
12962 ** implementations. Once sqlite3_initialize() has been called,
12963 ** the amount of memory available to SQLite is fixed and cannot
12964 ** be changed.
12965 **
12966 ** This version of the memory allocation subsystem is included
12967 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
12968 **
12969 ** $Id: mem3.c,v 1.23 2008/09/02 17:52:52 danielk1977 Exp $
12970 */
12971
12972 /*
12973 ** This version of the memory allocator is only built into the library
12974 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
12975 ** mean that the library will use a memory-pool by default, just that
12976 ** it is available. The mempool allocator is activated by calling
12977 ** sqlite3_config().
12978 */
12979 #ifdef SQLITE_ENABLE_MEMSYS3
12980
12981 /*
12982 ** Maximum size (in Mem3Blocks) of a "small" chunk.
12983 */
12984 #define MX_SMALL 10
12985
12986
12987 /*
12988 ** Number of freelist hash slots
12989 */
12990 #define N_HASH  61
12991
12992 /*
12993 ** A memory allocation (also called a "chunk") consists of two or 
12994 ** more blocks where each block is 8 bytes.  The first 8 bytes are 
12995 ** a header that is not returned to the user.
12996 **
12997 ** A chunk is two or more blocks that is either checked out or
12998 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
12999 ** size of the allocation in blocks if the allocation is free.
13000 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
13001 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
13002 ** is true if the previous chunk is checked out and false if the
13003 ** previous chunk is free.  The u.hdr.prevSize field is the size of
13004 ** the previous chunk in blocks if the previous chunk is on the
13005 ** freelist. If the previous chunk is checked out, then
13006 ** u.hdr.prevSize can be part of the data for that chunk and should
13007 ** not be read or written.
13008 **
13009 ** We often identify a chunk by its index in mem3.aPool[].  When
13010 ** this is done, the chunk index refers to the second block of
13011 ** the chunk.  In this way, the first chunk has an index of 1.
13012 ** A chunk index of 0 means "no such chunk" and is the equivalent
13013 ** of a NULL pointer.
13014 **
13015 ** The second block of free chunks is of the form u.list.  The
13016 ** two fields form a double-linked list of chunks of related sizes.
13017 ** Pointers to the head of the list are stored in mem3.aiSmall[] 
13018 ** for smaller chunks and mem3.aiHash[] for larger chunks.
13019 **
13020 ** The second block of a chunk is user data if the chunk is checked 
13021 ** out.  If a chunk is checked out, the user data may extend into
13022 ** the u.hdr.prevSize value of the following chunk.
13023 */
13024 typedef struct Mem3Block Mem3Block;
13025 struct Mem3Block {
13026   union {
13027     struct {
13028       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
13029       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
13030     } hdr;
13031     struct {
13032       u32 next;       /* Index in mem3.aPool[] of next free chunk */
13033       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
13034     } list;
13035   } u;
13036 };
13037
13038 /*
13039 ** All of the static variables used by this module are collected
13040 ** into a single structure named "mem3".  This is to keep the
13041 ** static variables organized and to reduce namespace pollution
13042 ** when this module is combined with other in the amalgamation.
13043 */
13044 static SQLITE_WSD struct Mem3Global {
13045   /*
13046   ** Memory available for allocation. nPool is the size of the array
13047   ** (in Mem3Blocks) pointed to by aPool less 2.
13048   */
13049   u32 nPool;
13050   Mem3Block *aPool;
13051
13052   /*
13053   ** True if we are evaluating an out-of-memory callback.
13054   */
13055   int alarmBusy;
13056   
13057   /*
13058   ** Mutex to control access to the memory allocation subsystem.
13059   */
13060   sqlite3_mutex *mutex;
13061   
13062   /*
13063   ** The minimum amount of free space that we have seen.
13064   */
13065   u32 mnMaster;
13066
13067   /*
13068   ** iMaster is the index of the master chunk.  Most new allocations
13069   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
13070   ** of the current master.  iMaster is 0 if there is not master chunk.
13071   ** The master chunk is not in either the aiHash[] or aiSmall[].
13072   */
13073   u32 iMaster;
13074   u32 szMaster;
13075
13076   /*
13077   ** Array of lists of free blocks according to the block size 
13078   ** for smaller chunks, or a hash on the block size for larger
13079   ** chunks.
13080   */
13081   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
13082   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
13083 } mem3 = { 97535575 };
13084
13085 #define mem3 GLOBAL(struct Mem3Global, mem3)
13086
13087 /*
13088 ** Unlink the chunk at mem3.aPool[i] from list it is currently
13089 ** on.  *pRoot is the list that i is a member of.
13090 */
13091 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
13092   u32 next = mem3.aPool[i].u.list.next;
13093   u32 prev = mem3.aPool[i].u.list.prev;
13094   assert( sqlite3_mutex_held(mem3.mutex) );
13095   if( prev==0 ){
13096     *pRoot = next;
13097   }else{
13098     mem3.aPool[prev].u.list.next = next;
13099   }
13100   if( next ){
13101     mem3.aPool[next].u.list.prev = prev;
13102   }
13103   mem3.aPool[i].u.list.next = 0;
13104   mem3.aPool[i].u.list.prev = 0;
13105 }
13106
13107 /*
13108 ** Unlink the chunk at index i from 
13109 ** whatever list is currently a member of.
13110 */
13111 static void memsys3Unlink(u32 i){
13112   u32 size, hash;
13113   assert( sqlite3_mutex_held(mem3.mutex) );
13114   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
13115   assert( i>=1 );
13116   size = mem3.aPool[i-1].u.hdr.size4x/4;
13117   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
13118   assert( size>=2 );
13119   if( size <= MX_SMALL ){
13120     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
13121   }else{
13122     hash = size % N_HASH;
13123     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
13124   }
13125 }
13126
13127 /*
13128 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
13129 ** at *pRoot.
13130 */
13131 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
13132   assert( sqlite3_mutex_held(mem3.mutex) );
13133   mem3.aPool[i].u.list.next = *pRoot;
13134   mem3.aPool[i].u.list.prev = 0;
13135   if( *pRoot ){
13136     mem3.aPool[*pRoot].u.list.prev = i;
13137   }
13138   *pRoot = i;
13139 }
13140
13141 /*
13142 ** Link the chunk at index i into either the appropriate
13143 ** small chunk list, or into the large chunk hash table.
13144 */
13145 static void memsys3Link(u32 i){
13146   u32 size, hash;
13147   assert( sqlite3_mutex_held(mem3.mutex) );
13148   assert( i>=1 );
13149   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
13150   size = mem3.aPool[i-1].u.hdr.size4x/4;
13151   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
13152   assert( size>=2 );
13153   if( size <= MX_SMALL ){
13154     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
13155   }else{
13156     hash = size % N_HASH;
13157     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
13158   }
13159 }
13160
13161 /*
13162 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
13163 ** will already be held (obtained by code in malloc.c) if
13164 ** sqlite3GlobalConfig.bMemStat is true.
13165 */
13166 static void memsys3Enter(void){
13167   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
13168     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
13169   }
13170   sqlite3_mutex_enter(mem3.mutex);
13171 }
13172 static void memsys3Leave(void){
13173   sqlite3_mutex_leave(mem3.mutex);
13174 }
13175
13176 /*
13177 ** Called when we are unable to satisfy an allocation of nBytes.
13178 */
13179 static void memsys3OutOfMemory(int nByte){
13180   if( !mem3.alarmBusy ){
13181     mem3.alarmBusy = 1;
13182     assert( sqlite3_mutex_held(mem3.mutex) );
13183     sqlite3_mutex_leave(mem3.mutex);
13184     sqlite3_release_memory(nByte);
13185     sqlite3_mutex_enter(mem3.mutex);
13186     mem3.alarmBusy = 0;
13187   }
13188 }
13189
13190
13191 /*
13192 ** Chunk i is a free chunk that has been unlinked.  Adjust its 
13193 ** size parameters for check-out and return a pointer to the 
13194 ** user portion of the chunk.
13195 */
13196 static void *memsys3Checkout(u32 i, int nBlock){
13197   u32 x;
13198   assert( sqlite3_mutex_held(mem3.mutex) );
13199   assert( i>=1 );
13200   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
13201   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
13202   x = mem3.aPool[i-1].u.hdr.size4x;
13203   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
13204   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
13205   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
13206   return &mem3.aPool[i];
13207 }
13208
13209 /*
13210 ** Carve a piece off of the end of the mem3.iMaster free chunk.
13211 ** Return a pointer to the new allocation.  Or, if the master chunk
13212 ** is not large enough, return 0.
13213 */
13214 static void *memsys3FromMaster(int nBlock){
13215   assert( sqlite3_mutex_held(mem3.mutex) );
13216   assert( mem3.szMaster>=nBlock );
13217   if( nBlock>=mem3.szMaster-1 ){
13218     /* Use the entire master */
13219     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
13220     mem3.iMaster = 0;
13221     mem3.szMaster = 0;
13222     mem3.mnMaster = 0;
13223     return p;
13224   }else{
13225     /* Split the master block.  Return the tail. */
13226     u32 newi, x;
13227     newi = mem3.iMaster + mem3.szMaster - nBlock;
13228     assert( newi > mem3.iMaster+1 );
13229     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
13230     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
13231     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
13232     mem3.szMaster -= nBlock;
13233     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
13234     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
13235     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
13236     if( mem3.szMaster < mem3.mnMaster ){
13237       mem3.mnMaster = mem3.szMaster;
13238     }
13239     return (void*)&mem3.aPool[newi];
13240   }
13241 }
13242
13243 /*
13244 ** *pRoot is the head of a list of free chunks of the same size
13245 ** or same size hash.  In other words, *pRoot is an entry in either
13246 ** mem3.aiSmall[] or mem3.aiHash[].  
13247 **
13248 ** This routine examines all entries on the given list and tries
13249 ** to coalesce each entries with adjacent free chunks.  
13250 **
13251 ** If it sees a chunk that is larger than mem3.iMaster, it replaces 
13252 ** the current mem3.iMaster with the new larger chunk.  In order for
13253 ** this mem3.iMaster replacement to work, the master chunk must be
13254 ** linked into the hash tables.  That is not the normal state of
13255 ** affairs, of course.  The calling routine must link the master
13256 ** chunk before invoking this routine, then must unlink the (possibly
13257 ** changed) master chunk once this routine has finished.
13258 */
13259 static void memsys3Merge(u32 *pRoot){
13260   u32 iNext, prev, size, i, x;
13261
13262   assert( sqlite3_mutex_held(mem3.mutex) );
13263   for(i=*pRoot; i>0; i=iNext){
13264     iNext = mem3.aPool[i].u.list.next;
13265     size = mem3.aPool[i-1].u.hdr.size4x;
13266     assert( (size&1)==0 );
13267     if( (size&2)==0 ){
13268       memsys3UnlinkFromList(i, pRoot);
13269       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
13270       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
13271       if( prev==iNext ){
13272         iNext = mem3.aPool[prev].u.list.next;
13273       }
13274       memsys3Unlink(prev);
13275       size = i + size/4 - prev;
13276       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
13277       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
13278       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
13279       memsys3Link(prev);
13280       i = prev;
13281     }else{
13282       size /= 4;
13283     }
13284     if( size>mem3.szMaster ){
13285       mem3.iMaster = i;
13286       mem3.szMaster = size;
13287     }
13288   }
13289 }
13290
13291 /*
13292 ** Return a block of memory of at least nBytes in size.
13293 ** Return NULL if unable.
13294 **
13295 ** This function assumes that the necessary mutexes, if any, are
13296 ** already held by the caller. Hence "Unsafe".
13297 */
13298 static void *memsys3MallocUnsafe(int nByte){
13299   u32 i;
13300   int nBlock;
13301   int toFree;
13302
13303   assert( sqlite3_mutex_held(mem3.mutex) );
13304   assert( sizeof(Mem3Block)==8 );
13305   if( nByte<=12 ){
13306     nBlock = 2;
13307   }else{
13308     nBlock = (nByte + 11)/8;
13309   }
13310   assert( nBlock>=2 );
13311
13312   /* STEP 1:
13313   ** Look for an entry of the correct size in either the small
13314   ** chunk table or in the large chunk hash table.  This is
13315   ** successful most of the time (about 9 times out of 10).
13316   */
13317   if( nBlock <= MX_SMALL ){
13318     i = mem3.aiSmall[nBlock-2];
13319     if( i>0 ){
13320       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
13321       return memsys3Checkout(i, nBlock);
13322     }
13323   }else{
13324     int hash = nBlock % N_HASH;
13325     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
13326       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
13327         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
13328         return memsys3Checkout(i, nBlock);
13329       }
13330     }
13331   }
13332
13333   /* STEP 2:
13334   ** Try to satisfy the allocation by carving a piece off of the end
13335   ** of the master chunk.  This step usually works if step 1 fails.
13336   */
13337   if( mem3.szMaster>=nBlock ){
13338     return memsys3FromMaster(nBlock);
13339   }
13340
13341
13342   /* STEP 3:  
13343   ** Loop through the entire memory pool.  Coalesce adjacent free
13344   ** chunks.  Recompute the master chunk as the largest free chunk.
13345   ** Then try again to satisfy the allocation by carving a piece off
13346   ** of the end of the master chunk.  This step happens very
13347   ** rarely (we hope!)
13348   */
13349   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
13350     memsys3OutOfMemory(toFree);
13351     if( mem3.iMaster ){
13352       memsys3Link(mem3.iMaster);
13353       mem3.iMaster = 0;
13354       mem3.szMaster = 0;
13355     }
13356     for(i=0; i<N_HASH; i++){
13357       memsys3Merge(&mem3.aiHash[i]);
13358     }
13359     for(i=0; i<MX_SMALL-1; i++){
13360       memsys3Merge(&mem3.aiSmall[i]);
13361     }
13362     if( mem3.szMaster ){
13363       memsys3Unlink(mem3.iMaster);
13364       if( mem3.szMaster>=nBlock ){
13365         return memsys3FromMaster(nBlock);
13366       }
13367     }
13368   }
13369
13370   /* If none of the above worked, then we fail. */
13371   return 0;
13372 }
13373
13374 /*
13375 ** Free an outstanding memory allocation.
13376 **
13377 ** This function assumes that the necessary mutexes, if any, are
13378 ** already held by the caller. Hence "Unsafe".
13379 */
13380 void memsys3FreeUnsafe(void *pOld){
13381   Mem3Block *p = (Mem3Block*)pOld;
13382   int i;
13383   u32 size, x;
13384   assert( sqlite3_mutex_held(mem3.mutex) );
13385   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
13386   i = p - mem3.aPool;
13387   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
13388   size = mem3.aPool[i-1].u.hdr.size4x/4;
13389   assert( i+size<=mem3.nPool+1 );
13390   mem3.aPool[i-1].u.hdr.size4x &= ~1;
13391   mem3.aPool[i+size-1].u.hdr.prevSize = size;
13392   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
13393   memsys3Link(i);
13394
13395   /* Try to expand the master using the newly freed chunk */
13396   if( mem3.iMaster ){
13397     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
13398       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
13399       mem3.iMaster -= size;
13400       mem3.szMaster += size;
13401       memsys3Unlink(mem3.iMaster);
13402       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
13403       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
13404       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
13405     }
13406     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
13407     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
13408       memsys3Unlink(mem3.iMaster+mem3.szMaster);
13409       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
13410       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
13411       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
13412     }
13413   }
13414 }
13415
13416 /*
13417 ** Return the size of an outstanding allocation, in bytes.  The
13418 ** size returned omits the 8-byte header overhead.  This only
13419 ** works for chunks that are currently checked out.
13420 */
13421 static int memsys3Size(void *p){
13422   Mem3Block *pBlock;
13423   if( p==0 ) return 0;
13424   pBlock = (Mem3Block*)p;
13425   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
13426   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
13427 }
13428
13429 /*
13430 ** Round up a request size to the next valid allocation size.
13431 */
13432 static int memsys3Roundup(int n){
13433   if( n<=12 ){
13434     return 12;
13435   }else{
13436     return ((n+11)&~7) - 4;
13437   }
13438 }
13439
13440 /*
13441 ** Allocate nBytes of memory.
13442 */
13443 static void *memsys3Malloc(int nBytes){
13444   sqlite3_int64 *p;
13445   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
13446   memsys3Enter();
13447   p = memsys3MallocUnsafe(nBytes);
13448   memsys3Leave();
13449   return (void*)p; 
13450 }
13451
13452 /*
13453 ** Free memory.
13454 */
13455 void memsys3Free(void *pPrior){
13456   assert( pPrior );
13457   memsys3Enter();
13458   memsys3FreeUnsafe(pPrior);
13459   memsys3Leave();
13460 }
13461
13462 /*
13463 ** Change the size of an existing memory allocation
13464 */
13465 void *memsys3Realloc(void *pPrior, int nBytes){
13466   int nOld;
13467   void *p;
13468   if( pPrior==0 ){
13469     return sqlite3_malloc(nBytes);
13470   }
13471   if( nBytes<=0 ){
13472     sqlite3_free(pPrior);
13473     return 0;
13474   }
13475   nOld = memsys3Size(pPrior);
13476   if( nBytes<=nOld && nBytes>=nOld-128 ){
13477     return pPrior;
13478   }
13479   memsys3Enter();
13480   p = memsys3MallocUnsafe(nBytes);
13481   if( p ){
13482     if( nOld<nBytes ){
13483       memcpy(p, pPrior, nOld);
13484     }else{
13485       memcpy(p, pPrior, nBytes);
13486     }
13487     memsys3FreeUnsafe(pPrior);
13488   }
13489   memsys3Leave();
13490   return p;
13491 }
13492
13493 /*
13494 ** Initialize this module.
13495 */
13496 static int memsys3Init(void *NotUsed){
13497   if( !sqlite3GlobalConfig.pHeap ){
13498     return SQLITE_ERROR;
13499   }
13500
13501   /* Store a pointer to the memory block in global structure mem3. */
13502   assert( sizeof(Mem3Block)==8 );
13503   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
13504   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
13505
13506   /* Initialize the master block. */
13507   mem3.szMaster = mem3.nPool;
13508   mem3.mnMaster = mem3.szMaster;
13509   mem3.iMaster = 1;
13510   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
13511   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
13512   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
13513
13514   return SQLITE_OK;
13515 }
13516
13517 /*
13518 ** Deinitialize this module.
13519 */
13520 static void memsys3Shutdown(void *NotUsed){
13521   return;
13522 }
13523
13524
13525
13526 /*
13527 ** Open the file indicated and write a log of all unfreed memory 
13528 ** allocations into that log.
13529 */
13530 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
13531 #ifdef SQLITE_DEBUG
13532   FILE *out;
13533   int i, j;
13534   u32 size;
13535   if( zFilename==0 || zFilename[0]==0 ){
13536     out = stdout;
13537   }else{
13538     out = fopen(zFilename, "w");
13539     if( out==0 ){
13540       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
13541                       zFilename);
13542       return;
13543     }
13544   }
13545   memsys3Enter();
13546   fprintf(out, "CHUNKS:\n");
13547   for(i=1; i<=mem3.nPool; i+=size/4){
13548     size = mem3.aPool[i-1].u.hdr.size4x;
13549     if( size/4<=1 ){
13550       fprintf(out, "%p size error\n", &mem3.aPool[i]);
13551       assert( 0 );
13552       break;
13553     }
13554     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
13555       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
13556       assert( 0 );
13557       break;
13558     }
13559     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
13560       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
13561       assert( 0 );
13562       break;
13563     }
13564     if( size&1 ){
13565       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
13566     }else{
13567       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
13568                   i==mem3.iMaster ? " **master**" : "");
13569     }
13570   }
13571   for(i=0; i<MX_SMALL-1; i++){
13572     if( mem3.aiSmall[i]==0 ) continue;
13573     fprintf(out, "small(%2d):", i);
13574     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
13575       fprintf(out, " %p(%d)", &mem3.aPool[j],
13576               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
13577     }
13578     fprintf(out, "\n"); 
13579   }
13580   for(i=0; i<N_HASH; i++){
13581     if( mem3.aiHash[i]==0 ) continue;
13582     fprintf(out, "hash(%2d):", i);
13583     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
13584       fprintf(out, " %p(%d)", &mem3.aPool[j],
13585               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
13586     }
13587     fprintf(out, "\n"); 
13588   }
13589   fprintf(out, "master=%d\n", mem3.iMaster);
13590   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
13591   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
13592   sqlite3_mutex_leave(mem3.mutex);
13593   if( out==stdout ){
13594     fflush(stdout);
13595   }else{
13596     fclose(out);
13597   }
13598 #endif
13599 }
13600
13601 /*
13602 ** This routine is the only routine in this file with external 
13603 ** linkage.
13604 **
13605 ** Populate the low-level memory allocation function pointers in
13606 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
13607 ** arguments specify the block of memory to manage.
13608 **
13609 ** This routine is only called by sqlite3_config(), and therefore
13610 ** is not required to be threadsafe (it is not).
13611 */
13612 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
13613   static const sqlite3_mem_methods mempoolMethods = {
13614      memsys3Malloc,
13615      memsys3Free,
13616      memsys3Realloc,
13617      memsys3Size,
13618      memsys3Roundup,
13619      memsys3Init,
13620      memsys3Shutdown,
13621      0
13622   };
13623   return &mempoolMethods;
13624 }
13625
13626 #endif /* SQLITE_ENABLE_MEMSYS3 */
13627
13628 /************** End of mem3.c ************************************************/
13629 /************** Begin file mem5.c ********************************************/
13630 /*
13631 ** 2007 October 14
13632 **
13633 ** The author disclaims copyright to this source code.  In place of
13634 ** a legal notice, here is a blessing:
13635 **
13636 **    May you do good and not evil.
13637 **    May you find forgiveness for yourself and forgive others.
13638 **    May you share freely, never taking more than you give.
13639 **
13640 *************************************************************************
13641 ** This file contains the C functions that implement a memory
13642 ** allocation subsystem for use by SQLite. 
13643 **
13644 ** This version of the memory allocation subsystem omits all
13645 ** use of malloc(). The SQLite user supplies a block of memory
13646 ** before calling sqlite3_initialize() from which allocations
13647 ** are made and returned by the xMalloc() and xRealloc() 
13648 ** implementations. Once sqlite3_initialize() has been called,
13649 ** the amount of memory available to SQLite is fixed and cannot
13650 ** be changed.
13651 **
13652 ** This version of the memory allocation subsystem is included
13653 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
13654 **
13655 ** $Id: mem5.c,v 1.14 2008/09/02 17:52:52 danielk1977 Exp $
13656 */
13657
13658 /*
13659 ** This version of the memory allocator is used only when 
13660 ** SQLITE_POW2_MEMORY_SIZE is defined.
13661 */
13662 #ifdef SQLITE_ENABLE_MEMSYS5
13663
13664 /*
13665 ** Log2 of the minimum size of an allocation.  For example, if
13666 ** 4 then all allocations will be rounded up to at least 16 bytes.
13667 ** If 5 then all allocations will be rounded up to at least 32 bytes.
13668 */
13669 #ifndef SQLITE_POW2_LOGMIN
13670 # define SQLITE_POW2_LOGMIN 6
13671 #endif
13672
13673 /*
13674 ** Log2 of the maximum size of an allocation.
13675 */
13676 #ifndef SQLITE_POW2_LOGMAX
13677 # define SQLITE_POW2_LOGMAX 20
13678 #endif
13679 #define POW2_MAX (((unsigned int)1)<<SQLITE_POW2_LOGMAX)
13680
13681 /*
13682 ** Number of distinct allocation sizes.
13683 */
13684 #define NSIZE (SQLITE_POW2_LOGMAX - SQLITE_POW2_LOGMIN + 1)
13685
13686 /*
13687 ** A minimum allocation is an instance of the following structure.
13688 ** Larger allocations are an array of these structures where the
13689 ** size of the array is a power of 2.
13690 */
13691 typedef struct Mem5Link Mem5Link;
13692 struct Mem5Link {
13693   int next;       /* Index of next free chunk */
13694   int prev;       /* Index of previous free chunk */
13695 };
13696
13697 /*
13698 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.nAtom). Since
13699 ** mem5.nAtom is always at least 8, this is not really a practical
13700 ** limitation.
13701 */
13702 #define LOGMAX 30
13703
13704 /*
13705 ** Masks used for mem5.aCtrl[] elements.
13706 */
13707 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block relative to POW2_MIN */
13708 #define CTRL_FREE     0x20    /* True if not checked out */
13709
13710 /*
13711 ** All of the static variables used by this module are collected
13712 ** into a single structure named "mem5".  This is to keep the
13713 ** static variables organized and to reduce namespace pollution
13714 ** when this module is combined with other in the amalgamation.
13715 */
13716 static SQLITE_WSD struct Mem5Global {
13717   /*
13718   ** Memory available for allocation
13719   */
13720   int nAtom;       /* Smallest possible allocation in bytes */
13721   int nBlock;      /* Number of nAtom sized blocks in zPool */
13722   u8 *zPool;
13723   
13724   /*
13725   ** Mutex to control access to the memory allocation subsystem.
13726   */
13727   sqlite3_mutex *mutex;
13728
13729   /*
13730   ** Performance statistics
13731   */
13732   u64 nAlloc;         /* Total number of calls to malloc */
13733   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
13734   u64 totalExcess;    /* Total internal fragmentation */
13735   u32 currentOut;     /* Current checkout, including internal fragmentation */
13736   u32 currentCount;   /* Current number of distinct checkouts */
13737   u32 maxOut;         /* Maximum instantaneous currentOut */
13738   u32 maxCount;       /* Maximum instantaneous currentCount */
13739   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
13740   
13741   /*
13742   ** Lists of free blocks of various sizes.
13743   */
13744   int aiFreelist[LOGMAX+1];
13745
13746   /*
13747   ** Space for tracking which blocks are checked out and the size
13748   ** of each block.  One byte per block.
13749   */
13750   u8 *aCtrl;
13751
13752 } mem5 = { 19804167 };
13753
13754 #define mem5 GLOBAL(struct Mem5Global, mem5)
13755
13756 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.nAtom]))
13757
13758 /*
13759 ** Unlink the chunk at mem5.aPool[i] from list it is currently
13760 ** on.  It should be found on mem5.aiFreelist[iLogsize].
13761 */
13762 static void memsys5Unlink(int i, int iLogsize){
13763   int next, prev;
13764   assert( i>=0 && i<mem5.nBlock );
13765   assert( iLogsize>=0 && iLogsize<=LOGMAX );
13766   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
13767
13768   next = MEM5LINK(i)->next;
13769   prev = MEM5LINK(i)->prev;
13770   if( prev<0 ){
13771     mem5.aiFreelist[iLogsize] = next;
13772   }else{
13773     MEM5LINK(prev)->next = next;
13774   }
13775   if( next>=0 ){
13776     MEM5LINK(next)->prev = prev;
13777   }
13778 }
13779
13780 /*
13781 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
13782 ** free list.
13783 */
13784 static void memsys5Link(int i, int iLogsize){
13785   int x;
13786   assert( sqlite3_mutex_held(mem5.mutex) );
13787   assert( i>=0 && i<mem5.nBlock );
13788   assert( iLogsize>=0 && iLogsize<=LOGMAX );
13789   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
13790
13791   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
13792   MEM5LINK(i)->prev = -1;
13793   if( x>=0 ){
13794     assert( x<mem5.nBlock );
13795     MEM5LINK(x)->prev = i;
13796   }
13797   mem5.aiFreelist[iLogsize] = i;
13798 }
13799
13800 /*
13801 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
13802 ** will already be held (obtained by code in malloc.c) if
13803 ** sqlite3GlobalConfig.bMemStat is true.
13804 */
13805 static void memsys5Enter(void){
13806   if( sqlite3GlobalConfig.bMemstat==0 && mem5.mutex==0 ){
13807     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
13808   }
13809   sqlite3_mutex_enter(mem5.mutex);
13810 }
13811 static void memsys5Leave(void){
13812   sqlite3_mutex_leave(mem5.mutex);
13813 }
13814
13815 /*
13816 ** Return the size of an outstanding allocation, in bytes.  The
13817 ** size returned omits the 8-byte header overhead.  This only
13818 ** works for chunks that are currently checked out.
13819 */
13820 static int memsys5Size(void *p){
13821   int iSize = 0;
13822   if( p ){
13823     int i = ((u8 *)p-mem5.zPool)/mem5.nAtom;
13824     assert( i>=0 && i<mem5.nBlock );
13825     iSize = mem5.nAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
13826   }
13827   return iSize;
13828 }
13829
13830 /*
13831 ** Find the first entry on the freelist iLogsize.  Unlink that
13832 ** entry and return its index. 
13833 */
13834 static int memsys5UnlinkFirst(int iLogsize){
13835   int i;
13836   int iFirst;
13837
13838   assert( iLogsize>=0 && iLogsize<=LOGMAX );
13839   i = iFirst = mem5.aiFreelist[iLogsize];
13840   assert( iFirst>=0 );
13841   while( i>0 ){
13842     if( i<iFirst ) iFirst = i;
13843     i = MEM5LINK(i)->next;
13844   }
13845   memsys5Unlink(iFirst, iLogsize);
13846   return iFirst;
13847 }
13848
13849 /*
13850 ** Return a block of memory of at least nBytes in size.
13851 ** Return NULL if unable.
13852 */
13853 static void *memsys5MallocUnsafe(int nByte){
13854   int i;           /* Index of a mem5.aPool[] slot */
13855   int iBin;        /* Index into mem5.aiFreelist[] */
13856   int iFullSz;     /* Size of allocation rounded up to power of 2 */
13857   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
13858
13859   /* Keep track of the maximum allocation request.  Even unfulfilled
13860   ** requests are counted */
13861   if( nByte>mem5.maxRequest ){
13862     mem5.maxRequest = nByte;
13863   }
13864
13865   /* Round nByte up to the next valid power of two */
13866   if( nByte>POW2_MAX ) return 0;
13867   for(iFullSz=mem5.nAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
13868
13869   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
13870   ** block.  If not, then split a block of the next larger power of
13871   ** two in order to create a new free block of size iLogsize.
13872   */
13873   for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
13874   if( iBin>LOGMAX ) return 0;
13875   i = memsys5UnlinkFirst(iBin);
13876   while( iBin>iLogsize ){
13877     int newSize;
13878
13879     iBin--;
13880     newSize = 1 << iBin;
13881     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
13882     memsys5Link(i+newSize, iBin);
13883   }
13884   mem5.aCtrl[i] = iLogsize;
13885
13886   /* Update allocator performance statistics. */
13887   mem5.nAlloc++;
13888   mem5.totalAlloc += iFullSz;
13889   mem5.totalExcess += iFullSz - nByte;
13890   mem5.currentCount++;
13891   mem5.currentOut += iFullSz;
13892   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
13893   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
13894
13895   /* Return a pointer to the allocated memory. */
13896   return (void*)&mem5.zPool[i*mem5.nAtom];
13897 }
13898
13899 /*
13900 ** Free an outstanding memory allocation.
13901 */
13902 static void memsys5FreeUnsafe(void *pOld){
13903   u32 size, iLogsize;
13904   int iBlock;             
13905
13906   /* Set iBlock to the index of the block pointed to by pOld in 
13907   ** the array of mem5.nAtom byte blocks pointed to by mem5.zPool.
13908   */
13909   iBlock = ((u8 *)pOld-mem5.zPool)/mem5.nAtom;
13910
13911   /* Check that the pointer pOld points to a valid, non-free block. */
13912   assert( iBlock>=0 && iBlock<mem5.nBlock );
13913   assert( ((u8 *)pOld-mem5.zPool)%mem5.nAtom==0 );
13914   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
13915
13916   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
13917   size = 1<<iLogsize;
13918   assert( iBlock+size-1<mem5.nBlock );
13919
13920   mem5.aCtrl[iBlock] |= CTRL_FREE;
13921   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
13922   assert( mem5.currentCount>0 );
13923   assert( mem5.currentOut>=0 );
13924   mem5.currentCount--;
13925   mem5.currentOut -= size*mem5.nAtom;
13926   assert( mem5.currentOut>0 || mem5.currentCount==0 );
13927   assert( mem5.currentCount>0 || mem5.currentOut==0 );
13928
13929   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
13930   while( iLogsize<LOGMAX ){
13931     int iBuddy;
13932     if( (iBlock>>iLogsize) & 1 ){
13933       iBuddy = iBlock - size;
13934     }else{
13935       iBuddy = iBlock + size;
13936     }
13937     assert( iBuddy>=0 );
13938     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
13939     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
13940     memsys5Unlink(iBuddy, iLogsize);
13941     iLogsize++;
13942     if( iBuddy<iBlock ){
13943       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
13944       mem5.aCtrl[iBlock] = 0;
13945       iBlock = iBuddy;
13946     }else{
13947       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
13948       mem5.aCtrl[iBuddy] = 0;
13949     }
13950     size *= 2;
13951   }
13952   memsys5Link(iBlock, iLogsize);
13953 }
13954
13955 /*
13956 ** Allocate nBytes of memory
13957 */
13958 static void *memsys5Malloc(int nBytes){
13959   sqlite3_int64 *p = 0;
13960   if( nBytes>0 ){
13961     memsys5Enter();
13962     p = memsys5MallocUnsafe(nBytes);
13963     memsys5Leave();
13964   }
13965   return (void*)p; 
13966 }
13967
13968 /*
13969 ** Free memory.
13970 */
13971 static void memsys5Free(void *pPrior){
13972   if( pPrior==0 ){
13973 assert(0);
13974     return;
13975   }
13976   memsys5Enter();
13977   memsys5FreeUnsafe(pPrior);
13978   memsys5Leave();  
13979 }
13980
13981 /*
13982 ** Change the size of an existing memory allocation
13983 */
13984 static void *memsys5Realloc(void *pPrior, int nBytes){
13985   int nOld;
13986   void *p;
13987   if( pPrior==0 ){
13988     return memsys5Malloc(nBytes);
13989   }
13990   if( nBytes<=0 ){
13991     memsys5Free(pPrior);
13992     return 0;
13993   }
13994   nOld = memsys5Size(pPrior);
13995   if( nBytes<=nOld ){
13996     return pPrior;
13997   }
13998   memsys5Enter();
13999   p = memsys5MallocUnsafe(nBytes);
14000   if( p ){
14001     memcpy(p, pPrior, nOld);
14002     memsys5FreeUnsafe(pPrior);
14003   }
14004   memsys5Leave();
14005   return p;
14006 }
14007
14008 /*
14009 ** Round up a request size to the next valid allocation size.
14010 */
14011 static int memsys5Roundup(int n){
14012   int iFullSz;
14013   for(iFullSz=mem5.nAtom; iFullSz<n; iFullSz *= 2);
14014   return iFullSz;
14015 }
14016
14017 static int memsys5Log(int iValue){
14018   int iLog;
14019   for(iLog=0; (1<<iLog)<iValue; iLog++);
14020   return iLog;
14021 }
14022
14023 /*
14024 ** Initialize this module.
14025 */
14026 static int memsys5Init(void *NotUsed){
14027   int ii;
14028   int nByte = sqlite3GlobalConfig.nHeap;
14029   u8 *zByte = (u8 *)sqlite3GlobalConfig.pHeap;
14030   int nMinLog;                 /* Log of minimum allocation size in bytes*/
14031   int iOffset;
14032
14033   if( !zByte ){
14034     return SQLITE_ERROR;
14035   }
14036
14037   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
14038   mem5.nAtom = (1<<nMinLog);
14039   while( sizeof(Mem5Link)>mem5.nAtom ){
14040     mem5.nAtom = mem5.nAtom << 1;
14041   }
14042
14043   mem5.nBlock = (nByte / (mem5.nAtom+sizeof(u8)));
14044   mem5.zPool = zByte;
14045   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.nAtom];
14046
14047   for(ii=0; ii<=LOGMAX; ii++){
14048     mem5.aiFreelist[ii] = -1;
14049   }
14050
14051   iOffset = 0;
14052   for(ii=LOGMAX; ii>=0; ii--){
14053     int nAlloc = (1<<ii);
14054     if( (iOffset+nAlloc)<=mem5.nBlock ){
14055       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
14056       memsys5Link(iOffset, ii);
14057       iOffset += nAlloc;
14058     }
14059     assert((iOffset+nAlloc)>mem5.nBlock);
14060   }
14061
14062   return SQLITE_OK;
14063 }
14064
14065 /*
14066 ** Deinitialize this module.
14067 */
14068 static void memsys5Shutdown(void *NotUsed){
14069   return;
14070 }
14071
14072 /*
14073 ** Open the file indicated and write a log of all unfreed memory 
14074 ** allocations into that log.
14075 */
14076 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
14077 #ifdef SQLITE_DEBUG
14078   FILE *out;
14079   int i, j, n;
14080   int nMinLog;
14081
14082   if( zFilename==0 || zFilename[0]==0 ){
14083     out = stdout;
14084   }else{
14085     out = fopen(zFilename, "w");
14086     if( out==0 ){
14087       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
14088                       zFilename);
14089       return;
14090     }
14091   }
14092   memsys5Enter();
14093   nMinLog = memsys5Log(mem5.nAtom);
14094   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
14095     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
14096     fprintf(out, "freelist items of size %d: %d\n", mem5.nAtom << i, n);
14097   }
14098   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
14099   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
14100   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
14101   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
14102   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
14103   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
14104   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
14105   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
14106   memsys5Leave();
14107   if( out==stdout ){
14108     fflush(stdout);
14109   }else{
14110     fclose(out);
14111   }
14112 #endif
14113 }
14114
14115 /*
14116 ** This routine is the only routine in this file with external 
14117 ** linkage. It returns a pointer to a static sqlite3_mem_methods
14118 ** struct populated with the memsys5 methods.
14119 */
14120 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
14121   static const sqlite3_mem_methods memsys5Methods = {
14122      memsys5Malloc,
14123      memsys5Free,
14124      memsys5Realloc,
14125      memsys5Size,
14126      memsys5Roundup,
14127      memsys5Init,
14128      memsys5Shutdown,
14129      0
14130   };
14131   return &memsys5Methods;
14132 }
14133
14134 #endif /* SQLITE_ENABLE_MEMSYS5 */
14135
14136 /************** End of mem5.c ************************************************/
14137 /************** Begin file mem6.c ********************************************/
14138 /*
14139 ** 2008 July 24
14140 **
14141 ** The author disclaims copyright to this source code.  In place of
14142 ** a legal notice, here is a blessing:
14143 **
14144 **    May you do good and not evil.
14145 **    May you find forgiveness for yourself and forgive others.
14146 **    May you share freely, never taking more than you give.
14147 **
14148 *************************************************************************
14149 **
14150 ** This file contains an alternative memory allocation system for SQLite.
14151 ** This system is implemented as a wrapper around the system provided
14152 ** by the operating system - vanilla malloc(), realloc() and free().
14153 **
14154 ** This system differentiates between requests for "small" allocations 
14155 ** (by default those of 128 bytes or less) and "large" allocations (all
14156 ** others). The 256 byte threshhold is configurable at runtime.
14157 **
14158 ** All requests for large allocations are passed through to the 
14159 ** default system.
14160 **
14161 ** Requests for small allocations are met by allocating space within
14162 ** one or more larger "chunks" of memory obtained from the default
14163 ** memory allocation system. Chunks of memory are usually 64KB or 
14164 ** larger. The algorithm used to manage space within each chunk is
14165 ** the same as that used by mem5.c. 
14166 **
14167 ** This strategy is designed to prevent the default memory allocation
14168 ** system (usually the system malloc) from suffering from heap 
14169 ** fragmentation. On some systems, heap fragmentation can cause a 
14170 ** significant real-time slowdown.
14171 **
14172 ** $Id: mem6.c,v 1.10 2008/09/02 17:52:52 danielk1977 Exp $
14173 */
14174
14175 #ifdef SQLITE_ENABLE_MEMSYS6
14176
14177
14178 /*
14179 ** Maximum size of any "small" allocation is ((1<<LOGMAX)*Mem6Chunk.nAtom).
14180 ** Mem6Chunk.nAtom is always at least 8, so this is not a practical
14181 ** limitation
14182 */
14183 #define LOGMAX 30
14184
14185 /*
14186 ** Default value for the "small" allocation size threshold.
14187 */
14188 #define SMALL_MALLOC_DEFAULT_THRESHOLD 256
14189
14190 /*
14191 ** Minimum size for a memory chunk.
14192 */
14193 #define MIN_CHUNKSIZE (1<<16)
14194
14195 #define LOG2_MINALLOC 4
14196
14197
14198 typedef struct Mem6Chunk Mem6Chunk;
14199 typedef struct Mem6Link Mem6Link;
14200
14201 /*
14202 ** A minimum allocation is an instance of the following structure.
14203 ** Larger allocations are an array of these structures where the
14204 ** size of the array is a power of 2.
14205 */
14206 struct Mem6Link {
14207   int next;       /* Index of next free chunk */
14208   int prev;       /* Index of previous free chunk */
14209 };
14210
14211 /*
14212 ** Masks used for mem5.aCtrl[] elements.
14213 */
14214 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block relative to POW2_MIN */
14215 #define CTRL_FREE     0x20    /* True if not checked out */
14216
14217 struct Mem6Chunk {
14218   Mem6Chunk *pNext;
14219
14220   /*
14221   ** Lists of free blocks of various sizes.
14222   */
14223   int aiFreelist[LOGMAX+1];
14224
14225   int nCheckedOut; /* Number of currently outstanding allocations */
14226
14227   /*
14228   ** Space for tracking which blocks are checked out and the size
14229   ** of each block. One byte per block.
14230   */
14231   u8 *aCtrl;
14232
14233   /*
14234   ** Memory available for allocation
14235   */
14236   int nAtom;       /* Smallest possible allocation in bytes */
14237   int nBlock;      /* Number of nAtom sized blocks in zPool */
14238   u8 *zPool;       /* Pointer to memory chunk from which allocations are made */
14239 };
14240
14241 #define MEM6LINK(idx) ((Mem6Link *)(&pChunk->zPool[(idx)*pChunk->nAtom]))
14242
14243 static SQLITE_WSD struct Mem6Global {
14244   int nMinAlloc;                  /* Minimum allowed allocation size */
14245   int nThreshold;                 /* Allocs larger than this go to malloc() */
14246   int nLogThreshold;              /* log2 of (nThreshold/nMinAlloc) */
14247   sqlite3_mutex *mutex;
14248   Mem6Chunk *pChunk;              /* Singly linked list of all memory chunks */
14249 } mem6 = { 48642791 };
14250
14251 #define mem6 GLOBAL(struct Mem6Global, mem6)
14252
14253 /*
14254 ** Unlink the chunk at pChunk->aPool[i] from list it is currently
14255 ** on.  It should be found on pChunk->aiFreelist[iLogsize].
14256 */
14257 static void memsys6Unlink(Mem6Chunk *pChunk, int i, int iLogsize){
14258   int next, prev;
14259   assert( i>=0 && i<pChunk->nBlock );
14260   assert( iLogsize>=0 && iLogsize<=mem6.nLogThreshold );
14261   assert( (pChunk->aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
14262
14263   next = MEM6LINK(i)->next;
14264   prev = MEM6LINK(i)->prev;
14265   if( prev<0 ){
14266     pChunk->aiFreelist[iLogsize] = next;
14267   }else{
14268     MEM6LINK(prev)->next = next;
14269   }
14270   if( next>=0 ){
14271     MEM6LINK(next)->prev = prev;
14272   }
14273 }
14274
14275 /*
14276 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
14277 ** free list.
14278 */
14279 static void memsys6Link(Mem6Chunk *pChunk, int i, int iLogsize){
14280   int x;
14281   assert( i>=0 && i<pChunk->nBlock );
14282   assert( iLogsize>=0 && iLogsize<=mem6.nLogThreshold );
14283   assert( (pChunk->aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
14284
14285   x = MEM6LINK(i)->next = pChunk->aiFreelist[iLogsize];
14286   MEM6LINK(i)->prev = -1;
14287   if( x>=0 ){
14288     assert( x<pChunk->nBlock );
14289     MEM6LINK(x)->prev = i;
14290   }
14291   pChunk->aiFreelist[iLogsize] = i;
14292 }
14293
14294
14295 /*
14296 ** Find the first entry on the freelist iLogsize.  Unlink that
14297 ** entry and return its index. 
14298 */
14299 static int memsys6UnlinkFirst(Mem6Chunk *pChunk, int iLogsize){
14300   int i;
14301   int iFirst;
14302
14303   assert( iLogsize>=0 && iLogsize<=mem6.nLogThreshold );
14304   i = iFirst = pChunk->aiFreelist[iLogsize];
14305   assert( iFirst>=0 );
14306   memsys6Unlink(pChunk, iFirst, iLogsize);
14307   return iFirst;
14308 }
14309
14310 static int roundupLog2(int n){
14311   static const char LogTable256[256] = {
14312     0,                                                    /* 1 */
14313     1,                                                    /* 2 */
14314     2, 2,                                                 /* 3..4 */
14315     3, 3, 3, 3,                                           /* 5..8 */
14316     4, 4, 4, 4, 4, 4, 4, 4,                               /* 9..16 */
14317     5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,       /* 17..32 */
14318     6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
14319     6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,       /* 33..64 */
14320     7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
14321     7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
14322     7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
14323     7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,       /* 65..128 */
14324     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
14325     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
14326     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
14327     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
14328     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
14329     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
14330     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
14331     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,       /* 129..256 */
14332   };
14333
14334   assert(n<=(1<<16) && n>0);
14335   if( n<=256 ) return LogTable256[n-1];
14336   return LogTable256[(n>>8) - ((n&0xFF)?0:1)] + 8;
14337 }
14338
14339 /*
14340 ** Allocate and return a block of (pChunk->nAtom << iLogsize) bytes from chunk
14341 ** pChunk. If the allocation request cannot be satisfied, return 0.
14342 */
14343 static void *chunkMalloc(Mem6Chunk *pChunk, int iLogsize){
14344   int i;           /* Index of a mem5.aPool[] slot */
14345   int iBin;        /* Index into mem5.aiFreelist[] */
14346
14347   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
14348   ** block.  If not, then split a block of the next larger power of
14349   ** two in order to create a new free block of size iLogsize.
14350   */
14351   for(iBin=iLogsize; pChunk->aiFreelist[iBin]<0 && iBin<=mem6.nLogThreshold; iBin++){}
14352   if( iBin>mem6.nLogThreshold ) return 0;
14353   i = memsys6UnlinkFirst(pChunk, iBin);
14354   while( iBin>iLogsize ){
14355     int newSize;
14356     iBin--;
14357     newSize = 1 << iBin;
14358     pChunk->aCtrl[i+newSize] = CTRL_FREE | iBin;
14359     memsys6Link(pChunk, i+newSize, iBin);
14360   }
14361   pChunk->aCtrl[i] = iLogsize;
14362
14363   /* Return a pointer to the allocated memory. */
14364   pChunk->nCheckedOut++;
14365   return (void*)&pChunk->zPool[i*pChunk->nAtom];
14366 }
14367
14368 /*
14369 ** Free the allocation pointed to by p, which is guaranteed to be non-zero
14370 ** and a part of chunk object pChunk.
14371 */
14372 static void chunkFree(Mem6Chunk *pChunk, void *pOld){
14373   u32 size, iLogsize;
14374   int iBlock;             
14375
14376   /* Set iBlock to the index of the block pointed to by pOld in 
14377   ** the array of pChunk->nAtom byte blocks pointed to by pChunk->zPool.
14378   */
14379   iBlock = ((u8 *)pOld-pChunk->zPool)/pChunk->nAtom;
14380
14381   /* Check that the pointer pOld points to a valid, non-free block. */
14382   assert( iBlock>=0 && iBlock<pChunk->nBlock );
14383   assert( ((u8 *)pOld-pChunk->zPool)%pChunk->nAtom==0 );
14384   assert( (pChunk->aCtrl[iBlock] & CTRL_FREE)==0 );
14385
14386   iLogsize = pChunk->aCtrl[iBlock] & CTRL_LOGSIZE;
14387   size = 1<<iLogsize;
14388   assert( iBlock+size-1<pChunk->nBlock );
14389
14390   pChunk->aCtrl[iBlock] |= CTRL_FREE;
14391   pChunk->aCtrl[iBlock+size-1] |= CTRL_FREE;
14392
14393   pChunk->aCtrl[iBlock] = CTRL_FREE | iLogsize;
14394   while( iLogsize<mem6.nLogThreshold ){
14395     int iBuddy;
14396     if( (iBlock>>iLogsize) & 1 ){
14397       iBuddy = iBlock - size;
14398     }else{
14399       iBuddy = iBlock + size;
14400     }
14401     assert( iBuddy>=0 );
14402     if( (iBuddy+(1<<iLogsize))>pChunk->nBlock ) break;
14403     if( pChunk->aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
14404     memsys6Unlink(pChunk, iBuddy, iLogsize);
14405     iLogsize++;
14406     if( iBuddy<iBlock ){
14407       pChunk->aCtrl[iBuddy] = CTRL_FREE | iLogsize;
14408       pChunk->aCtrl[iBlock] = 0;
14409       iBlock = iBuddy;
14410     }else{
14411       pChunk->aCtrl[iBlock] = CTRL_FREE | iLogsize;
14412       pChunk->aCtrl[iBuddy] = 0;
14413     }
14414     size *= 2;
14415   }
14416   pChunk->nCheckedOut--;
14417   memsys6Link(pChunk, iBlock, iLogsize);
14418 }
14419
14420 /*
14421 ** Return the actual size of the block pointed to by p, which is guaranteed
14422 ** to have been allocated from chunk pChunk.
14423 */
14424 static int chunkSize(Mem6Chunk *pChunk, void *p){
14425   int iSize = 0;
14426   if( p ){
14427     int i = ((u8 *)p-pChunk->zPool)/pChunk->nAtom;
14428     assert( i>=0 && i<pChunk->nBlock );
14429     iSize = pChunk->nAtom * (1 << (pChunk->aCtrl[i]&CTRL_LOGSIZE));
14430   }
14431   return iSize;
14432 }
14433
14434 /*
14435 ** Return true if there are currently no outstanding allocations.
14436 */
14437 static int chunkIsEmpty(Mem6Chunk *pChunk){
14438   return (pChunk->nCheckedOut==0);
14439 }
14440
14441 /*
14442 ** Initialize the buffer zChunk, which is nChunk bytes in size, as
14443 ** an Mem6Chunk object. Return a copy of the zChunk pointer.
14444 */
14445 static Mem6Chunk *chunkInit(u8 *zChunk, int nChunk, int nMinAlloc){
14446   int ii;
14447   int iOffset;
14448   Mem6Chunk *pChunk = (Mem6Chunk *)zChunk;
14449
14450   assert( nChunk>sizeof(Mem6Chunk) );
14451   assert( nMinAlloc>sizeof(Mem6Link) );
14452
14453   memset(pChunk, 0, sizeof(Mem6Chunk));
14454   pChunk->nAtom = nMinAlloc;
14455   pChunk->nBlock = ((nChunk-sizeof(Mem6Chunk)) / (pChunk->nAtom+sizeof(u8)));
14456
14457   pChunk->zPool = (u8 *)&pChunk[1];
14458   pChunk->aCtrl = &pChunk->zPool[pChunk->nBlock*pChunk->nAtom];
14459
14460   for(ii=0; ii<=mem6.nLogThreshold; ii++){
14461     pChunk->aiFreelist[ii] = -1;
14462   }
14463
14464   iOffset = 0;
14465   for(ii=mem6.nLogThreshold; ii>=0; ii--){
14466     int nAlloc = (1<<ii);
14467     while( (iOffset+nAlloc)<=pChunk->nBlock ){
14468       pChunk->aCtrl[iOffset] = ii | CTRL_FREE;
14469       memsys6Link(pChunk, iOffset, ii);
14470       iOffset += nAlloc;
14471     }
14472   }
14473
14474   return pChunk;
14475 }
14476
14477
14478 static void mem6Enter(void){
14479   sqlite3_mutex_enter(mem6.mutex);
14480 }
14481
14482 static void mem6Leave(void){
14483   sqlite3_mutex_leave(mem6.mutex);
14484 }
14485
14486 /*
14487 ** Based on the number and size of the currently allocated chunks, return
14488 ** the size of the next chunk to allocate, in bytes.
14489 */
14490 static int nextChunkSize(void){
14491   int iTotal = MIN_CHUNKSIZE;
14492   Mem6Chunk *p;
14493   for(p=mem6.pChunk; p; p=p->pNext){
14494     iTotal = iTotal*2;
14495   }
14496   return iTotal;
14497 }
14498
14499 static void freeChunk(Mem6Chunk *pChunk){
14500   Mem6Chunk **pp = &mem6.pChunk;
14501   for( pp=&mem6.pChunk; *pp!=pChunk; pp = &(*pp)->pNext );
14502   *pp = (*pp)->pNext;
14503   free(pChunk);
14504 }
14505
14506 static void *memsys6Malloc(int nByte){
14507   Mem6Chunk *pChunk;
14508   void *p = 0;
14509   int nTotal = nByte+8;
14510   int iOffset = 0;
14511
14512   if( nTotal>mem6.nThreshold ){
14513     p = malloc(nTotal);
14514   }else{
14515     int iLogsize = 0;
14516     if( nTotal>(1<<LOG2_MINALLOC) ){
14517       iLogsize = roundupLog2(nTotal) - LOG2_MINALLOC;
14518     }
14519     mem6Enter();
14520     for(pChunk=mem6.pChunk; pChunk; pChunk=pChunk->pNext){
14521       p = chunkMalloc(pChunk, iLogsize);
14522       if( p ){
14523         break;
14524       }
14525     }
14526     if( !p ){
14527       int iSize = nextChunkSize();
14528       p = malloc(iSize);
14529       if( p ){
14530         pChunk = chunkInit((u8 *)p, iSize, mem6.nMinAlloc);
14531         pChunk->pNext = mem6.pChunk;
14532         mem6.pChunk = pChunk;
14533         p = chunkMalloc(pChunk, iLogsize);
14534         assert(p);
14535       }
14536     }
14537     iOffset = ((u8*)p - (u8*)pChunk);
14538     mem6Leave();
14539   }
14540
14541   if( !p ){
14542     return 0;
14543   }
14544   ((u32 *)p)[0] = iOffset;
14545   ((u32 *)p)[1] = nByte;
14546   return &((u32 *)p)[2];
14547 }
14548
14549 static int memsys6Size(void *pPrior){
14550   if( pPrior==0 ) return 0;
14551   return ((u32*)pPrior)[-1];
14552 }
14553
14554 static void memsys6Free(void *pPrior){
14555   int iSlot;
14556   void *p = &((u32 *)pPrior)[-2];
14557   iSlot = ((u32 *)p)[0];
14558   if( iSlot ){
14559     Mem6Chunk *pChunk;
14560     mem6Enter();
14561     pChunk = (Mem6Chunk *)(&((u8 *)p)[-1 * iSlot]);
14562     chunkFree(pChunk, p);
14563     if( chunkIsEmpty(pChunk) ){
14564       freeChunk(pChunk);
14565     }
14566     mem6Leave();
14567   }else{
14568     free(p);
14569   }
14570 }
14571
14572 static void *memsys6Realloc(void *p, int nByte){
14573   void *p2;
14574
14575   if( p && nByte<=memsys6Size(p) ){
14576     p2 = p;
14577   }else{
14578     p2 = memsys6Malloc(nByte);
14579     if( p && p2 ){
14580       memcpy(p2, p, memsys6Size(p));
14581       memsys6Free(p);
14582     }
14583   }
14584
14585   return p2;
14586 }
14587
14588 static int memsys6Roundup(int n){
14589   if( n>mem6.nThreshold ){
14590     return n;
14591   }else{
14592     return (1<<roundupLog2(n));
14593   }
14594 }
14595
14596 static int memsys6Init(void *pCtx){
14597   u8 bMemstat = sqlite3GlobalConfig.bMemstat;
14598   mem6.nMinAlloc = (1 << LOG2_MINALLOC);
14599   mem6.pChunk = 0;
14600   mem6.nThreshold = sqlite3GlobalConfig.nSmall;
14601   if( mem6.nThreshold<=0 ){
14602     mem6.nThreshold = SMALL_MALLOC_DEFAULT_THRESHOLD;
14603   }
14604   mem6.nLogThreshold = roundupLog2(mem6.nThreshold) - LOG2_MINALLOC;
14605   if( !bMemstat ){
14606     mem6.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
14607   }
14608   return SQLITE_OK;
14609 }
14610
14611 static void memsys6Shutdown(void *pCtx){
14612   memset(&mem6, 0, sizeof(mem6));
14613 }
14614
14615 /*
14616 ** This routine is the only routine in this file with external 
14617 ** linkage. It returns a pointer to a static sqlite3_mem_methods
14618 ** struct populated with the memsys6 methods.
14619 */
14620 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys6(void){
14621   static const sqlite3_mem_methods memsys6Methods = {
14622      memsys6Malloc,
14623      memsys6Free,
14624      memsys6Realloc,
14625      memsys6Size,
14626      memsys6Roundup,
14627      memsys6Init,
14628      memsys6Shutdown,
14629      0
14630   };
14631   return &memsys6Methods;
14632 }
14633
14634 #endif
14635
14636 /************** End of mem6.c ************************************************/
14637 /************** Begin file mutex.c *******************************************/
14638 /*
14639 ** 2007 August 14
14640 **
14641 ** The author disclaims copyright to this source code.  In place of
14642 ** a legal notice, here is a blessing:
14643 **
14644 **    May you do good and not evil.
14645 **    May you find forgiveness for yourself and forgive others.
14646 **    May you share freely, never taking more than you give.
14647 **
14648 *************************************************************************
14649 ** This file contains the C functions that implement mutexes.
14650 **
14651 ** The implementation in this file does not provide any mutual
14652 ** exclusion and is thus suitable for use only in applications
14653 ** that use SQLite in a single thread.  But this implementation
14654 ** does do a lot of error checking on mutexes to make sure they
14655 ** are called correctly and at appropriate times.  Hence, this
14656 ** implementation is suitable for testing.
14657 ** debugging purposes
14658 **
14659 ** $Id: mutex.c,v 1.28 2008/09/01 18:34:20 danielk1977 Exp $
14660 */
14661
14662 #ifndef SQLITE_MUTEX_NOOP
14663 /*
14664 ** Initialize the mutex system.
14665 */
14666 SQLITE_PRIVATE int sqlite3MutexInit(void){ 
14667   int rc = SQLITE_OK;
14668   if( sqlite3GlobalConfig.bCoreMutex ){
14669     if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
14670       /* If the xMutexAlloc method has not been set, then the user did not
14671       ** install a mutex implementation via sqlite3_config() prior to 
14672       ** sqlite3_initialize() being called. This block copies pointers to
14673       ** the default implementation into the sqlite3GlobalConfig structure.
14674       **
14675       ** The danger is that although sqlite3_config() is not a threadsafe
14676       ** API, sqlite3_initialize() is, and so multiple threads may be
14677       ** attempting to run this function simultaneously. To guard write
14678       ** access to the sqlite3GlobalConfig structure, the 'MASTER' static mutex
14679       ** is obtained before modifying it.
14680       */
14681       sqlite3_mutex_methods *p = sqlite3DefaultMutex();
14682       sqlite3_mutex *pMaster = 0;
14683   
14684       rc = p->xMutexInit();
14685       if( rc==SQLITE_OK ){
14686         pMaster = p->xMutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14687         assert(pMaster);
14688         p->xMutexEnter(pMaster);
14689         assert( sqlite3GlobalConfig.mutex.xMutexAlloc==0 
14690              || sqlite3GlobalConfig.mutex.xMutexAlloc==p->xMutexAlloc
14691         );
14692         if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
14693           sqlite3GlobalConfig.mutex = *p;
14694         }
14695         p->xMutexLeave(pMaster);
14696       }
14697     }else{
14698       rc = sqlite3GlobalConfig.mutex.xMutexInit();
14699     }
14700   }
14701
14702   return rc;
14703 }
14704
14705 /*
14706 ** Shutdown the mutex system. This call frees resources allocated by
14707 ** sqlite3MutexInit().
14708 */
14709 SQLITE_PRIVATE int sqlite3MutexEnd(void){
14710   int rc = SQLITE_OK;
14711   rc = sqlite3GlobalConfig.mutex.xMutexEnd();
14712   return rc;
14713 }
14714
14715 /*
14716 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
14717 */
14718 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
14719 #ifndef SQLITE_OMIT_AUTOINIT
14720   if( sqlite3_initialize() ) return 0;
14721 #endif
14722   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
14723 }
14724
14725 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
14726   if( !sqlite3GlobalConfig.bCoreMutex ){
14727     return 0;
14728   }
14729   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
14730 }
14731
14732 /*
14733 ** Free a dynamic mutex.
14734 */
14735 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
14736   if( p ){
14737     sqlite3GlobalConfig.mutex.xMutexFree(p);
14738   }
14739 }
14740
14741 /*
14742 ** Obtain the mutex p. If some other thread already has the mutex, block
14743 ** until it can be obtained.
14744 */
14745 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
14746   if( p ){
14747     sqlite3GlobalConfig.mutex.xMutexEnter(p);
14748   }
14749 }
14750
14751 /*
14752 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
14753 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
14754 */
14755 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
14756   int rc = SQLITE_OK;
14757   if( p ){
14758     return sqlite3GlobalConfig.mutex.xMutexTry(p);
14759   }
14760   return rc;
14761 }
14762
14763 /*
14764 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
14765 ** entered by the same thread.  The behavior is undefined if the mutex 
14766 ** is not currently entered. If a NULL pointer is passed as an argument
14767 ** this function is a no-op.
14768 */
14769 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
14770   if( p ){
14771     sqlite3GlobalConfig.mutex.xMutexLeave(p);
14772   }
14773 }
14774
14775 #ifndef NDEBUG
14776 /*
14777 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
14778 ** intended for use inside assert() statements.
14779 */
14780 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
14781   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
14782 }
14783 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
14784   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
14785 }
14786 #endif
14787
14788 #endif
14789
14790 #ifdef SQLITE_MUTEX_NOOP_DEBUG
14791 /*
14792 ** In this implementation, mutexes do not provide any mutual exclusion.
14793 ** But the error checking is provided.  This implementation is useful
14794 ** for test purposes.
14795 */
14796
14797 /*
14798 ** The mutex object
14799 */
14800 struct sqlite3_mutex {
14801   int id;     /* The mutex type */
14802   int cnt;    /* Number of entries without a matching leave */
14803 };
14804
14805 /*
14806 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
14807 ** intended for use inside assert() statements.
14808 */
14809 static int noopMutexHeld(sqlite3_mutex *p){
14810   return p==0 || p->cnt>0;
14811 }
14812 static int noopMutexNotheld(sqlite3_mutex *p){
14813   return p==0 || p->cnt==0;
14814 }
14815
14816 /*
14817 ** Initialize and deinitialize the mutex subsystem.
14818 */
14819 static int noopMutexInit(void){ return SQLITE_OK; }
14820 static int noopMutexEnd(void){ return SQLITE_OK; }
14821
14822 /*
14823 ** The sqlite3_mutex_alloc() routine allocates a new
14824 ** mutex and returns a pointer to it.  If it returns NULL
14825 ** that means that a mutex could not be allocated. 
14826 */
14827 static sqlite3_mutex *noopMutexAlloc(int id){
14828   static sqlite3_mutex aStatic[6];
14829   sqlite3_mutex *pNew = 0;
14830   switch( id ){
14831     case SQLITE_MUTEX_FAST:
14832     case SQLITE_MUTEX_RECURSIVE: {
14833       pNew = sqlite3Malloc(sizeof(*pNew));
14834       if( pNew ){
14835         pNew->id = id;
14836         pNew->cnt = 0;
14837       }
14838       break;
14839     }
14840     default: {
14841       assert( id-2 >= 0 );
14842       assert( id-2 < sizeof(aStatic)/sizeof(aStatic[0]) );
14843       pNew = &aStatic[id-2];
14844       pNew->id = id;
14845       break;
14846     }
14847   }
14848   return pNew;
14849 }
14850
14851 /*
14852 ** This routine deallocates a previously allocated mutex.
14853 */
14854 static void noopMutexFree(sqlite3_mutex *p){
14855   assert( p->cnt==0 );
14856   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
14857   sqlite3_free(p);
14858 }
14859
14860 /*
14861 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
14862 ** to enter a mutex.  If another thread is already within the mutex,
14863 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
14864 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
14865 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
14866 ** be entered multiple times by the same thread.  In such cases the,
14867 ** mutex must be exited an equal number of times before another thread
14868 ** can enter.  If the same thread tries to enter any other kind of mutex
14869 ** more than once, the behavior is undefined.
14870 */
14871 static void noopMutexEnter(sqlite3_mutex *p){
14872   assert( p->id==SQLITE_MUTEX_RECURSIVE || noopMutexNotheld(p) );
14873   p->cnt++;
14874 }
14875 static int noopMutexTry(sqlite3_mutex *p){
14876   assert( p->id==SQLITE_MUTEX_RECURSIVE || noopMutexNotheld(p) );
14877   p->cnt++;
14878   return SQLITE_OK;
14879 }
14880
14881 /*
14882 ** The sqlite3_mutex_leave() routine exits a mutex that was
14883 ** previously entered by the same thread.  The behavior
14884 ** is undefined if the mutex is not currently entered or
14885 ** is not currently allocated.  SQLite will never do either.
14886 */
14887 static void noopMutexLeave(sqlite3_mutex *p){
14888   assert( noopMutexHeld(p) );
14889   p->cnt--;
14890   assert( p->id==SQLITE_MUTEX_RECURSIVE || noopMutexNotheld(p) );
14891 }
14892
14893 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
14894   static sqlite3_mutex_methods sMutex = {
14895     noopMutexInit,
14896     noopMutexEnd,
14897     noopMutexAlloc,
14898     noopMutexFree,
14899     noopMutexEnter,
14900     noopMutexTry,
14901     noopMutexLeave,
14902
14903     noopMutexHeld,
14904     noopMutexNotheld
14905   };
14906
14907   return &sMutex;
14908 }
14909 #endif /* SQLITE_MUTEX_NOOP_DEBUG */
14910
14911 /************** End of mutex.c ***********************************************/
14912 /************** Begin file mutex_os2.c ***************************************/
14913 /*
14914 ** 2007 August 28
14915 **
14916 ** The author disclaims copyright to this source code.  In place of
14917 ** a legal notice, here is a blessing:
14918 **
14919 **    May you do good and not evil.
14920 **    May you find forgiveness for yourself and forgive others.
14921 **    May you share freely, never taking more than you give.
14922 **
14923 *************************************************************************
14924 ** This file contains the C functions that implement mutexes for OS/2
14925 **
14926 ** $Id: mutex_os2.c,v 1.10 2008/06/23 22:13:28 pweilbacher Exp $
14927 */
14928
14929 /*
14930 ** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
14931 ** See the mutex.h file for details.
14932 */
14933 #ifdef SQLITE_MUTEX_OS2
14934
14935 /********************** OS/2 Mutex Implementation **********************
14936 **
14937 ** This implementation of mutexes is built using the OS/2 API.
14938 */
14939
14940 /*
14941 ** The mutex object
14942 ** Each recursive mutex is an instance of the following structure.
14943 */
14944 struct sqlite3_mutex {
14945   HMTX mutex;       /* Mutex controlling the lock */
14946   int  id;          /* Mutex type */
14947   int  nRef;        /* Number of references */
14948   TID  owner;       /* Thread holding this mutex */
14949 };
14950
14951 #define OS2_MUTEX_INITIALIZER   0,0,0,0
14952
14953 /*
14954 ** Initialize and deinitialize the mutex subsystem.
14955 */
14956 static int os2MutexInit(void){ return SQLITE_OK; }
14957 static int os2MutexEnd(void){ return SQLITE_OK; }
14958
14959 /*
14960 ** The sqlite3_mutex_alloc() routine allocates a new
14961 ** mutex and returns a pointer to it.  If it returns NULL
14962 ** that means that a mutex could not be allocated. 
14963 ** SQLite will unwind its stack and return an error.  The argument
14964 ** to sqlite3_mutex_alloc() is one of these integer constants:
14965 **
14966 ** <ul>
14967 ** <li>  SQLITE_MUTEX_FAST               0
14968 ** <li>  SQLITE_MUTEX_RECURSIVE          1
14969 ** <li>  SQLITE_MUTEX_STATIC_MASTER      2
14970 ** <li>  SQLITE_MUTEX_STATIC_MEM         3
14971 ** <li>  SQLITE_MUTEX_STATIC_PRNG        4
14972 ** </ul>
14973 **
14974 ** The first two constants cause sqlite3_mutex_alloc() to create
14975 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
14976 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
14977 ** The mutex implementation does not need to make a distinction
14978 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
14979 ** not want to.  But SQLite will only request a recursive mutex in
14980 ** cases where it really needs one.  If a faster non-recursive mutex
14981 ** implementation is available on the host platform, the mutex subsystem
14982 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
14983 **
14984 ** The other allowed parameters to sqlite3_mutex_alloc() each return
14985 ** a pointer to a static preexisting mutex.  Three static mutexes are
14986 ** used by the current version of SQLite.  Future versions of SQLite
14987 ** may add additional static mutexes.  Static mutexes are for internal
14988 ** use by SQLite only.  Applications that use SQLite mutexes should
14989 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
14990 ** SQLITE_MUTEX_RECURSIVE.
14991 **
14992 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
14993 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
14994 ** returns a different mutex on every call.  But for the static
14995 ** mutex types, the same mutex is returned on every call that has
14996 ** the same type number.
14997 */
14998 static sqlite3_mutex *os2MutexAlloc(int iType){
14999   sqlite3_mutex *p = NULL;
15000   switch( iType ){
15001     case SQLITE_MUTEX_FAST:
15002     case SQLITE_MUTEX_RECURSIVE: {
15003       p = sqlite3MallocZero( sizeof(*p) );
15004       if( p ){
15005         p->id = iType;
15006         if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
15007           sqlite3_free( p );
15008           p = NULL;
15009         }
15010       }
15011       break;
15012     }
15013     default: {
15014       static volatile int isInit = 0;
15015       static sqlite3_mutex staticMutexes[] = {
15016         { OS2_MUTEX_INITIALIZER, },
15017         { OS2_MUTEX_INITIALIZER, },
15018         { OS2_MUTEX_INITIALIZER, },
15019         { OS2_MUTEX_INITIALIZER, },
15020         { OS2_MUTEX_INITIALIZER, },
15021         { OS2_MUTEX_INITIALIZER, },
15022       };
15023       if ( !isInit ){
15024         APIRET rc;
15025         PTIB ptib;
15026         PPIB ppib;
15027         HMTX mutex;
15028         char name[32];
15029         DosGetInfoBlocks( &ptib, &ppib );
15030         sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
15031                           ppib->pib_ulpid );
15032         while( !isInit ){
15033           mutex = 0;
15034           rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
15035           if( rc == NO_ERROR ){
15036             int i;
15037             if( !isInit ){
15038               for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
15039                 DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
15040               }
15041               isInit = 1;
15042             }
15043             DosCloseMutexSem( mutex );
15044           }else if( rc == ERROR_DUPLICATE_NAME ){
15045             DosSleep( 1 );
15046           }else{
15047             return p;
15048           }
15049         }
15050       }
15051       assert( iType-2 >= 0 );
15052       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
15053       p = &staticMutexes[iType-2];
15054       p->id = iType;
15055       break;
15056     }
15057   }
15058   return p;
15059 }
15060
15061
15062 /*
15063 ** This routine deallocates a previously allocated mutex.
15064 ** SQLite is careful to deallocate every mutex that it allocates.
15065 */
15066 static void os2MutexFree(sqlite3_mutex *p){
15067   if( p==0 ) return;
15068   assert( p->nRef==0 );
15069   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15070   DosCloseMutexSem( p->mutex );
15071   sqlite3_free( p );
15072 }
15073
15074 /*
15075 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15076 ** to enter a mutex.  If another thread is already within the mutex,
15077 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15078 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15079 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15080 ** be entered multiple times by the same thread.  In such cases the,
15081 ** mutex must be exited an equal number of times before another thread
15082 ** can enter.  If the same thread tries to enter any other kind of mutex
15083 ** more than once, the behavior is undefined.
15084 */
15085 static void os2MutexEnter(sqlite3_mutex *p){
15086   TID tid;
15087   PID holder1;
15088   ULONG holder2;
15089   if( p==0 ) return;
15090   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
15091   DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
15092   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
15093   p->owner = tid;
15094   p->nRef++;
15095 }
15096 static int os2MutexTry(sqlite3_mutex *p){
15097   int rc;
15098   TID tid;
15099   PID holder1;
15100   ULONG holder2;
15101   if( p==0 ) return SQLITE_OK;
15102   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
15103   if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR) {
15104     DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
15105     p->owner = tid;
15106     p->nRef++;
15107     rc = SQLITE_OK;
15108   } else {
15109     rc = SQLITE_BUSY;
15110   }
15111
15112   return rc;
15113 }
15114
15115 /*
15116 ** The sqlite3_mutex_leave() routine exits a mutex that was
15117 ** previously entered by the same thread.  The behavior
15118 ** is undefined if the mutex is not currently entered or
15119 ** is not currently allocated.  SQLite will never do either.
15120 */
15121 static void os2MutexLeave(sqlite3_mutex *p){
15122   TID tid;
15123   PID holder1;
15124   ULONG holder2;
15125   if( p==0 ) return;
15126   assert( p->nRef>0 );
15127   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
15128   assert( p->owner==tid );
15129   p->nRef--;
15130   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
15131   DosReleaseMutexSem(p->mutex);
15132 }
15133
15134 #ifdef SQLITE_DEBUG
15135 /*
15136 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15137 ** intended for use inside assert() statements.
15138 */
15139 static int os2MutexHeld(sqlite3_mutex *p){
15140   TID tid;
15141   PID pid;
15142   ULONG ulCount;
15143   PTIB ptib;
15144   if( p!=0 ) {
15145     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
15146   } else {
15147     DosGetInfoBlocks(&ptib, NULL);
15148     tid = ptib->tib_ptib2->tib2_ultid;
15149   }
15150   return p==0 || (p->nRef!=0 && p->owner==tid);
15151 }
15152 static int os2MutexNotheld(sqlite3_mutex *p){
15153   TID tid;
15154   PID pid;
15155   ULONG ulCount;
15156   PTIB ptib;
15157   if( p!= 0 ) {
15158     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
15159   } else {
15160     DosGetInfoBlocks(&ptib, NULL);
15161     tid = ptib->tib_ptib2->tib2_ultid;
15162   }
15163   return p==0 || p->nRef==0 || p->owner!=tid;
15164 }
15165 #endif
15166
15167 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15168   static sqlite3_mutex_methods sMutex = {
15169     os2MutexInit,
15170     os2MutexEnd,
15171     os2MutexAlloc,
15172     os2MutexFree,
15173     os2MutexEnter,
15174     os2MutexTry,
15175     os2MutexLeave,
15176 #ifdef SQLITE_DEBUG
15177     os2MutexHeld,
15178     os2MutexNotheld
15179 #endif
15180   };
15181
15182   return &sMutex;
15183 }
15184 #endif /* SQLITE_MUTEX_OS2 */
15185
15186 /************** End of mutex_os2.c *******************************************/
15187 /************** Begin file mutex_unix.c **************************************/
15188 /*
15189 ** 2007 August 28
15190 **
15191 ** The author disclaims copyright to this source code.  In place of
15192 ** a legal notice, here is a blessing:
15193 **
15194 **    May you do good and not evil.
15195 **    May you find forgiveness for yourself and forgive others.
15196 **    May you share freely, never taking more than you give.
15197 **
15198 *************************************************************************
15199 ** This file contains the C functions that implement mutexes for pthreads
15200 **
15201 ** $Id: mutex_unix.c,v 1.13 2008/07/16 12:33:24 drh Exp $
15202 */
15203
15204 /*
15205 ** The code in this file is only used if we are compiling threadsafe
15206 ** under unix with pthreads.
15207 **
15208 ** Note that this implementation requires a version of pthreads that
15209 ** supports recursive mutexes.
15210 */
15211 #ifdef SQLITE_MUTEX_PTHREADS
15212
15213 #include <pthread.h>
15214
15215
15216 /*
15217 ** Each recursive mutex is an instance of the following structure.
15218 */
15219 struct sqlite3_mutex {
15220   pthread_mutex_t mutex;     /* Mutex controlling the lock */
15221   int id;                    /* Mutex type */
15222   int nRef;                  /* Number of entrances */
15223   pthread_t owner;           /* Thread that is within this mutex */
15224 #ifdef SQLITE_DEBUG
15225   int trace;                 /* True to trace changes */
15226 #endif
15227 };
15228 #ifdef SQLITE_DEBUG
15229 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
15230 #else
15231 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0 }
15232 #endif
15233
15234 /*
15235 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15236 ** intended for use only inside assert() statements.  On some platforms,
15237 ** there might be race conditions that can cause these routines to
15238 ** deliver incorrect results.  In particular, if pthread_equal() is
15239 ** not an atomic operation, then these routines might delivery
15240 ** incorrect results.  On most platforms, pthread_equal() is a 
15241 ** comparison of two integers and is therefore atomic.  But we are
15242 ** told that HPUX is not such a platform.  If so, then these routines
15243 ** will not always work correctly on HPUX.
15244 **
15245 ** On those platforms where pthread_equal() is not atomic, SQLite
15246 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
15247 ** make sure no assert() statements are evaluated and hence these
15248 ** routines are never called.
15249 */
15250 #ifndef NDEBUG
15251 static int pthreadMutexHeld(sqlite3_mutex *p){
15252   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
15253 }
15254 static int pthreadMutexNotheld(sqlite3_mutex *p){
15255   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
15256 }
15257 #endif
15258
15259 /*
15260 ** Initialize and deinitialize the mutex subsystem.
15261 */
15262 static int pthreadMutexInit(void){ return SQLITE_OK; }
15263 static int pthreadMutexEnd(void){ return SQLITE_OK; }
15264
15265 /*
15266 ** The sqlite3_mutex_alloc() routine allocates a new
15267 ** mutex and returns a pointer to it.  If it returns NULL
15268 ** that means that a mutex could not be allocated.  SQLite
15269 ** will unwind its stack and return an error.  The argument
15270 ** to sqlite3_mutex_alloc() is one of these integer constants:
15271 **
15272 ** <ul>
15273 ** <li>  SQLITE_MUTEX_FAST
15274 ** <li>  SQLITE_MUTEX_RECURSIVE
15275 ** <li>  SQLITE_MUTEX_STATIC_MASTER
15276 ** <li>  SQLITE_MUTEX_STATIC_MEM
15277 ** <li>  SQLITE_MUTEX_STATIC_MEM2
15278 ** <li>  SQLITE_MUTEX_STATIC_PRNG
15279 ** <li>  SQLITE_MUTEX_STATIC_LRU
15280 ** </ul>
15281 **
15282 ** The first two constants cause sqlite3_mutex_alloc() to create
15283 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15284 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15285 ** The mutex implementation does not need to make a distinction
15286 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15287 ** not want to.  But SQLite will only request a recursive mutex in
15288 ** cases where it really needs one.  If a faster non-recursive mutex
15289 ** implementation is available on the host platform, the mutex subsystem
15290 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
15291 **
15292 ** The other allowed parameters to sqlite3_mutex_alloc() each return
15293 ** a pointer to a static preexisting mutex.  Three static mutexes are
15294 ** used by the current version of SQLite.  Future versions of SQLite
15295 ** may add additional static mutexes.  Static mutexes are for internal
15296 ** use by SQLite only.  Applications that use SQLite mutexes should
15297 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15298 ** SQLITE_MUTEX_RECURSIVE.
15299 **
15300 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15301 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15302 ** returns a different mutex on every call.  But for the static 
15303 ** mutex types, the same mutex is returned on every call that has
15304 ** the same type number.
15305 */
15306 static sqlite3_mutex *pthreadMutexAlloc(int iType){
15307   static sqlite3_mutex staticMutexes[] = {
15308     SQLITE3_MUTEX_INITIALIZER,
15309     SQLITE3_MUTEX_INITIALIZER,
15310     SQLITE3_MUTEX_INITIALIZER,
15311     SQLITE3_MUTEX_INITIALIZER,
15312     SQLITE3_MUTEX_INITIALIZER,
15313     SQLITE3_MUTEX_INITIALIZER
15314   };
15315   sqlite3_mutex *p;
15316   switch( iType ){
15317     case SQLITE_MUTEX_RECURSIVE: {
15318       p = sqlite3MallocZero( sizeof(*p) );
15319       if( p ){
15320 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15321         /* If recursive mutexes are not available, we will have to
15322         ** build our own.  See below. */
15323         pthread_mutex_init(&p->mutex, 0);
15324 #else
15325         /* Use a recursive mutex if it is available */
15326         pthread_mutexattr_t recursiveAttr;
15327         pthread_mutexattr_init(&recursiveAttr);
15328         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
15329         pthread_mutex_init(&p->mutex, &recursiveAttr);
15330         pthread_mutexattr_destroy(&recursiveAttr);
15331 #endif
15332         p->id = iType;
15333       }
15334       break;
15335     }
15336     case SQLITE_MUTEX_FAST: {
15337       p = sqlite3MallocZero( sizeof(*p) );
15338       if( p ){
15339         p->id = iType;
15340         pthread_mutex_init(&p->mutex, 0);
15341       }
15342       break;
15343     }
15344     default: {
15345       assert( iType-2 >= 0 );
15346       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
15347       p = &staticMutexes[iType-2];
15348       p->id = iType;
15349       break;
15350     }
15351   }
15352   return p;
15353 }
15354
15355
15356 /*
15357 ** This routine deallocates a previously
15358 ** allocated mutex.  SQLite is careful to deallocate every
15359 ** mutex that it allocates.
15360 */
15361 static void pthreadMutexFree(sqlite3_mutex *p){
15362   assert( p->nRef==0 );
15363   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15364   pthread_mutex_destroy(&p->mutex);
15365   sqlite3_free(p);
15366 }
15367
15368 /*
15369 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15370 ** to enter a mutex.  If another thread is already within the mutex,
15371 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15372 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15373 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15374 ** be entered multiple times by the same thread.  In such cases the,
15375 ** mutex must be exited an equal number of times before another thread
15376 ** can enter.  If the same thread tries to enter any other kind of mutex
15377 ** more than once, the behavior is undefined.
15378 */
15379 static void pthreadMutexEnter(sqlite3_mutex *p){
15380   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
15381
15382 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15383   /* If recursive mutexes are not available, then we have to grow
15384   ** our own.  This implementation assumes that pthread_equal()
15385   ** is atomic - that it cannot be deceived into thinking self
15386   ** and p->owner are equal if p->owner changes between two values
15387   ** that are not equal to self while the comparison is taking place.
15388   ** This implementation also assumes a coherent cache - that 
15389   ** separate processes cannot read different values from the same
15390   ** address at the same time.  If either of these two conditions
15391   ** are not met, then the mutexes will fail and problems will result.
15392   */
15393   {
15394     pthread_t self = pthread_self();
15395     if( p->nRef>0 && pthread_equal(p->owner, self) ){
15396       p->nRef++;
15397     }else{
15398       pthread_mutex_lock(&p->mutex);
15399       assert( p->nRef==0 );
15400       p->owner = self;
15401       p->nRef = 1;
15402     }
15403   }
15404 #else
15405   /* Use the built-in recursive mutexes if they are available.
15406   */
15407   pthread_mutex_lock(&p->mutex);
15408   p->owner = pthread_self();
15409   p->nRef++;
15410 #endif
15411
15412 #ifdef SQLITE_DEBUG
15413   if( p->trace ){
15414     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15415   }
15416 #endif
15417 }
15418 static int pthreadMutexTry(sqlite3_mutex *p){
15419   int rc;
15420   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
15421
15422 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15423   /* If recursive mutexes are not available, then we have to grow
15424   ** our own.  This implementation assumes that pthread_equal()
15425   ** is atomic - that it cannot be deceived into thinking self
15426   ** and p->owner are equal if p->owner changes between two values
15427   ** that are not equal to self while the comparison is taking place.
15428   ** This implementation also assumes a coherent cache - that 
15429   ** separate processes cannot read different values from the same
15430   ** address at the same time.  If either of these two conditions
15431   ** are not met, then the mutexes will fail and problems will result.
15432   */
15433   {
15434     pthread_t self = pthread_self();
15435     if( p->nRef>0 && pthread_equal(p->owner, self) ){
15436       p->nRef++;
15437       rc = SQLITE_OK;
15438     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
15439       assert( p->nRef==0 );
15440       p->owner = self;
15441       p->nRef = 1;
15442       rc = SQLITE_OK;
15443     }else{
15444       rc = SQLITE_BUSY;
15445     }
15446   }
15447 #else
15448   /* Use the built-in recursive mutexes if they are available.
15449   */
15450   if( pthread_mutex_trylock(&p->mutex)==0 ){
15451     p->owner = pthread_self();
15452     p->nRef++;
15453     rc = SQLITE_OK;
15454   }else{
15455     rc = SQLITE_BUSY;
15456   }
15457 #endif
15458
15459 #ifdef SQLITE_DEBUG
15460   if( rc==SQLITE_OK && p->trace ){
15461     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15462   }
15463 #endif
15464   return rc;
15465 }
15466
15467 /*
15468 ** The sqlite3_mutex_leave() routine exits a mutex that was
15469 ** previously entered by the same thread.  The behavior
15470 ** is undefined if the mutex is not currently entered or
15471 ** is not currently allocated.  SQLite will never do either.
15472 */
15473 static void pthreadMutexLeave(sqlite3_mutex *p){
15474   assert( pthreadMutexHeld(p) );
15475   p->nRef--;
15476   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
15477
15478 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15479   if( p->nRef==0 ){
15480     pthread_mutex_unlock(&p->mutex);
15481   }
15482 #else
15483   pthread_mutex_unlock(&p->mutex);
15484 #endif
15485
15486 #ifdef SQLITE_DEBUG
15487   if( p->trace ){
15488     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15489   }
15490 #endif
15491 }
15492
15493 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15494   static sqlite3_mutex_methods sMutex = {
15495     pthreadMutexInit,
15496     pthreadMutexEnd,
15497     pthreadMutexAlloc,
15498     pthreadMutexFree,
15499     pthreadMutexEnter,
15500     pthreadMutexTry,
15501     pthreadMutexLeave,
15502 #ifdef SQLITE_DEBUG
15503     pthreadMutexHeld,
15504     pthreadMutexNotheld
15505 #endif
15506   };
15507
15508   return &sMutex;
15509 }
15510
15511 #endif /* SQLITE_MUTEX_PTHREAD */
15512
15513 /************** End of mutex_unix.c ******************************************/
15514 /************** Begin file mutex_w32.c ***************************************/
15515 /*
15516 ** 2007 August 14
15517 **
15518 ** The author disclaims copyright to this source code.  In place of
15519 ** a legal notice, here is a blessing:
15520 **
15521 **    May you do good and not evil.
15522 **    May you find forgiveness for yourself and forgive others.
15523 **    May you share freely, never taking more than you give.
15524 **
15525 *************************************************************************
15526 ** This file contains the C functions that implement mutexes for win32
15527 **
15528 ** $Id: mutex_w32.c,v 1.11 2008/06/26 10:41:19 danielk1977 Exp $
15529 */
15530
15531 /*
15532 ** The code in this file is only used if we are compiling multithreaded
15533 ** on a win32 system.
15534 */
15535 #ifdef SQLITE_MUTEX_W32
15536
15537 /*
15538 ** Each recursive mutex is an instance of the following structure.
15539 */
15540 struct sqlite3_mutex {
15541   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
15542   int id;                    /* Mutex type */
15543   int nRef;                  /* Number of enterances */
15544   DWORD owner;               /* Thread holding this mutex */
15545 };
15546
15547 /*
15548 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
15549 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
15550 **
15551 ** Here is an interesting observation:  Win95, Win98, and WinME lack
15552 ** the LockFileEx() API.  But we can still statically link against that
15553 ** API as long as we don't call it win running Win95/98/ME.  A call to
15554 ** this routine is used to determine if the host is Win95/98/ME or
15555 ** WinNT/2K/XP so that we will know whether or not we can safely call
15556 ** the LockFileEx() API.
15557 */
15558 #if SQLITE_OS_WINCE
15559 # define mutexIsNT()  (1)
15560 #else
15561   static int mutexIsNT(void){
15562     static int osType = 0;
15563     if( osType==0 ){
15564       OSVERSIONINFO sInfo;
15565       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
15566       GetVersionEx(&sInfo);
15567       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
15568     }
15569     return osType==2;
15570   }
15571 #endif /* SQLITE_OS_WINCE */
15572
15573
15574 #ifdef SQLITE_DEBUG
15575 /*
15576 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15577 ** intended for use only inside assert() statements.
15578 */
15579 static int winMutexHeld(sqlite3_mutex *p){
15580   return p->nRef!=0 && p->owner==GetCurrentThreadId();
15581 }
15582 static int winMutexNotheld(sqlite3_mutex *p){
15583   return p->nRef==0 || p->owner!=GetCurrentThreadId();
15584 }
15585 #endif
15586
15587
15588 /*
15589 ** Initialize and deinitialize the mutex subsystem.
15590 */
15591 static int winMutexInit(void){ return SQLITE_OK; }
15592 static int winMutexEnd(void){ return SQLITE_OK; }
15593
15594 /*
15595 ** The sqlite3_mutex_alloc() routine allocates a new
15596 ** mutex and returns a pointer to it.  If it returns NULL
15597 ** that means that a mutex could not be allocated.  SQLite
15598 ** will unwind its stack and return an error.  The argument
15599 ** to sqlite3_mutex_alloc() is one of these integer constants:
15600 **
15601 ** <ul>
15602 ** <li>  SQLITE_MUTEX_FAST               0
15603 ** <li>  SQLITE_MUTEX_RECURSIVE          1
15604 ** <li>  SQLITE_MUTEX_STATIC_MASTER      2
15605 ** <li>  SQLITE_MUTEX_STATIC_MEM         3
15606 ** <li>  SQLITE_MUTEX_STATIC_PRNG        4
15607 ** </ul>
15608 **
15609 ** The first two constants cause sqlite3_mutex_alloc() to create
15610 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15611 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15612 ** The mutex implementation does not need to make a distinction
15613 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15614 ** not want to.  But SQLite will only request a recursive mutex in
15615 ** cases where it really needs one.  If a faster non-recursive mutex
15616 ** implementation is available on the host platform, the mutex subsystem
15617 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
15618 **
15619 ** The other allowed parameters to sqlite3_mutex_alloc() each return
15620 ** a pointer to a static preexisting mutex.  Three static mutexes are
15621 ** used by the current version of SQLite.  Future versions of SQLite
15622 ** may add additional static mutexes.  Static mutexes are for internal
15623 ** use by SQLite only.  Applications that use SQLite mutexes should
15624 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15625 ** SQLITE_MUTEX_RECURSIVE.
15626 **
15627 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15628 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15629 ** returns a different mutex on every call.  But for the static 
15630 ** mutex types, the same mutex is returned on every call that has
15631 ** the same type number.
15632 */
15633 static sqlite3_mutex *winMutexAlloc(int iType){
15634   sqlite3_mutex *p;
15635
15636   switch( iType ){
15637     case SQLITE_MUTEX_FAST:
15638     case SQLITE_MUTEX_RECURSIVE: {
15639       p = sqlite3MallocZero( sizeof(*p) );
15640       if( p ){
15641         p->id = iType;
15642         InitializeCriticalSection(&p->mutex);
15643       }
15644       break;
15645     }
15646     default: {
15647       static sqlite3_mutex staticMutexes[6];
15648       static int isInit = 0;
15649       while( !isInit ){
15650         static long lock = 0;
15651         if( InterlockedIncrement(&lock)==1 ){
15652           int i;
15653           for(i=0; i<sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++){
15654             InitializeCriticalSection(&staticMutexes[i].mutex);
15655           }
15656           isInit = 1;
15657         }else{
15658           Sleep(1);
15659         }
15660       }
15661       assert( iType-2 >= 0 );
15662       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
15663       p = &staticMutexes[iType-2];
15664       p->id = iType;
15665       break;
15666     }
15667   }
15668   return p;
15669 }
15670
15671
15672 /*
15673 ** This routine deallocates a previously
15674 ** allocated mutex.  SQLite is careful to deallocate every
15675 ** mutex that it allocates.
15676 */
15677 static void winMutexFree(sqlite3_mutex *p){
15678   assert( p );
15679   assert( p->nRef==0 );
15680   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15681   DeleteCriticalSection(&p->mutex);
15682   sqlite3_free(p);
15683 }
15684
15685 /*
15686 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15687 ** to enter a mutex.  If another thread is already within the mutex,
15688 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15689 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15690 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15691 ** be entered multiple times by the same thread.  In such cases the,
15692 ** mutex must be exited an equal number of times before another thread
15693 ** can enter.  If the same thread tries to enter any other kind of mutex
15694 ** more than once, the behavior is undefined.
15695 */
15696 static void winMutexEnter(sqlite3_mutex *p){
15697   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) );
15698   EnterCriticalSection(&p->mutex);
15699   p->owner = GetCurrentThreadId(); 
15700   p->nRef++;
15701 }
15702 static int winMutexTry(sqlite3_mutex *p){
15703   int rc = SQLITE_BUSY;
15704   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) );
15705   /*
15706   ** The sqlite3_mutex_try() routine is very rarely used, and when it
15707   ** is used it is merely an optimization.  So it is OK for it to always
15708   ** fail.  
15709   **
15710   ** The TryEnterCriticalSection() interface is only available on WinNT.
15711   ** And some windows compilers complain if you try to use it without
15712   ** first doing some #defines that prevent SQLite from building on Win98.
15713   ** For that reason, we will omit this optimization for now.  See
15714   ** ticket #2685.
15715   */
15716 #if 0
15717   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
15718     p->owner = GetCurrentThreadId();
15719     p->nRef++;
15720     rc = SQLITE_OK;
15721   }
15722 #endif
15723   return rc;
15724 }
15725
15726 /*
15727 ** The sqlite3_mutex_leave() routine exits a mutex that was
15728 ** previously entered by the same thread.  The behavior
15729 ** is undefined if the mutex is not currently entered or
15730 ** is not currently allocated.  SQLite will never do either.
15731 */
15732 static void winMutexLeave(sqlite3_mutex *p){
15733   assert( p->nRef>0 );
15734   assert( p->owner==GetCurrentThreadId() );
15735   p->nRef--;
15736   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
15737   LeaveCriticalSection(&p->mutex);
15738 }
15739
15740 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15741   static sqlite3_mutex_methods sMutex = {
15742     winMutexInit,
15743     winMutexEnd,
15744     winMutexAlloc,
15745     winMutexFree,
15746     winMutexEnter,
15747     winMutexTry,
15748     winMutexLeave,
15749 #ifdef SQLITE_DEBUG
15750     winMutexHeld,
15751     winMutexNotheld
15752 #endif
15753   };
15754
15755   return &sMutex;
15756 }
15757 #endif /* SQLITE_MUTEX_W32 */
15758
15759 /************** End of mutex_w32.c *******************************************/
15760 /************** Begin file malloc.c ******************************************/
15761 /*
15762 ** 2001 September 15
15763 **
15764 ** The author disclaims copyright to this source code.  In place of
15765 ** a legal notice, here is a blessing:
15766 **
15767 **    May you do good and not evil.
15768 **    May you find forgiveness for yourself and forgive others.
15769 **    May you share freely, never taking more than you give.
15770 **
15771 *************************************************************************
15772 **
15773 ** Memory allocation functions used throughout sqlite.
15774 **
15775 ** $Id: malloc.c,v 1.41 2008/09/04 04:32:49 shane Exp $
15776 */
15777
15778 /*
15779 ** This routine runs when the memory allocator sees that the
15780 ** total memory allocation is about to exceed the soft heap
15781 ** limit.
15782 */
15783 static void softHeapLimitEnforcer(
15784   void *NotUsed, 
15785   sqlite3_int64 inUse,
15786   int allocSize
15787 ){
15788   sqlite3_release_memory(allocSize);
15789 }
15790
15791 /*
15792 ** Set the soft heap-size limit for the library. Passing a zero or 
15793 ** negative value indicates no limit.
15794 */
15795 SQLITE_API void sqlite3_soft_heap_limit(int n){
15796   sqlite3_uint64 iLimit;
15797   int overage;
15798   if( n<0 ){
15799     iLimit = 0;
15800   }else{
15801     iLimit = n;
15802   }
15803   sqlite3_initialize();
15804   if( iLimit>0 ){
15805     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, iLimit);
15806   }else{
15807     sqlite3MemoryAlarm(0, 0, 0);
15808   }
15809   overage = sqlite3_memory_used() - n;
15810   if( overage>0 ){
15811     sqlite3_release_memory(overage);
15812   }
15813 }
15814
15815 /*
15816 ** Attempt to release up to n bytes of non-essential memory currently
15817 ** held by SQLite. An example of non-essential memory is memory used to
15818 ** cache database pages that are not currently in use.
15819 */
15820 SQLITE_API int sqlite3_release_memory(int n){
15821 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
15822   int nRet = 0;
15823 #if 0
15824   nRet += sqlite3VdbeReleaseMemory(n);
15825 #endif
15826   nRet += sqlite3PcacheReleaseMemory(n-nRet);
15827   return nRet;
15828 #else
15829   return SQLITE_OK;
15830 #endif
15831 }
15832
15833 /*
15834 ** State information local to the memory allocation subsystem.
15835 */
15836 static SQLITE_WSD struct Mem0Global {
15837   /* Number of free pages for scratch and page-cache memory */
15838   u32 nScratchFree;
15839   u32 nPageFree;
15840
15841   sqlite3_mutex *mutex;         /* Mutex to serialize access */
15842
15843   /*
15844   ** The alarm callback and its arguments.  The mem0.mutex lock will
15845   ** be held while the callback is running.  Recursive calls into
15846   ** the memory subsystem are allowed, but no new callbacks will be
15847   ** issued.  The alarmBusy variable is set to prevent recursive
15848   ** callbacks.
15849   */
15850   sqlite3_int64 alarmThreshold;
15851   void (*alarmCallback)(void*, sqlite3_int64,int);
15852   void *alarmArg;
15853   int alarmBusy;
15854
15855   /*
15856   ** Pointers to the end of sqlite3GlobalConfig.pScratch and
15857   ** sqlite3GlobalConfig.pPage to a block of memory that records
15858   ** which pages are available.
15859   */
15860   u32 *aScratchFree;
15861   u32 *aPageFree;
15862 } mem0 = { 62560955 };
15863
15864 #define mem0 GLOBAL(struct Mem0Global, mem0)
15865
15866 /*
15867 ** Initialize the memory allocation subsystem.
15868 */
15869 SQLITE_PRIVATE int sqlite3MallocInit(void){
15870   if( sqlite3GlobalConfig.m.xMalloc==0 ){
15871     sqlite3MemSetDefault();
15872   }
15873   memset(&mem0, 0, sizeof(mem0));
15874   if( sqlite3GlobalConfig.bCoreMutex ){
15875     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15876   }
15877   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
15878       && sqlite3GlobalConfig.nScratch>=0 ){
15879     int i;
15880     sqlite3GlobalConfig.szScratch -= 4;
15881     mem0.aScratchFree = (u32*)&((char*)sqlite3GlobalConfig.pScratch)
15882                   [sqlite3GlobalConfig.szScratch*sqlite3GlobalConfig.nScratch];
15883     for(i=0; i<sqlite3GlobalConfig.nScratch; i++){ mem0.aScratchFree[i] = i; }
15884     mem0.nScratchFree = sqlite3GlobalConfig.nScratch;
15885   }else{
15886     sqlite3GlobalConfig.pScratch = 0;
15887     sqlite3GlobalConfig.szScratch = 0;
15888   }
15889   if( sqlite3GlobalConfig.pPage && sqlite3GlobalConfig.szPage>=512
15890       && sqlite3GlobalConfig.nPage>=1 ){
15891     int i;
15892     int overhead;
15893     int sz = sqlite3GlobalConfig.szPage;
15894     int n = sqlite3GlobalConfig.nPage;
15895     overhead = (4*n + sz - 1)/sz;
15896     sqlite3GlobalConfig.nPage -= overhead;
15897     mem0.aPageFree = (u32*)&((char*)sqlite3GlobalConfig.pPage)
15898                   [sqlite3GlobalConfig.szPage*sqlite3GlobalConfig.nPage];
15899     for(i=0; i<sqlite3GlobalConfig.nPage; i++){ mem0.aPageFree[i] = i; }
15900     mem0.nPageFree = sqlite3GlobalConfig.nPage;
15901   }else{
15902     sqlite3GlobalConfig.pPage = 0;
15903     sqlite3GlobalConfig.szPage = 0;
15904   }
15905   return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
15906 }
15907
15908 /*
15909 ** Deinitialize the memory allocation subsystem.
15910 */
15911 SQLITE_PRIVATE void sqlite3MallocEnd(void){
15912   sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
15913   memset(&mem0, 0, sizeof(mem0));
15914 }
15915
15916 /*
15917 ** Return the amount of memory currently checked out.
15918 */
15919 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
15920   int n, mx;
15921   sqlite3_int64 res;
15922   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
15923   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
15924   return res;
15925 }
15926
15927 /*
15928 ** Return the maximum amount of memory that has ever been
15929 ** checked out since either the beginning of this process
15930 ** or since the most recent reset.
15931 */
15932 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
15933   int n, mx;
15934   sqlite3_int64 res;
15935   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
15936   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
15937   return res;
15938 }
15939
15940 /*
15941 ** Change the alarm callback
15942 */
15943 SQLITE_PRIVATE int sqlite3MemoryAlarm(
15944   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
15945   void *pArg,
15946   sqlite3_int64 iThreshold
15947 ){
15948   sqlite3_mutex_enter(mem0.mutex);
15949   mem0.alarmCallback = xCallback;
15950   mem0.alarmArg = pArg;
15951   mem0.alarmThreshold = iThreshold;
15952   sqlite3_mutex_leave(mem0.mutex);
15953   return SQLITE_OK;
15954 }
15955
15956 /*
15957 ** Deprecated external interface.  Internal/core SQLite code
15958 ** should call sqlite3MemoryAlarm.
15959 */
15960 SQLITE_API int sqlite3_memory_alarm(
15961   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
15962   void *pArg,
15963   sqlite3_int64 iThreshold
15964 ){
15965   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
15966 }
15967
15968 /*
15969 ** Trigger the alarm 
15970 */
15971 static void sqlite3MallocAlarm(int nByte){
15972   void (*xCallback)(void*,sqlite3_int64,int);
15973   sqlite3_int64 nowUsed;
15974   void *pArg;
15975   if( mem0.alarmCallback==0 || mem0.alarmBusy  ) return;
15976   mem0.alarmBusy = 1;
15977   xCallback = mem0.alarmCallback;
15978   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
15979   pArg = mem0.alarmArg;
15980   sqlite3_mutex_leave(mem0.mutex);
15981   xCallback(pArg, nowUsed, nByte);
15982   sqlite3_mutex_enter(mem0.mutex);
15983   mem0.alarmBusy = 0;
15984 }
15985
15986 /*
15987 ** Do a memory allocation with statistics and alarms.  Assume the
15988 ** lock is already held.
15989 */
15990 static int mallocWithAlarm(int n, void **pp){
15991   int nFull;
15992   void *p;
15993   assert( sqlite3_mutex_held(mem0.mutex) );
15994   nFull = sqlite3GlobalConfig.m.xRoundup(n);
15995   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
15996   if( mem0.alarmCallback!=0 ){
15997     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
15998     if( nUsed+nFull >= mem0.alarmThreshold ){
15999       sqlite3MallocAlarm(nFull);
16000     }
16001   }
16002   p = sqlite3GlobalConfig.m.xMalloc(nFull);
16003   if( p==0 && mem0.alarmCallback ){
16004     sqlite3MallocAlarm(nFull);
16005     p = sqlite3GlobalConfig.m.xMalloc(nFull);
16006   }
16007   if( p ){
16008     nFull = sqlite3MallocSize(p);
16009     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
16010   }
16011   *pp = p;
16012   return nFull;
16013 }
16014
16015 /*
16016 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
16017 ** assumes the memory subsystem has already been initialized.
16018 */
16019 SQLITE_PRIVATE void *sqlite3Malloc(int n){
16020   void *p;
16021   if( n<=0 ){
16022     p = 0;
16023   }else if( sqlite3GlobalConfig.bMemstat ){
16024     sqlite3_mutex_enter(mem0.mutex);
16025     mallocWithAlarm(n, &p);
16026     sqlite3_mutex_leave(mem0.mutex);
16027   }else{
16028     p = sqlite3GlobalConfig.m.xMalloc(n);
16029   }
16030   return p;
16031 }
16032
16033 /*
16034 ** This version of the memory allocation is for use by the application.
16035 ** First make sure the memory subsystem is initialized, then do the
16036 ** allocation.
16037 */
16038 SQLITE_API void *sqlite3_malloc(int n){
16039 #ifndef SQLITE_OMIT_AUTOINIT
16040   if( sqlite3_initialize() ) return 0;
16041 #endif
16042   return sqlite3Malloc(n);
16043 }
16044
16045 /*
16046 ** Each thread may only have a single outstanding allocation from
16047 ** xScratchMalloc().  We verify this constraint in the single-threaded
16048 ** case by setting scratchAllocOut to 1 when an allocation
16049 ** is outstanding clearing it when the allocation is freed.
16050 */
16051 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16052 static int scratchAllocOut = 0;
16053 #endif
16054
16055
16056 /*
16057 ** Allocate memory that is to be used and released right away.
16058 ** This routine is similar to alloca() in that it is not intended
16059 ** for situations where the memory might be held long-term.  This
16060 ** routine is intended to get memory to old large transient data
16061 ** structures that would not normally fit on the stack of an
16062 ** embedded processor.
16063 */
16064 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
16065   void *p;
16066   assert( n>0 );
16067
16068 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16069   /* Verify that no more than one scratch allocation per thread
16070   ** is outstanding at one time.  (This is only checked in the
16071   ** single-threaded case since checking in the multi-threaded case
16072   ** would be much more complicated.) */
16073   assert( scratchAllocOut==0 );
16074 #endif
16075
16076   if( sqlite3GlobalConfig.szScratch<n ){
16077     goto scratch_overflow;
16078   }else{  
16079     sqlite3_mutex_enter(mem0.mutex);
16080     if( mem0.nScratchFree==0 ){
16081       sqlite3_mutex_leave(mem0.mutex);
16082       goto scratch_overflow;
16083     }else{
16084       int i;
16085       i = mem0.aScratchFree[--mem0.nScratchFree];
16086       i *= sqlite3GlobalConfig.szScratch;
16087       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
16088       sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
16089       sqlite3_mutex_leave(mem0.mutex);
16090       p = (void*)&((char*)sqlite3GlobalConfig.pScratch)[i];
16091     }
16092   }
16093 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16094   scratchAllocOut = p!=0;
16095 #endif
16096
16097   return p;
16098
16099 scratch_overflow:
16100   if( sqlite3GlobalConfig.bMemstat ){
16101     sqlite3_mutex_enter(mem0.mutex);
16102     sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
16103     n = mallocWithAlarm(n, &p);
16104     if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
16105     sqlite3_mutex_leave(mem0.mutex);
16106   }else{
16107     p = sqlite3GlobalConfig.m.xMalloc(n);
16108   }
16109 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16110   scratchAllocOut = p!=0;
16111 #endif
16112   return p;    
16113 }
16114 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
16115   if( p ){
16116
16117 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16118     /* Verify that no more than one scratch allocation per thread
16119     ** is outstanding at one time.  (This is only checked in the
16120     ** single-threaded case since checking in the multi-threaded case
16121     ** would be much more complicated.) */
16122     assert( scratchAllocOut==1 );
16123     scratchAllocOut = 0;
16124 #endif
16125
16126     if( sqlite3GlobalConfig.pScratch==0
16127            || p<sqlite3GlobalConfig.pScratch
16128            || p>=(void*)mem0.aScratchFree ){
16129       if( sqlite3GlobalConfig.bMemstat ){
16130         int iSize = sqlite3MallocSize(p);
16131         sqlite3_mutex_enter(mem0.mutex);
16132         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
16133         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
16134         sqlite3GlobalConfig.m.xFree(p);
16135         sqlite3_mutex_leave(mem0.mutex);
16136       }else{
16137         sqlite3GlobalConfig.m.xFree(p);
16138       }
16139     }else{
16140       int i;
16141       i = (u8 *)p - (u8 *)sqlite3GlobalConfig.pScratch;
16142       i /= sqlite3GlobalConfig.szScratch;
16143       assert( i>=0 && i<sqlite3GlobalConfig.nScratch );
16144       sqlite3_mutex_enter(mem0.mutex);
16145       assert( mem0.nScratchFree<sqlite3GlobalConfig.nScratch );
16146       mem0.aScratchFree[mem0.nScratchFree++] = i;
16147       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
16148       sqlite3_mutex_leave(mem0.mutex);
16149     }
16150   }
16151 }
16152
16153 /*
16154 ** Allocate memory to be used by the page cache.  Make use of the
16155 ** memory buffer provided by SQLITE_CONFIG_PAGECACHE if there is one
16156 ** and that memory is of the right size and is not completely
16157 ** consumed.  Otherwise, failover to sqlite3Malloc().
16158 */
16159 #if 0
16160 SQLITE_PRIVATE void *sqlite3PageMalloc(int n){
16161   void *p;
16162   assert( n>0 );
16163   assert( (n & (n-1))==0 );
16164   assert( n>=512 && n<=32768 );
16165
16166   if( sqlite3GlobalConfig.szPage<n ){
16167     goto page_overflow;
16168   }else{  
16169     sqlite3_mutex_enter(mem0.mutex);
16170     if( mem0.nPageFree==0 ){
16171       sqlite3_mutex_leave(mem0.mutex);
16172       goto page_overflow;
16173     }else{
16174       int i;
16175       i = mem0.aPageFree[--mem0.nPageFree];
16176       sqlite3_mutex_leave(mem0.mutex);
16177       i *= sqlite3GlobalConfig.szPage;
16178       sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, n);
16179       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
16180       p = (void*)&((char*)sqlite3GlobalConfig.pPage)[i];
16181     }
16182   }
16183   return p;
16184
16185 page_overflow:
16186   if( sqlite3GlobalConfig.bMemstat ){
16187     sqlite3_mutex_enter(mem0.mutex);
16188     sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, n);
16189     n = mallocWithAlarm(n, &p);
16190     if( p ) sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, n);
16191     sqlite3_mutex_leave(mem0.mutex);
16192   }else{
16193     p = sqlite3GlobalConfig.m.xMalloc(n);
16194   }
16195   return p;    
16196 }
16197 SQLITE_PRIVATE void sqlite3PageFree(void *p){
16198   if( p ){
16199     if( sqlite3GlobalConfig.pPage==0
16200            || p<sqlite3GlobalConfig.pPage
16201            || p>=(void*)mem0.aPageFree ){
16202       /* In this case, the page allocation was obtained from a regular 
16203       ** call to sqlite3_mem_methods.xMalloc() (a page-cache-memory 
16204       ** "overflow"). Free the block with sqlite3_mem_methods.xFree().
16205       */
16206       if( sqlite3GlobalConfig.bMemstat ){
16207         int iSize = sqlite3MallocSize(p);
16208         sqlite3_mutex_enter(mem0.mutex);
16209         sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
16210         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
16211         sqlite3GlobalConfig.m.xFree(p);
16212         sqlite3_mutex_leave(mem0.mutex);
16213       }else{
16214         sqlite3GlobalConfig.m.xFree(p);
16215       }
16216     }else{
16217       /* The page allocation was allocated from the sqlite3GlobalConfig.pPage
16218       ** buffer. In this case all that is add the index of the page in
16219       ** the sqlite3GlobalConfig.pPage array to the set of free indexes stored
16220       ** in the mem0.aPageFree[] array.
16221       */
16222       int i;
16223       i = (u8 *)p - (u8 *)sqlite3GlobalConfig.pPage;
16224       i /= sqlite3GlobalConfig.szPage;
16225       assert( i>=0 && i<sqlite3GlobalConfig.nPage );
16226       sqlite3_mutex_enter(mem0.mutex);
16227       assert( mem0.nPageFree<sqlite3GlobalConfig.nPage );
16228       mem0.aPageFree[mem0.nPageFree++] = i;
16229       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
16230       sqlite3_mutex_leave(mem0.mutex);
16231 #if !defined(NDEBUG) && 0
16232       /* Assert that a duplicate was not just inserted into aPageFree[]. */
16233       for(i=0; i<mem0.nPageFree-1; i++){
16234         assert( mem0.aPageFree[i]!=mem0.aPageFree[mem0.nPageFree-1] );
16235       }
16236 #endif
16237     }
16238   }
16239 }
16240 #endif
16241
16242 /*
16243 ** TRUE if p is a lookaside memory allocation from db
16244 */
16245 static int isLookaside(sqlite3 *db, void *p){
16246   return db && p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
16247 }
16248
16249 /*
16250 ** Return the size of a memory allocation previously obtained from
16251 ** sqlite3Malloc() or sqlite3_malloc().
16252 */
16253 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
16254   return sqlite3GlobalConfig.m.xSize(p);
16255 }
16256 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
16257   if( isLookaside(db, p) ){
16258     return db->lookaside.sz;
16259   }else{
16260     return sqlite3GlobalConfig.m.xSize(p);
16261   }
16262 }
16263
16264 /*
16265 ** Free memory previously obtained from sqlite3Malloc().
16266 */
16267 SQLITE_API void sqlite3_free(void *p){
16268   if( p==0 ) return;
16269   if( sqlite3GlobalConfig.bMemstat ){
16270     sqlite3_mutex_enter(mem0.mutex);
16271     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
16272     sqlite3GlobalConfig.m.xFree(p);
16273     sqlite3_mutex_leave(mem0.mutex);
16274   }else{
16275     sqlite3GlobalConfig.m.xFree(p);
16276   }
16277 }
16278
16279 /*
16280 ** Free memory that might be associated with a particular database
16281 ** connection.
16282 */
16283 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
16284   if( isLookaside(db, p) ){
16285     LookasideSlot *pBuf = (LookasideSlot*)p;
16286     pBuf->pNext = db->lookaside.pFree;
16287     db->lookaside.pFree = pBuf;
16288     db->lookaside.nOut--;
16289   }else{
16290     sqlite3_free(p);
16291   }
16292 }
16293
16294 /*
16295 ** Change the size of an existing memory allocation
16296 */
16297 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
16298   int nOld, nNew;
16299   void *pNew;
16300   if( pOld==0 ){
16301     return sqlite3Malloc(nBytes);
16302   }
16303   if( nBytes<=0 ){
16304     sqlite3_free(pOld);
16305     return 0;
16306   }
16307   nOld = sqlite3MallocSize(pOld);
16308   if( sqlite3GlobalConfig.bMemstat ){
16309     sqlite3_mutex_enter(mem0.mutex);
16310     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
16311     nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
16312     if( nOld==nNew ){
16313       pNew = pOld;
16314     }else{
16315       if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >= 
16316             mem0.alarmThreshold ){
16317         sqlite3MallocAlarm(nNew-nOld);
16318       }
16319       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
16320       if( pNew==0 && mem0.alarmCallback ){
16321         sqlite3MallocAlarm(nBytes);
16322         pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
16323       }
16324       if( pNew ){
16325         nNew = sqlite3MallocSize(pNew);
16326         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
16327       }
16328     }
16329     sqlite3_mutex_leave(mem0.mutex);
16330   }else{
16331     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nBytes);
16332   }
16333   return pNew;
16334 }
16335
16336 /*
16337 ** The public interface to sqlite3Realloc.  Make sure that the memory
16338 ** subsystem is initialized prior to invoking sqliteRealloc.
16339 */
16340 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
16341 #ifndef SQLITE_OMIT_AUTOINIT
16342   if( sqlite3_initialize() ) return 0;
16343 #endif
16344   return sqlite3Realloc(pOld, n);
16345 }
16346
16347
16348 /*
16349 ** Allocate and zero memory.
16350 */ 
16351 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
16352   void *p = sqlite3Malloc(n);
16353   if( p ){
16354     memset(p, 0, n);
16355   }
16356   return p;
16357 }
16358
16359 /*
16360 ** Allocate and zero memory.  If the allocation fails, make
16361 ** the mallocFailed flag in the connection pointer.
16362 */
16363 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
16364   void *p = sqlite3DbMallocRaw(db, n);
16365   if( p ){
16366     memset(p, 0, n);
16367   }
16368   return p;
16369 }
16370
16371 /*
16372 ** Allocate and zero memory.  If the allocation fails, make
16373 ** the mallocFailed flag in the connection pointer.
16374 */
16375 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
16376   void *p;
16377   if( db ){
16378     LookasideSlot *pBuf;
16379     if( db->mallocFailed ){
16380       return 0;
16381     }
16382     if( db->lookaside.bEnabled && n<=db->lookaside.sz
16383          && (pBuf = db->lookaside.pFree)!=0 ){
16384       db->lookaside.pFree = pBuf->pNext;
16385       db->lookaside.nOut++;
16386       if( db->lookaside.nOut>db->lookaside.mxOut ){
16387         db->lookaside.mxOut = db->lookaside.nOut;
16388       }
16389       return (void*)pBuf;
16390     }
16391   }
16392   p = sqlite3Malloc(n);
16393   if( !p && db ){
16394     db->mallocFailed = 1;
16395   }
16396   return p;
16397 }
16398
16399 /*
16400 ** Resize the block of memory pointed to by p to n bytes. If the
16401 ** resize fails, set the mallocFailed flag in the connection object.
16402 */
16403 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
16404   void *pNew = 0;
16405   if( db->mallocFailed==0 ){
16406     if( p==0 ){
16407       return sqlite3DbMallocRaw(db, n);
16408     }
16409     if( isLookaside(db, p) ){
16410       if( n<=db->lookaside.sz ){
16411         return p;
16412       }
16413       pNew = sqlite3DbMallocRaw(db, n);
16414       if( pNew ){
16415         memcpy(pNew, p, db->lookaside.sz);
16416         sqlite3DbFree(db, p);
16417       }
16418     }else{
16419       pNew = sqlite3_realloc(p, n);
16420       if( !pNew ){
16421         db->mallocFailed = 1;
16422       }
16423     }
16424   }
16425   return pNew;
16426 }
16427
16428 /*
16429 ** Attempt to reallocate p.  If the reallocation fails, then free p
16430 ** and set the mallocFailed flag in the database connection.
16431 */
16432 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
16433   void *pNew;
16434   pNew = sqlite3DbRealloc(db, p, n);
16435   if( !pNew ){
16436     sqlite3DbFree(db, p);
16437   }
16438   return pNew;
16439 }
16440
16441 /*
16442 ** Make a copy of a string in memory obtained from sqliteMalloc(). These 
16443 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
16444 ** is because when memory debugging is turned on, these two functions are 
16445 ** called via macros that record the current file and line number in the
16446 ** ThreadData structure.
16447 */
16448 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
16449   char *zNew;
16450   size_t n;
16451   if( z==0 ){
16452     return 0;
16453   }
16454   n = strlen(z)+1;
16455   assert( (n&0x7fffffff)==n );
16456   zNew = sqlite3DbMallocRaw(db, (int)n);
16457   if( zNew ){
16458     memcpy(zNew, z, n);
16459   }
16460   return zNew;
16461 }
16462 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
16463   char *zNew;
16464   if( z==0 ){
16465     return 0;
16466   }
16467   assert( (n&0x7fffffff)==n );
16468   zNew = sqlite3DbMallocRaw(db, n+1);
16469   if( zNew ){
16470     memcpy(zNew, z, n);
16471     zNew[n] = 0;
16472   }
16473   return zNew;
16474 }
16475
16476 /*
16477 ** Create a string from the zFromat argument and the va_list that follows.
16478 ** Store the string in memory obtained from sqliteMalloc() and make *pz
16479 ** point to that string.
16480 */
16481 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
16482   va_list ap;
16483   char *z;
16484
16485   va_start(ap, zFormat);
16486   z = sqlite3VMPrintf(db, zFormat, ap);
16487   va_end(ap);
16488   sqlite3DbFree(db, *pz);
16489   *pz = z;
16490 }
16491
16492
16493 /*
16494 ** This function must be called before exiting any API function (i.e. 
16495 ** returning control to the user) that has called sqlite3_malloc or
16496 ** sqlite3_realloc.
16497 **
16498 ** The returned value is normally a copy of the second argument to this
16499 ** function. However, if a malloc() failure has occured since the previous
16500 ** invocation SQLITE_NOMEM is returned instead. 
16501 **
16502 ** If the first argument, db, is not NULL and a malloc() error has occured,
16503 ** then the connection error-code (the value returned by sqlite3_errcode())
16504 ** is set to SQLITE_NOMEM.
16505 */
16506 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
16507   /* If the db handle is not NULL, then we must hold the connection handle
16508   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
16509   ** is unsafe, as is the call to sqlite3Error().
16510   */
16511   assert( !db || sqlite3_mutex_held(db->mutex) );
16512   if( db && db->mallocFailed ){
16513     sqlite3Error(db, SQLITE_NOMEM, 0);
16514     db->mallocFailed = 0;
16515     rc = SQLITE_NOMEM;
16516   }
16517   return rc & (db ? db->errMask : 0xff);
16518 }
16519
16520 /************** End of malloc.c **********************************************/
16521 /************** Begin file printf.c ******************************************/
16522 /*
16523 ** The "printf" code that follows dates from the 1980's.  It is in
16524 ** the public domain.  The original comments are included here for
16525 ** completeness.  They are very out-of-date but might be useful as
16526 ** an historical reference.  Most of the "enhancements" have been backed
16527 ** out so that the functionality is now the same as standard printf().
16528 **
16529 ** $Id: printf.c,v 1.94 2008/08/22 14:08:36 drh Exp $
16530 **
16531 **************************************************************************
16532 **
16533 ** The following modules is an enhanced replacement for the "printf" subroutines
16534 ** found in the standard C library.  The following enhancements are
16535 ** supported:
16536 **
16537 **      +  Additional functions.  The standard set of "printf" functions
16538 **         includes printf, fprintf, sprintf, vprintf, vfprintf, and
16539 **         vsprintf.  This module adds the following:
16540 **
16541 **           *  snprintf -- Works like sprintf, but has an extra argument
16542 **                          which is the size of the buffer written to.
16543 **
16544 **           *  mprintf --  Similar to sprintf.  Writes output to memory
16545 **                          obtained from malloc.
16546 **
16547 **           *  xprintf --  Calls a function to dispose of output.
16548 **
16549 **           *  nprintf --  No output, but returns the number of characters
16550 **                          that would have been output by printf.
16551 **
16552 **           *  A v- version (ex: vsnprintf) of every function is also
16553 **              supplied.
16554 **
16555 **      +  A few extensions to the formatting notation are supported:
16556 **
16557 **           *  The "=" flag (similar to "-") causes the output to be
16558 **              be centered in the appropriately sized field.
16559 **
16560 **           *  The %b field outputs an integer in binary notation.
16561 **
16562 **           *  The %c field now accepts a precision.  The character output
16563 **              is repeated by the number of times the precision specifies.
16564 **
16565 **           *  The %' field works like %c, but takes as its character the
16566 **              next character of the format string, instead of the next
16567 **              argument.  For example,  printf("%.78'-")  prints 78 minus
16568 **              signs, the same as  printf("%.78c",'-').
16569 **
16570 **      +  When compiled using GCC on a SPARC, this version of printf is
16571 **         faster than the library printf for SUN OS 4.1.
16572 **
16573 **      +  All functions are fully reentrant.
16574 **
16575 */
16576
16577 /*
16578 ** Conversion types fall into various categories as defined by the
16579 ** following enumeration.
16580 */
16581 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
16582 #define etFLOAT       2 /* Floating point.  %f */
16583 #define etEXP         3 /* Exponentional notation. %e and %E */
16584 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
16585 #define etSIZE        5 /* Return number of characters processed so far. %n */
16586 #define etSTRING      6 /* Strings. %s */
16587 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
16588 #define etPERCENT     8 /* Percent symbol. %% */
16589 #define etCHARX       9 /* Characters. %c */
16590 /* The rest are extensions, not normally found in printf() */
16591 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
16592 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
16593                           NULL pointers replaced by SQL NULL.  %Q */
16594 #define etTOKEN      12 /* a pointer to a Token structure */
16595 #define etSRCLIST    13 /* a pointer to a SrcList */
16596 #define etPOINTER    14 /* The %p conversion */
16597 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
16598 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
16599
16600
16601 /*
16602 ** An "etByte" is an 8-bit unsigned value.
16603 */
16604 typedef unsigned char etByte;
16605
16606 /*
16607 ** Each builtin conversion character (ex: the 'd' in "%d") is described
16608 ** by an instance of the following structure
16609 */
16610 typedef struct et_info {   /* Information about each format field */
16611   char fmttype;            /* The format field code letter */
16612   etByte base;             /* The base for radix conversion */
16613   etByte flags;            /* One or more of FLAG_ constants below */
16614   etByte type;             /* Conversion paradigm */
16615   etByte charset;          /* Offset into aDigits[] of the digits string */
16616   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
16617 } et_info;
16618
16619 /*
16620 ** Allowed values for et_info.flags
16621 */
16622 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
16623 #define FLAG_INTERN  2     /* True if for internal use only */
16624 #define FLAG_STRING  4     /* Allow infinity precision */
16625
16626
16627 /*
16628 ** The following table is searched linearly, so it is good to put the
16629 ** most frequently used conversion types first.
16630 */
16631 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
16632 static const char aPrefix[] = "-x0\000X0";
16633 static const et_info fmtinfo[] = {
16634   {  'd', 10, 1, etRADIX,      0,  0 },
16635   {  's',  0, 4, etSTRING,     0,  0 },
16636   {  'g',  0, 1, etGENERIC,    30, 0 },
16637   {  'z',  0, 4, etDYNSTRING,  0,  0 },
16638   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
16639   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
16640   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
16641   {  'c',  0, 0, etCHARX,      0,  0 },
16642   {  'o',  8, 0, etRADIX,      0,  2 },
16643   {  'u', 10, 0, etRADIX,      0,  0 },
16644   {  'x', 16, 0, etRADIX,      16, 1 },
16645   {  'X', 16, 0, etRADIX,      0,  4 },
16646 #ifndef SQLITE_OMIT_FLOATING_POINT
16647   {  'f',  0, 1, etFLOAT,      0,  0 },
16648   {  'e',  0, 1, etEXP,        30, 0 },
16649   {  'E',  0, 1, etEXP,        14, 0 },
16650   {  'G',  0, 1, etGENERIC,    14, 0 },
16651 #endif
16652   {  'i', 10, 1, etRADIX,      0,  0 },
16653   {  'n',  0, 0, etSIZE,       0,  0 },
16654   {  '%',  0, 0, etPERCENT,    0,  0 },
16655   {  'p', 16, 0, etPOINTER,    0,  1 },
16656   {  'T',  0, 2, etTOKEN,      0,  0 },
16657   {  'S',  0, 2, etSRCLIST,    0,  0 },
16658   {  'r', 10, 3, etORDINAL,    0,  0 },
16659 };
16660 #define etNINFO  (sizeof(fmtinfo)/sizeof(fmtinfo[0]))
16661
16662 /*
16663 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
16664 ** conversions will work.
16665 */
16666 #ifndef SQLITE_OMIT_FLOATING_POINT
16667 /*
16668 ** "*val" is a double such that 0.1 <= *val < 10.0
16669 ** Return the ascii code for the leading digit of *val, then
16670 ** multiply "*val" by 10.0 to renormalize.
16671 **
16672 ** Example:
16673 **     input:     *val = 3.14159
16674 **     output:    *val = 1.4159    function return = '3'
16675 **
16676 ** The counter *cnt is incremented each time.  After counter exceeds
16677 ** 16 (the number of significant digits in a 64-bit float) '0' is
16678 ** always returned.
16679 */
16680 static int et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
16681   int digit;
16682   LONGDOUBLE_TYPE d;
16683   if( (*cnt)++ >= 16 ) return '0';
16684   digit = (int)*val;
16685   d = digit;
16686   digit += '0';
16687   *val = (*val - d)*10.0;
16688   return digit;
16689 }
16690 #endif /* SQLITE_OMIT_FLOATING_POINT */
16691
16692 /*
16693 ** Append N space characters to the given string buffer.
16694 */
16695 static void appendSpace(StrAccum *pAccum, int N){
16696   static const char zSpaces[] = "                             ";
16697   while( N>=sizeof(zSpaces)-1 ){
16698     sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
16699     N -= sizeof(zSpaces)-1;
16700   }
16701   if( N>0 ){
16702     sqlite3StrAccumAppend(pAccum, zSpaces, N);
16703   }
16704 }
16705
16706 /*
16707 ** On machines with a small stack size, you can redefine the
16708 ** SQLITE_PRINT_BUF_SIZE to be less than 350.  But beware - for
16709 ** smaller values some %f conversions may go into an infinite loop.
16710 */
16711 #ifndef SQLITE_PRINT_BUF_SIZE
16712 # define SQLITE_PRINT_BUF_SIZE 350
16713 #endif
16714 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
16715
16716 /*
16717 ** The root program.  All variations call this core.
16718 **
16719 ** INPUTS:
16720 **   func   This is a pointer to a function taking three arguments
16721 **            1. A pointer to anything.  Same as the "arg" parameter.
16722 **            2. A pointer to the list of characters to be output
16723 **               (Note, this list is NOT null terminated.)
16724 **            3. An integer number of characters to be output.
16725 **               (Note: This number might be zero.)
16726 **
16727 **   arg    This is the pointer to anything which will be passed as the
16728 **          first argument to "func".  Use it for whatever you like.
16729 **
16730 **   fmt    This is the format string, as in the usual print.
16731 **
16732 **   ap     This is a pointer to a list of arguments.  Same as in
16733 **          vfprint.
16734 **
16735 ** OUTPUTS:
16736 **          The return value is the total number of characters sent to
16737 **          the function "func".  Returns -1 on a error.
16738 **
16739 ** Note that the order in which automatic variables are declared below
16740 ** seems to make a big difference in determining how fast this beast
16741 ** will run.
16742 */
16743 SQLITE_PRIVATE void sqlite3VXPrintf(
16744   StrAccum *pAccum,                  /* Accumulate results here */
16745   int useExtended,                   /* Allow extended %-conversions */
16746   const char *fmt,                   /* Format string */
16747   va_list ap                         /* arguments */
16748 ){
16749   int c;                     /* Next character in the format string */
16750   char *bufpt;               /* Pointer to the conversion buffer */
16751   int precision;             /* Precision of the current field */
16752   int length;                /* Length of the field */
16753   int idx;                   /* A general purpose loop counter */
16754   int width;                 /* Width of the current field */
16755   etByte flag_leftjustify;   /* True if "-" flag is present */
16756   etByte flag_plussign;      /* True if "+" flag is present */
16757   etByte flag_blanksign;     /* True if " " flag is present */
16758   etByte flag_alternateform; /* True if "#" flag is present */
16759   etByte flag_altform2;      /* True if "!" flag is present */
16760   etByte flag_zeropad;       /* True if field width constant starts with zero */
16761   etByte flag_long;          /* True if "l" flag is present */
16762   etByte flag_longlong;      /* True if the "ll" flag is present */
16763   etByte done;               /* Loop termination flag */
16764   sqlite_uint64 longvalue;   /* Value for integer types */
16765   LONGDOUBLE_TYPE realvalue; /* Value for real types */
16766   const et_info *infop;      /* Pointer to the appropriate info structure */
16767   char buf[etBUFSIZE];       /* Conversion buffer */
16768   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
16769   etByte xtype;              /* Conversion paradigm */
16770   char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
16771 #ifndef SQLITE_OMIT_FLOATING_POINT
16772   int  exp, e2;              /* exponent of real numbers */
16773   double rounder;            /* Used for rounding floating point values */
16774   etByte flag_dp;            /* True if decimal point should be shown */
16775   etByte flag_rtz;           /* True if trailing zeros should be removed */
16776   etByte flag_exp;           /* True to force display of the exponent */
16777   int nsd;                   /* Number of significant digits returned */
16778 #endif
16779
16780   length = 0;
16781   bufpt = 0;
16782   for(; (c=(*fmt))!=0; ++fmt){
16783     if( c!='%' ){
16784       int amt;
16785       bufpt = (char *)fmt;
16786       amt = 1;
16787       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
16788       sqlite3StrAccumAppend(pAccum, bufpt, amt);
16789       if( c==0 ) break;
16790     }
16791     if( (c=(*++fmt))==0 ){
16792       sqlite3StrAccumAppend(pAccum, "%", 1);
16793       break;
16794     }
16795     /* Find out what flags are present */
16796     flag_leftjustify = flag_plussign = flag_blanksign = 
16797      flag_alternateform = flag_altform2 = flag_zeropad = 0;
16798     done = 0;
16799     do{
16800       switch( c ){
16801         case '-':   flag_leftjustify = 1;     break;
16802         case '+':   flag_plussign = 1;        break;
16803         case ' ':   flag_blanksign = 1;       break;
16804         case '#':   flag_alternateform = 1;   break;
16805         case '!':   flag_altform2 = 1;        break;
16806         case '0':   flag_zeropad = 1;         break;
16807         default:    done = 1;                 break;
16808       }
16809     }while( !done && (c=(*++fmt))!=0 );
16810     /* Get the field width */
16811     width = 0;
16812     if( c=='*' ){
16813       width = va_arg(ap,int);
16814       if( width<0 ){
16815         flag_leftjustify = 1;
16816         width = -width;
16817       }
16818       c = *++fmt;
16819     }else{
16820       while( c>='0' && c<='9' ){
16821         width = width*10 + c - '0';
16822         c = *++fmt;
16823       }
16824     }
16825     if( width > etBUFSIZE-10 ){
16826       width = etBUFSIZE-10;
16827     }
16828     /* Get the precision */
16829     if( c=='.' ){
16830       precision = 0;
16831       c = *++fmt;
16832       if( c=='*' ){
16833         precision = va_arg(ap,int);
16834         if( precision<0 ) precision = -precision;
16835         c = *++fmt;
16836       }else{
16837         while( c>='0' && c<='9' ){
16838           precision = precision*10 + c - '0';
16839           c = *++fmt;
16840         }
16841       }
16842     }else{
16843       precision = -1;
16844     }
16845     /* Get the conversion type modifier */
16846     if( c=='l' ){
16847       flag_long = 1;
16848       c = *++fmt;
16849       if( c=='l' ){
16850         flag_longlong = 1;
16851         c = *++fmt;
16852       }else{
16853         flag_longlong = 0;
16854       }
16855     }else{
16856       flag_long = flag_longlong = 0;
16857     }
16858     /* Fetch the info entry for the field */
16859     infop = 0;
16860     for(idx=0; idx<etNINFO; idx++){
16861       if( c==fmtinfo[idx].fmttype ){
16862         infop = &fmtinfo[idx];
16863         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
16864           xtype = infop->type;
16865         }else{
16866           return;
16867         }
16868         break;
16869       }
16870     }
16871     zExtra = 0;
16872     if( infop==0 ){
16873       return;
16874     }
16875
16876
16877     /* Limit the precision to prevent overflowing buf[] during conversion */
16878     if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
16879       precision = etBUFSIZE-40;
16880     }
16881
16882     /*
16883     ** At this point, variables are initialized as follows:
16884     **
16885     **   flag_alternateform          TRUE if a '#' is present.
16886     **   flag_altform2               TRUE if a '!' is present.
16887     **   flag_plussign               TRUE if a '+' is present.
16888     **   flag_leftjustify            TRUE if a '-' is present or if the
16889     **                               field width was negative.
16890     **   flag_zeropad                TRUE if the width began with 0.
16891     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
16892     **                               the conversion character.
16893     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
16894     **                               the conversion character.
16895     **   flag_blanksign              TRUE if a ' ' is present.
16896     **   width                       The specified field width.  This is
16897     **                               always non-negative.  Zero is the default.
16898     **   precision                   The specified precision.  The default
16899     **                               is -1.
16900     **   xtype                       The class of the conversion.
16901     **   infop                       Pointer to the appropriate info struct.
16902     */
16903     switch( xtype ){
16904       case etPOINTER:
16905         flag_longlong = sizeof(char*)==sizeof(i64);
16906         flag_long = sizeof(char*)==sizeof(long int);
16907         /* Fall through into the next case */
16908       case etORDINAL:
16909       case etRADIX:
16910         if( infop->flags & FLAG_SIGNED ){
16911           i64 v;
16912           if( flag_longlong )   v = va_arg(ap,i64);
16913           else if( flag_long )  v = va_arg(ap,long int);
16914           else                  v = va_arg(ap,int);
16915           if( v<0 ){
16916             longvalue = -v;
16917             prefix = '-';
16918           }else{
16919             longvalue = v;
16920             if( flag_plussign )        prefix = '+';
16921             else if( flag_blanksign )  prefix = ' ';
16922             else                       prefix = 0;
16923           }
16924         }else{
16925           if( flag_longlong )   longvalue = va_arg(ap,u64);
16926           else if( flag_long )  longvalue = va_arg(ap,unsigned long int);
16927           else                  longvalue = va_arg(ap,unsigned int);
16928           prefix = 0;
16929         }
16930         if( longvalue==0 ) flag_alternateform = 0;
16931         if( flag_zeropad && precision<width-(prefix!=0) ){
16932           precision = width-(prefix!=0);
16933         }
16934         bufpt = &buf[etBUFSIZE-1];
16935         if( xtype==etORDINAL ){
16936           static const char zOrd[] = "thstndrd";
16937           int x = longvalue % 10;
16938           if( x>=4 || (longvalue/10)%10==1 ){
16939             x = 0;
16940           }
16941           buf[etBUFSIZE-3] = zOrd[x*2];
16942           buf[etBUFSIZE-2] = zOrd[x*2+1];
16943           bufpt -= 2;
16944         }
16945         {
16946           register const char *cset;      /* Use registers for speed */
16947           register int base;
16948           cset = &aDigits[infop->charset];
16949           base = infop->base;
16950           do{                                           /* Convert to ascii */
16951             *(--bufpt) = cset[longvalue%base];
16952             longvalue = longvalue/base;
16953           }while( longvalue>0 );
16954         }
16955         length = &buf[etBUFSIZE-1]-bufpt;
16956         for(idx=precision-length; idx>0; idx--){
16957           *(--bufpt) = '0';                             /* Zero pad */
16958         }
16959         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
16960         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
16961           const char *pre;
16962           char x;
16963           pre = &aPrefix[infop->prefix];
16964           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
16965         }
16966         length = &buf[etBUFSIZE-1]-bufpt;
16967         break;
16968       case etFLOAT:
16969       case etEXP:
16970       case etGENERIC:
16971         realvalue = va_arg(ap,double);
16972 #ifndef SQLITE_OMIT_FLOATING_POINT
16973         if( precision<0 ) precision = 6;         /* Set default precision */
16974         if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
16975         if( realvalue<0.0 ){
16976           realvalue = -realvalue;
16977           prefix = '-';
16978         }else{
16979           if( flag_plussign )          prefix = '+';
16980           else if( flag_blanksign )    prefix = ' ';
16981           else                         prefix = 0;
16982         }
16983         if( xtype==etGENERIC && precision>0 ) precision--;
16984 #if 0
16985         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
16986         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
16987 #else
16988         /* It makes more sense to use 0.5 */
16989         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
16990 #endif
16991         if( xtype==etFLOAT ) realvalue += rounder;
16992         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
16993         exp = 0;
16994         if( sqlite3IsNaN(realvalue) ){
16995           bufpt = "NaN";
16996           length = 3;
16997           break;
16998         }
16999         if( realvalue>0.0 ){
17000           while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
17001           while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
17002           while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
17003           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
17004           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
17005           if( exp>350 ){
17006             if( prefix=='-' ){
17007               bufpt = "-Inf";
17008             }else if( prefix=='+' ){
17009               bufpt = "+Inf";
17010             }else{
17011               bufpt = "Inf";
17012             }
17013             length = strlen(bufpt);
17014             break;
17015           }
17016         }
17017         bufpt = buf;
17018         /*
17019         ** If the field type is etGENERIC, then convert to either etEXP
17020         ** or etFLOAT, as appropriate.
17021         */
17022         flag_exp = xtype==etEXP;
17023         if( xtype!=etFLOAT ){
17024           realvalue += rounder;
17025           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
17026         }
17027         if( xtype==etGENERIC ){
17028           flag_rtz = !flag_alternateform;
17029           if( exp<-4 || exp>precision ){
17030             xtype = etEXP;
17031           }else{
17032             precision = precision - exp;
17033             xtype = etFLOAT;
17034           }
17035         }else{
17036           flag_rtz = 0;
17037         }
17038         if( xtype==etEXP ){
17039           e2 = 0;
17040         }else{
17041           e2 = exp;
17042         }
17043         nsd = 0;
17044         flag_dp = (precision>0) | flag_alternateform | flag_altform2;
17045         /* The sign in front of the number */
17046         if( prefix ){
17047           *(bufpt++) = prefix;
17048         }
17049         /* Digits prior to the decimal point */
17050         if( e2<0 ){
17051           *(bufpt++) = '0';
17052         }else{
17053           for(; e2>=0; e2--){
17054             *(bufpt++) = et_getdigit(&realvalue,&nsd);
17055           }
17056         }
17057         /* The decimal point */
17058         if( flag_dp ){
17059           *(bufpt++) = '.';
17060         }
17061         /* "0" digits after the decimal point but before the first
17062         ** significant digit of the number */
17063         for(e2++; e2<0; precision--, e2++){
17064           assert( precision>0 );
17065           *(bufpt++) = '0';
17066         }
17067         /* Significant digits after the decimal point */
17068         while( (precision--)>0 ){
17069           *(bufpt++) = et_getdigit(&realvalue,&nsd);
17070         }
17071         /* Remove trailing zeros and the "." if no digits follow the "." */
17072         if( flag_rtz && flag_dp ){
17073           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
17074           assert( bufpt>buf );
17075           if( bufpt[-1]=='.' ){
17076             if( flag_altform2 ){
17077               *(bufpt++) = '0';
17078             }else{
17079               *(--bufpt) = 0;
17080             }
17081           }
17082         }
17083         /* Add the "eNNN" suffix */
17084         if( flag_exp || xtype==etEXP ){
17085           *(bufpt++) = aDigits[infop->charset];
17086           if( exp<0 ){
17087             *(bufpt++) = '-'; exp = -exp;
17088           }else{
17089             *(bufpt++) = '+';
17090           }
17091           if( exp>=100 ){
17092             *(bufpt++) = (exp/100)+'0';                /* 100's digit */
17093             exp %= 100;
17094           }
17095           *(bufpt++) = exp/10+'0';                     /* 10's digit */
17096           *(bufpt++) = exp%10+'0';                     /* 1's digit */
17097         }
17098         *bufpt = 0;
17099
17100         /* The converted number is in buf[] and zero terminated. Output it.
17101         ** Note that the number is in the usual order, not reversed as with
17102         ** integer conversions. */
17103         length = bufpt-buf;
17104         bufpt = buf;
17105
17106         /* Special case:  Add leading zeros if the flag_zeropad flag is
17107         ** set and we are not left justified */
17108         if( flag_zeropad && !flag_leftjustify && length < width){
17109           int i;
17110           int nPad = width - length;
17111           for(i=width; i>=nPad; i--){
17112             bufpt[i] = bufpt[i-nPad];
17113           }
17114           i = prefix!=0;
17115           while( nPad-- ) bufpt[i++] = '0';
17116           length = width;
17117         }
17118 #endif
17119         break;
17120       case etSIZE:
17121         *(va_arg(ap,int*)) = pAccum->nChar;
17122         length = width = 0;
17123         break;
17124       case etPERCENT:
17125         buf[0] = '%';
17126         bufpt = buf;
17127         length = 1;
17128         break;
17129       case etCHARX:
17130         c = buf[0] = va_arg(ap,int);
17131         if( precision>=0 ){
17132           for(idx=1; idx<precision; idx++) buf[idx] = c;
17133           length = precision;
17134         }else{
17135           length =1;
17136         }
17137         bufpt = buf;
17138         break;
17139       case etSTRING:
17140       case etDYNSTRING:
17141         bufpt = va_arg(ap,char*);
17142         if( bufpt==0 ){
17143           bufpt = "";
17144         }else if( xtype==etDYNSTRING ){
17145           zExtra = bufpt;
17146         }
17147         if( precision>=0 ){
17148           for(length=0; length<precision && bufpt[length]; length++){}
17149         }else{
17150           length = strlen(bufpt);
17151         }
17152         break;
17153       case etSQLESCAPE:
17154       case etSQLESCAPE2:
17155       case etSQLESCAPE3: {
17156         int i, j, n, ch, isnull;
17157         int needQuote;
17158         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
17159         char *escarg = va_arg(ap,char*);
17160         isnull = escarg==0;
17161         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
17162         for(i=n=0; (ch=escarg[i])!=0; i++){
17163           if( ch==q )  n++;
17164         }
17165         needQuote = !isnull && xtype==etSQLESCAPE2;
17166         n += i + 1 + needQuote*2;
17167         if( n>etBUFSIZE ){
17168           bufpt = zExtra = sqlite3Malloc( n );
17169           if( bufpt==0 ) return;
17170         }else{
17171           bufpt = buf;
17172         }
17173         j = 0;
17174         if( needQuote ) bufpt[j++] = q;
17175         for(i=0; (ch=escarg[i])!=0; i++){
17176           bufpt[j++] = ch;
17177           if( ch==q ) bufpt[j++] = ch;
17178         }
17179         if( needQuote ) bufpt[j++] = q;
17180         bufpt[j] = 0;
17181         length = j;
17182         /* The precision is ignored on %q and %Q */
17183         /* if( precision>=0 && precision<length ) length = precision; */
17184         break;
17185       }
17186       case etTOKEN: {
17187         Token *pToken = va_arg(ap, Token*);
17188         if( pToken ){
17189           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
17190         }
17191         length = width = 0;
17192         break;
17193       }
17194       case etSRCLIST: {
17195         SrcList *pSrc = va_arg(ap, SrcList*);
17196         int k = va_arg(ap, int);
17197         struct SrcList_item *pItem = &pSrc->a[k];
17198         assert( k>=0 && k<pSrc->nSrc );
17199         if( pItem->zDatabase ){
17200           sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
17201           sqlite3StrAccumAppend(pAccum, ".", 1);
17202         }
17203         sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
17204         length = width = 0;
17205         break;
17206       }
17207     }/* End switch over the format type */
17208     /*
17209     ** The text of the conversion is pointed to by "bufpt" and is
17210     ** "length" characters long.  The field width is "width".  Do
17211     ** the output.
17212     */
17213     if( !flag_leftjustify ){
17214       register int nspace;
17215       nspace = width-length;
17216       if( nspace>0 ){
17217         appendSpace(pAccum, nspace);
17218       }
17219     }
17220     if( length>0 ){
17221       sqlite3StrAccumAppend(pAccum, bufpt, length);
17222     }
17223     if( flag_leftjustify ){
17224       register int nspace;
17225       nspace = width-length;
17226       if( nspace>0 ){
17227         appendSpace(pAccum, nspace);
17228       }
17229     }
17230     if( zExtra ){
17231       sqlite3_free(zExtra);
17232     }
17233   }/* End for loop over the format string */
17234 } /* End of function */
17235
17236 /*
17237 ** Append N bytes of text from z to the StrAccum object.
17238 */
17239 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
17240   if( p->tooBig | p->mallocFailed ){
17241     return;
17242   }
17243   if( N<0 ){
17244     N = strlen(z);
17245   }
17246   if( N==0 ){
17247     return;
17248   }
17249   if( p->nChar+N >= p->nAlloc ){
17250     char *zNew;
17251     if( !p->useMalloc ){
17252       p->tooBig = 1;
17253       N = p->nAlloc - p->nChar - 1;
17254       if( N<=0 ){
17255         return;
17256       }
17257     }else{
17258       i64 szNew = p->nChar;
17259       szNew += N + 1;
17260       if( szNew > p->mxAlloc ){
17261         sqlite3StrAccumReset(p);
17262         p->tooBig = 1;
17263         return;
17264       }else{
17265         p->nAlloc = szNew;
17266       }
17267       zNew = sqlite3DbMallocRaw(p->db, p->nAlloc );
17268       if( zNew ){
17269         memcpy(zNew, p->zText, p->nChar);
17270         sqlite3StrAccumReset(p);
17271         p->zText = zNew;
17272       }else{
17273         p->mallocFailed = 1;
17274         sqlite3StrAccumReset(p);
17275         return;
17276       }
17277     }
17278   }
17279   memcpy(&p->zText[p->nChar], z, N);
17280   p->nChar += N;
17281 }
17282
17283 /*
17284 ** Finish off a string by making sure it is zero-terminated.
17285 ** Return a pointer to the resulting string.  Return a NULL
17286 ** pointer if any kind of error was encountered.
17287 */
17288 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
17289   if( p->zText ){
17290     p->zText[p->nChar] = 0;
17291     if( p->useMalloc && p->zText==p->zBase ){
17292       p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
17293       if( p->zText ){
17294         memcpy(p->zText, p->zBase, p->nChar+1);
17295       }else{
17296         p->mallocFailed = 1;
17297       }
17298     }
17299   }
17300   return p->zText;
17301 }
17302
17303 /*
17304 ** Reset an StrAccum string.  Reclaim all malloced memory.
17305 */
17306 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
17307   if( p->zText!=p->zBase ){
17308     sqlite3DbFree(p->db, p->zText);
17309   }
17310   p->zText = 0;
17311 }
17312
17313 /*
17314 ** Initialize a string accumulator
17315 */
17316 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
17317   p->zText = p->zBase = zBase;
17318   p->db = 0;
17319   p->nChar = 0;
17320   p->nAlloc = n;
17321   p->mxAlloc = mx;
17322   p->useMalloc = 1;
17323   p->tooBig = 0;
17324   p->mallocFailed = 0;
17325 }
17326
17327 /*
17328 ** Print into memory obtained from sqliteMalloc().  Use the internal
17329 ** %-conversion extensions.
17330 */
17331 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
17332   char *z;
17333   char zBase[SQLITE_PRINT_BUF_SIZE];
17334   StrAccum acc;
17335   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
17336                       db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH);
17337   acc.db = db;
17338   sqlite3VXPrintf(&acc, 1, zFormat, ap);
17339   z = sqlite3StrAccumFinish(&acc);
17340   if( acc.mallocFailed && db ){
17341     db->mallocFailed = 1;
17342   }
17343   return z;
17344 }
17345
17346 /*
17347 ** Print into memory obtained from sqliteMalloc().  Use the internal
17348 ** %-conversion extensions.
17349 */
17350 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
17351   va_list ap;
17352   char *z;
17353   va_start(ap, zFormat);
17354   z = sqlite3VMPrintf(db, zFormat, ap);
17355   va_end(ap);
17356   return z;
17357 }
17358
17359 /*
17360 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
17361 ** the string and before returnning.  This routine is intended to be used
17362 ** to modify an existing string.  For example:
17363 **
17364 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
17365 **
17366 */
17367 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
17368   va_list ap;
17369   char *z;
17370   va_start(ap, zFormat);
17371   z = sqlite3VMPrintf(db, zFormat, ap);
17372   va_end(ap);
17373   sqlite3DbFree(db, zStr);
17374   return z;
17375 }
17376
17377 /*
17378 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
17379 ** %-conversion extensions.
17380 */
17381 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
17382   char *z;
17383   char zBase[SQLITE_PRINT_BUF_SIZE];
17384   StrAccum acc;
17385 #ifndef SQLITE_OMIT_AUTOINIT
17386   if( sqlite3_initialize() ) return 0;
17387 #endif
17388   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
17389   sqlite3VXPrintf(&acc, 0, zFormat, ap);
17390   z = sqlite3StrAccumFinish(&acc);
17391   return z;
17392 }
17393
17394 /*
17395 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
17396 ** %-conversion extensions.
17397 */
17398 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
17399   va_list ap;
17400   char *z;
17401 #ifndef SQLITE_OMIT_AUTOINIT
17402   if( sqlite3_initialize() ) return 0;
17403 #endif
17404   va_start(ap, zFormat);
17405   z = sqlite3_vmprintf(zFormat, ap);
17406   va_end(ap);
17407   return z;
17408 }
17409
17410 /*
17411 ** sqlite3_snprintf() works like snprintf() except that it ignores the
17412 ** current locale settings.  This is important for SQLite because we
17413 ** are not able to use a "," as the decimal point in place of "." as
17414 ** specified by some locales.
17415 */
17416 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
17417   char *z;
17418   va_list ap;
17419   StrAccum acc;
17420
17421   if( n<=0 ){
17422     return zBuf;
17423   }
17424   sqlite3StrAccumInit(&acc, zBuf, n, 0);
17425   acc.useMalloc = 0;
17426   va_start(ap,zFormat);
17427   sqlite3VXPrintf(&acc, 0, zFormat, ap);
17428   va_end(ap);
17429   z = sqlite3StrAccumFinish(&acc);
17430   return z;
17431 }
17432
17433 #if defined(SQLITE_DEBUG)
17434 /*
17435 ** A version of printf() that understands %lld.  Used for debugging.
17436 ** The printf() built into some versions of windows does not understand %lld
17437 ** and segfaults if you give it a long long int.
17438 */
17439 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
17440   va_list ap;
17441   StrAccum acc;
17442   char zBuf[500];
17443   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
17444   acc.useMalloc = 0;
17445   va_start(ap,zFormat);
17446   sqlite3VXPrintf(&acc, 0, zFormat, ap);
17447   va_end(ap);
17448   sqlite3StrAccumFinish(&acc);
17449   fprintf(stdout,"%s", zBuf);
17450   fflush(stdout);
17451 }
17452 #endif
17453
17454 /************** End of printf.c **********************************************/
17455 /************** Begin file random.c ******************************************/
17456 /*
17457 ** 2001 September 15
17458 **
17459 ** The author disclaims copyright to this source code.  In place of
17460 ** a legal notice, here is a blessing:
17461 **
17462 **    May you do good and not evil.
17463 **    May you find forgiveness for yourself and forgive others.
17464 **    May you share freely, never taking more than you give.
17465 **
17466 *************************************************************************
17467 ** This file contains code to implement a pseudo-random number
17468 ** generator (PRNG) for SQLite.
17469 **
17470 ** Random numbers are used by some of the database backends in order
17471 ** to generate random integer keys for tables or random filenames.
17472 **
17473 ** $Id: random.c,v 1.26 2008/09/02 00:52:52 drh Exp $
17474 */
17475
17476
17477 /* All threads share a single random number generator.
17478 ** This structure is the current state of the generator.
17479 */
17480 static SQLITE_WSD struct sqlite3PrngType {
17481   unsigned char isInit;          /* True if initialized */
17482   unsigned char i, j;            /* State variables */
17483   unsigned char s[256];          /* State variables */
17484 } sqlite3Prng = { 0, };
17485
17486 /*
17487 ** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
17488 ** must be held while executing this routine.
17489 **
17490 ** Why not just use a library random generator like lrand48() for this?
17491 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
17492 ** good source of random numbers.  The lrand48() library function may
17493 ** well be good enough.  But maybe not.  Or maybe lrand48() has some
17494 ** subtle problems on some systems that could cause problems.  It is hard
17495 ** to know.  To minimize the risk of problems due to bad lrand48()
17496 ** implementations, SQLite uses this random number generator based
17497 ** on RC4, which we know works very well.
17498 **
17499 ** (Later):  Actually, OP_NewRowid does not depend on a good source of
17500 ** randomness any more.  But we will leave this code in all the same.
17501 */
17502 static int randomByte(void){
17503   unsigned char t;
17504
17505
17506   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
17507   ** state vector.  If writable static data is unsupported on the target,
17508   ** we have to locate the state vector at run-time.  In the more common
17509   ** case where writable static data is supported, wsdPrng can refer directly
17510   ** to the "sqlite3Prng" state vector declared above.
17511   */
17512 #ifdef SQLITE_OMIT_WSD
17513   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
17514 # define wsdPrng p[0]
17515 #else
17516 # define wsdPrng sqlite3Prng
17517 #endif
17518
17519
17520   /* Initialize the state of the random number generator once,
17521   ** the first time this routine is called.  The seed value does
17522   ** not need to contain a lot of randomness since we are not
17523   ** trying to do secure encryption or anything like that...
17524   **
17525   ** Nothing in this file or anywhere else in SQLite does any kind of
17526   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
17527   ** number generator) not as an encryption device.
17528   */
17529   if( !wsdPrng.isInit ){
17530     int i;
17531     char k[256];
17532     wsdPrng.j = 0;
17533     wsdPrng.i = 0;
17534     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
17535     for(i=0; i<256; i++){
17536       wsdPrng.s[i] = i;
17537     }
17538     for(i=0; i<256; i++){
17539       wsdPrng.j += wsdPrng.s[i] + k[i];
17540       t = wsdPrng.s[wsdPrng.j];
17541       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
17542       wsdPrng.s[i] = t;
17543     }
17544     wsdPrng.isInit = 1;
17545   }
17546
17547   /* Generate and return single random byte
17548   */
17549   wsdPrng.i++;
17550   t = wsdPrng.s[wsdPrng.i];
17551   wsdPrng.j += t;
17552   wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
17553   wsdPrng.s[wsdPrng.j] = t;
17554   t += wsdPrng.s[wsdPrng.i];
17555   return wsdPrng.s[t];
17556 }
17557
17558 /*
17559 ** Return N random bytes.
17560 */
17561 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
17562   unsigned char *zBuf = pBuf;
17563 #ifndef SQLITE_MUTEX_NOOP
17564   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
17565 #endif
17566   sqlite3_mutex_enter(mutex);
17567   while( N-- ){
17568     *(zBuf++) = randomByte();
17569   }
17570   sqlite3_mutex_leave(mutex);
17571 }
17572
17573 #ifndef SQLITE_OMIT_BUILTIN_TEST
17574 /*
17575 ** For testing purposes, we sometimes want to preserve the state of
17576 ** PRNG and restore the PRNG to its saved state at a later time, or
17577 ** to reset the PRNG to its initial state.  These routines accomplish
17578 ** those tasks.
17579 **
17580 ** The sqlite3_test_control() interface calls these routines to
17581 ** control the PRNG.
17582 */
17583 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng = { 0, };
17584 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
17585   memcpy(
17586     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
17587     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
17588     sizeof(sqlite3Prng)
17589   );
17590 }
17591 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
17592   memcpy(
17593     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
17594     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
17595     sizeof(sqlite3Prng)
17596   );
17597 }
17598 SQLITE_PRIVATE void sqlite3PrngResetState(void){
17599   GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
17600 }
17601 #endif /* SQLITE_OMIT_BUILTIN_TEST */
17602
17603 /************** End of random.c **********************************************/
17604 /************** Begin file utf.c *********************************************/
17605 /*
17606 ** 2004 April 13
17607 **
17608 ** The author disclaims copyright to this source code.  In place of
17609 ** a legal notice, here is a blessing:
17610 **
17611 **    May you do good and not evil.
17612 **    May you find forgiveness for yourself and forgive others.
17613 **    May you share freely, never taking more than you give.
17614 **
17615 *************************************************************************
17616 ** This file contains routines used to translate between UTF-8, 
17617 ** UTF-16, UTF-16BE, and UTF-16LE.
17618 **
17619 ** $Id: utf.c,v 1.65 2008/08/12 15:04:59 danielk1977 Exp $
17620 **
17621 ** Notes on UTF-8:
17622 **
17623 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
17624 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
17625 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
17626 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
17627 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
17628 **
17629 **
17630 ** Notes on UTF-16:  (with wwww+1==uuuuu)
17631 **
17632 **      Word-0               Word-1          Value
17633 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
17634 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
17635 **
17636 **
17637 ** BOM or Byte Order Mark:
17638 **     0xff 0xfe   little-endian utf-16 follows
17639 **     0xfe 0xff   big-endian utf-16 follows
17640 **
17641 */
17642 /************** Include vdbeInt.h in the middle of utf.c *********************/
17643 /************** Begin file vdbeInt.h *****************************************/
17644 /*
17645 ** 2003 September 6
17646 **
17647 ** The author disclaims copyright to this source code.  In place of
17648 ** a legal notice, here is a blessing:
17649 **
17650 **    May you do good and not evil.
17651 **    May you find forgiveness for yourself and forgive others.
17652 **    May you share freely, never taking more than you give.
17653 **
17654 *************************************************************************
17655 ** This is the header file for information that is private to the
17656 ** VDBE.  This information used to all be at the top of the single
17657 ** source code file "vdbe.c".  When that file became too big (over
17658 ** 6000 lines long) it was split up into several smaller files and
17659 ** this header information was factored out.
17660 **
17661 ** $Id: vdbeInt.h,v 1.154 2008/08/13 19:11:48 drh Exp $
17662 */
17663 #ifndef _VDBEINT_H_
17664 #define _VDBEINT_H_
17665
17666 /*
17667 ** intToKey() and keyToInt() used to transform the rowid.  But with
17668 ** the latest versions of the design they are no-ops.
17669 */
17670 #define keyToInt(X)   (X)
17671 #define intToKey(X)   (X)
17672
17673
17674 /*
17675 ** SQL is translated into a sequence of instructions to be
17676 ** executed by a virtual machine.  Each instruction is an instance
17677 ** of the following structure.
17678 */
17679 typedef struct VdbeOp Op;
17680
17681 /*
17682 ** Boolean values
17683 */
17684 typedef unsigned char Bool;
17685
17686 /*
17687 ** A cursor is a pointer into a single BTree within a database file.
17688 ** The cursor can seek to a BTree entry with a particular key, or
17689 ** loop over all entries of the Btree.  You can also insert new BTree
17690 ** entries or retrieve the key or data from the entry that the cursor
17691 ** is currently pointing to.
17692 ** 
17693 ** Every cursor that the virtual machine has open is represented by an
17694 ** instance of the following structure.
17695 **
17696 ** If the Cursor.isTriggerRow flag is set it means that this cursor is
17697 ** really a single row that represents the NEW or OLD pseudo-table of
17698 ** a row trigger.  The data for the row is stored in Cursor.pData and
17699 ** the rowid is in Cursor.iKey.
17700 */
17701 struct Cursor {
17702   BtCursor *pCursor;    /* The cursor structure of the backend */
17703   int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
17704   i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
17705   i64 nextRowid;        /* Next rowid returned by OP_NewRowid */
17706   Bool zeroed;          /* True if zeroed out and ready for reuse */
17707   Bool rowidIsValid;    /* True if lastRowid is valid */
17708   Bool atFirst;         /* True if pointing to first entry */
17709   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
17710   Bool nullRow;         /* True if pointing to a row with no data */
17711   Bool nextRowidValid;  /* True if the nextRowid field is valid */
17712   Bool pseudoTable;     /* This is a NEW or OLD pseudo-tables of a trigger */
17713   Bool ephemPseudoTable;
17714   Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
17715   Bool isTable;         /* True if a table requiring integer keys */
17716   Bool isIndex;         /* True if an index containing keys only - no data */
17717   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
17718   Btree *pBt;           /* Separate file holding temporary table */
17719   int nData;            /* Number of bytes in pData */
17720   char *pData;          /* Data for a NEW or OLD pseudo-table */
17721   i64 iKey;             /* Key for the NEW or OLD pseudo-table row */
17722   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
17723   int nField;           /* Number of fields in the header */
17724   i64 seqCount;         /* Sequence counter */
17725   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
17726   const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
17727
17728   /* Cached information about the header for the data record that the
17729   ** cursor is currently pointing to.  Only valid if cacheValid is true.
17730   ** aRow might point to (ephemeral) data for the current row, or it might
17731   ** be NULL.
17732   */
17733   int cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
17734   int payloadSize;      /* Total number of bytes in the record */
17735   u32 *aType;           /* Type values for all entries in the record */
17736   u32 *aOffset;         /* Cached offsets to the start of each columns data */
17737   u8 *aRow;             /* Data for the current row, if all on one page */
17738 };
17739 typedef struct Cursor Cursor;
17740
17741 /*
17742 ** A value for Cursor.cacheValid that means the cache is always invalid.
17743 */
17744 #define CACHE_STALE 0
17745
17746 /*
17747 ** Internally, the vdbe manipulates nearly all SQL values as Mem
17748 ** structures. Each Mem struct may cache multiple representations (string,
17749 ** integer etc.) of the same value.  A value (and therefore Mem structure)
17750 ** has the following properties:
17751 **
17752 ** Each value has a manifest type. The manifest type of the value stored
17753 ** in a Mem struct is returned by the MemType(Mem*) macro. The type is
17754 ** one of SQLITE_NULL, SQLITE_INTEGER, SQLITE_REAL, SQLITE_TEXT or
17755 ** SQLITE_BLOB.
17756 */
17757 struct Mem {
17758   union {
17759     i64 i;              /* Integer value. Or FuncDef* when flags==MEM_Agg */
17760     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
17761   } u;
17762   double r;           /* Real value */
17763   sqlite3 *db;        /* The associated database connection */
17764   char *z;            /* String or BLOB value */
17765   int n;              /* Number of characters in string value, excluding '\0' */
17766   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
17767   u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
17768   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
17769   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
17770   char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
17771 };
17772
17773 /* One or more of the following flags are set to indicate the validOK
17774 ** representations of the value stored in the Mem struct.
17775 **
17776 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
17777 ** No other flags may be set in this case.
17778 **
17779 ** If the MEM_Str flag is set then Mem.z points at a string representation.
17780 ** Usually this is encoded in the same unicode encoding as the main
17781 ** database (see below for exceptions). If the MEM_Term flag is also
17782 ** set, then the string is nul terminated. The MEM_Int and MEM_Real 
17783 ** flags may coexist with the MEM_Str flag.
17784 **
17785 ** Multiple of these values can appear in Mem.flags.  But only one
17786 ** at a time can appear in Mem.type.
17787 */
17788 #define MEM_Null      0x0001   /* Value is NULL */
17789 #define MEM_Str       0x0002   /* Value is a string */
17790 #define MEM_Int       0x0004   /* Value is an integer */
17791 #define MEM_Real      0x0008   /* Value is a real number */
17792 #define MEM_Blob      0x0010   /* Value is a BLOB */
17793
17794 #define MemSetTypeFlag(p, f) \
17795   ((p)->flags = ((p)->flags&~(MEM_Int|MEM_Real|MEM_Null|MEM_Blob|MEM_Str))|f)
17796
17797 /* Whenever Mem contains a valid string or blob representation, one of
17798 ** the following flags must be set to determine the memory management
17799 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
17800 ** string is \000 or \u0000 terminated
17801 */
17802 #define MEM_Term      0x0020   /* String rep is nul terminated */
17803 #define MEM_Dyn       0x0040   /* Need to call sqliteFree() on Mem.z */
17804 #define MEM_Static    0x0080   /* Mem.z points to a static string */
17805 #define MEM_Ephem     0x0100   /* Mem.z points to an ephemeral string */
17806 #define MEM_Agg       0x0400   /* Mem.z points to an agg function context */
17807 #define MEM_Zero      0x0800   /* Mem.i contains count of 0s appended to blob */
17808
17809 #ifdef SQLITE_OMIT_INCRBLOB
17810   #undef MEM_Zero
17811   #define MEM_Zero 0x0000
17812 #endif
17813
17814
17815 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
17816 ** additional information about auxiliary information bound to arguments
17817 ** of the function.  This is used to implement the sqlite3_get_auxdata()
17818 ** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
17819 ** that can be associated with a constant argument to a function.  This
17820 ** allows functions such as "regexp" to compile their constant regular
17821 ** expression argument once and reused the compiled code for multiple
17822 ** invocations.
17823 */
17824 struct VdbeFunc {
17825   FuncDef *pFunc;               /* The definition of the function */
17826   int nAux;                     /* Number of entries allocated for apAux[] */
17827   struct AuxData {
17828     void *pAux;                   /* Aux data for the i-th argument */
17829     void (*xDelete)(void *);      /* Destructor for the aux data */
17830   } apAux[1];                   /* One slot for each function argument */
17831 };
17832
17833 /*
17834 ** The "context" argument for a installable function.  A pointer to an
17835 ** instance of this structure is the first argument to the routines used
17836 ** implement the SQL functions.
17837 **
17838 ** There is a typedef for this structure in sqlite.h.  So all routines,
17839 ** even the public interface to SQLite, can use a pointer to this structure.
17840 ** But this file is the only place where the internal details of this
17841 ** structure are known.
17842 **
17843 ** This structure is defined inside of vdbeInt.h because it uses substructures
17844 ** (Mem) which are only defined there.
17845 */
17846 struct sqlite3_context {
17847   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
17848   VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
17849   Mem s;                /* The return value is stored here */
17850   Mem *pMem;            /* Memory cell used to store aggregate context */
17851   int isError;          /* Error code returned by the function. */
17852   CollSeq *pColl;       /* Collating sequence */
17853 };
17854
17855 /*
17856 ** A Set structure is used for quick testing to see if a value
17857 ** is part of a small set.  Sets are used to implement code like
17858 ** this:
17859 **            x.y IN ('hi','hoo','hum')
17860 */
17861 typedef struct Set Set;
17862 struct Set {
17863   Hash hash;             /* A set is just a hash table */
17864   HashElem *prev;        /* Previously accessed hash elemen */
17865 };
17866
17867 /*
17868 ** A FifoPage structure holds a single page of valves.  Pages are arranged
17869 ** in a list.
17870 */
17871 typedef struct FifoPage FifoPage;
17872 struct FifoPage {
17873   int nSlot;         /* Number of entries aSlot[] */
17874   int iWrite;        /* Push the next value into this entry in aSlot[] */
17875   int iRead;         /* Read the next value from this entry in aSlot[] */
17876   FifoPage *pNext;   /* Next page in the fifo */
17877   i64 aSlot[1];      /* One or more slots for rowid values */
17878 };
17879
17880 /*
17881 ** The Fifo structure is typedef-ed in vdbeInt.h.  But the implementation
17882 ** of that structure is private to this file.
17883 **
17884 ** The Fifo structure describes the entire fifo.  
17885 */
17886 typedef struct Fifo Fifo;
17887 struct Fifo {
17888   int nEntry;         /* Total number of entries */
17889   sqlite3 *db;        /* The associated database connection */
17890   FifoPage *pFirst;   /* First page on the list */
17891   FifoPage *pLast;    /* Last page on the list */
17892 };
17893
17894 /*
17895 ** A Context stores the last insert rowid, the last statement change count,
17896 ** and the current statement change count (i.e. changes since last statement).
17897 ** The current keylist is also stored in the context.
17898 ** Elements of Context structure type make up the ContextStack, which is
17899 ** updated by the ContextPush and ContextPop opcodes (used by triggers).
17900 ** The context is pushed before executing a trigger a popped when the
17901 ** trigger finishes.
17902 */
17903 typedef struct Context Context;
17904 struct Context {
17905   i64 lastRowid;    /* Last insert rowid (sqlite3.lastRowid) */
17906   int nChange;      /* Statement changes (Vdbe.nChanges)     */
17907   Fifo sFifo;       /* Records that will participate in a DELETE or UPDATE */
17908 };
17909
17910 /*
17911 ** An instance of the virtual machine.  This structure contains the complete
17912 ** state of the virtual machine.
17913 **
17914 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_compile()
17915 ** is really a pointer to an instance of this structure.
17916 **
17917 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
17918 ** any virtual table method invocations made by the vdbe program. It is
17919 ** set to 2 for xDestroy method calls and 1 for all other methods. This
17920 ** variable is used for two purposes: to allow xDestroy methods to execute
17921 ** "DROP TABLE" statements and to prevent some nasty side effects of
17922 ** malloc failure when SQLite is invoked recursively by a virtual table 
17923 ** method function.
17924 */
17925 struct Vdbe {
17926   sqlite3 *db;        /* The whole database */
17927   Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
17928   int nOp;            /* Number of instructions in the program */
17929   int nOpAlloc;       /* Number of slots allocated for aOp[] */
17930   Op *aOp;            /* Space to hold the virtual machine's program */
17931   int nLabel;         /* Number of labels used */
17932   int nLabelAlloc;    /* Number of slots allocated in aLabel[] */
17933   int *aLabel;        /* Space to hold the labels */
17934   Mem **apArg;        /* Arguments to currently executing user function */
17935   Mem *aColName;      /* Column names to return */
17936   int nCursor;        /* Number of slots in apCsr[] */
17937   Cursor **apCsr;     /* One element of this array for each open cursor */
17938   int nVar;           /* Number of entries in aVar[] */
17939   Mem *aVar;          /* Values for the OP_Variable opcode. */
17940   char **azVar;       /* Name of variables */
17941   int okVar;          /* True if azVar[] has been initialized */
17942   int magic;              /* Magic number for sanity checking */
17943   int nMem;               /* Number of memory locations currently allocated */
17944   Mem *aMem;              /* The memory locations */
17945   int nCallback;          /* Number of callbacks invoked so far */
17946   int cacheCtr;           /* Cursor row cache generation counter */
17947   Fifo sFifo;             /* A list of ROWIDs */
17948   int contextStackTop;    /* Index of top element in the context stack */
17949   int contextStackDepth;  /* The size of the "context" stack */
17950   Context *contextStack;  /* Stack used by opcodes ContextPush & ContextPop*/
17951   int pc;                 /* The program counter */
17952   int rc;                 /* Value to return */
17953   unsigned uniqueCnt;     /* Used by OP_MakeRecord when P2!=0 */
17954   int errorAction;        /* Recovery action to do in case of an error */
17955   int inTempTrans;        /* True if temp database is transactioned */
17956   int nResColumn;         /* Number of columns in one row of the result set */
17957   char **azResColumn;     /* Values for one row of result */ 
17958   char *zErrMsg;          /* Error message written here */
17959   Mem *pResultSet;        /* Pointer to an array of results */
17960   u8 explain;             /* True if EXPLAIN present on SQL command */
17961   u8 changeCntOn;         /* True to update the change-counter */
17962   u8 expired;             /* True if the VM needs to be recompiled */
17963   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
17964   u8 inVtabMethod;        /* See comments above */
17965   int nChange;            /* Number of db changes made since last reset */
17966   i64 startTime;          /* Time when query started - used for profiling */
17967   int btreeMask;          /* Bitmask of db->aDb[] entries referenced */
17968   BtreeMutexArray aMutex; /* An array of Btree used here and needing locks */
17969   int nSql;             /* Number of bytes in zSql */
17970   char *zSql;           /* Text of the SQL statement that generated this */
17971 #ifdef SQLITE_DEBUG
17972   FILE *trace;        /* Write an execution trace here, if not NULL */
17973 #endif
17974   int openedStatement;  /* True if this VM has opened a statement journal */
17975 #ifdef SQLITE_SSE
17976   int fetchId;          /* Statement number used by sqlite3_fetch_statement */
17977   int lru;              /* Counter used for LRU cache replacement */
17978 #endif
17979 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
17980   Vdbe *pLruPrev;
17981   Vdbe *pLruNext;
17982 #endif
17983 };
17984
17985 /*
17986 ** The following are allowed values for Vdbe.magic
17987 */
17988 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
17989 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
17990 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
17991 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
17992
17993 /*
17994 ** Function prototypes
17995 */
17996 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, Cursor*);
17997 void sqliteVdbePopStack(Vdbe*,int);
17998 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(Cursor*);
17999 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
18000 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
18001 #endif
18002 SQLITE_PRIVATE int sqlite3VdbeSerialTypeLen(u32);
18003 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
18004 SQLITE_PRIVATE int sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
18005 SQLITE_PRIVATE int sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
18006 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
18007
18008 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
18009 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(Cursor*,UnpackedRecord*,int*);
18010 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(BtCursor *, i64 *);
18011 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
18012 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
18013 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
18014 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
18015 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
18016 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
18017 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
18018 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
18019 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
18020 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
18021 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
18022 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
18023 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
18024 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
18025 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
18026 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
18027 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
18028 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
18029 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
18030 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
18031 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
18032 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
18033 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
18034 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
18035 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
18036 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
18037 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
18038 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
18039 SQLITE_PRIVATE int sqlite3VdbeOpcodeHasProperty(int, int);
18040 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
18041 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
18042 SQLITE_PRIVATE int sqlite3VdbeReleaseBuffers(Vdbe *p);
18043 #endif
18044
18045 #ifndef NDEBUG
18046 SQLITE_PRIVATE   void sqlite3VdbeMemSanity(Mem*);
18047 #endif
18048 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
18049 #ifdef SQLITE_DEBUG
18050 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
18051 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
18052 #endif
18053 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
18054 SQLITE_PRIVATE void sqlite3VdbeFifoInit(Fifo*, sqlite3*);
18055 SQLITE_PRIVATE int sqlite3VdbeFifoPush(Fifo*, i64);
18056 SQLITE_PRIVATE int sqlite3VdbeFifoPop(Fifo*, i64*);
18057 SQLITE_PRIVATE void sqlite3VdbeFifoClear(Fifo*);
18058
18059 #ifndef SQLITE_OMIT_INCRBLOB
18060 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
18061 #else
18062   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
18063 #endif
18064
18065 #endif /* !defined(_VDBEINT_H_) */
18066
18067 /************** End of vdbeInt.h *********************************************/
18068 /************** Continuing where we left off in utf.c ************************/
18069
18070 /*
18071 ** The following constant value is used by the SQLITE_BIGENDIAN and
18072 ** SQLITE_LITTLEENDIAN macros.
18073 */
18074 SQLITE_PRIVATE const int sqlite3one = 1;
18075
18076 /*
18077 ** This lookup table is used to help decode the first byte of
18078 ** a multi-byte UTF8 character.
18079 */
18080 static const unsigned char sqlite3UtfTrans1[] = {
18081   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
18082   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
18083   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
18084   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
18085   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
18086   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
18087   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
18088   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
18089 };
18090
18091
18092 #define WRITE_UTF8(zOut, c) {                          \
18093   if( c<0x00080 ){                                     \
18094     *zOut++ = (c&0xFF);                                \
18095   }                                                    \
18096   else if( c<0x00800 ){                                \
18097     *zOut++ = 0xC0 + ((c>>6)&0x1F);                    \
18098     *zOut++ = 0x80 + (c & 0x3F);                       \
18099   }                                                    \
18100   else if( c<0x10000 ){                                \
18101     *zOut++ = 0xE0 + ((c>>12)&0x0F);                   \
18102     *zOut++ = 0x80 + ((c>>6) & 0x3F);                  \
18103     *zOut++ = 0x80 + (c & 0x3F);                       \
18104   }else{                                               \
18105     *zOut++ = 0xF0 + ((c>>18) & 0x07);                 \
18106     *zOut++ = 0x80 + ((c>>12) & 0x3F);                 \
18107     *zOut++ = 0x80 + ((c>>6) & 0x3F);                  \
18108     *zOut++ = 0x80 + (c & 0x3F);                       \
18109   }                                                    \
18110 }
18111
18112 #define WRITE_UTF16LE(zOut, c) {                                \
18113   if( c<=0xFFFF ){                                              \
18114     *zOut++ = (c&0x00FF);                                       \
18115     *zOut++ = ((c>>8)&0x00FF);                                  \
18116   }else{                                                        \
18117     *zOut++ = (((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
18118     *zOut++ = (0x00D8 + (((c-0x10000)>>18)&0x03));              \
18119     *zOut++ = (c&0x00FF);                                       \
18120     *zOut++ = (0x00DC + ((c>>8)&0x03));                         \
18121   }                                                             \
18122 }
18123
18124 #define WRITE_UTF16BE(zOut, c) {                                \
18125   if( c<=0xFFFF ){                                              \
18126     *zOut++ = ((c>>8)&0x00FF);                                  \
18127     *zOut++ = (c&0x00FF);                                       \
18128   }else{                                                        \
18129     *zOut++ = (0x00D8 + (((c-0x10000)>>18)&0x03));              \
18130     *zOut++ = (((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
18131     *zOut++ = (0x00DC + ((c>>8)&0x03));                         \
18132     *zOut++ = (c&0x00FF);                                       \
18133   }                                                             \
18134 }
18135
18136 #define READ_UTF16LE(zIn, c){                                         \
18137   c = (*zIn++);                                                       \
18138   c += ((*zIn++)<<8);                                                 \
18139   if( c>=0xD800 && c<0xE000 ){                                       \
18140     int c2 = (*zIn++);                                                \
18141     c2 += ((*zIn++)<<8);                                              \
18142     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
18143     if( (c & 0xFFFF0000)==0 ) c = 0xFFFD;                             \
18144   }                                                                   \
18145 }
18146
18147 #define READ_UTF16BE(zIn, c){                                         \
18148   c = ((*zIn++)<<8);                                                  \
18149   c += (*zIn++);                                                      \
18150   if( c>=0xD800 && c<0xE000 ){                                       \
18151     int c2 = ((*zIn++)<<8);                                           \
18152     c2 += (*zIn++);                                                   \
18153     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
18154     if( (c & 0xFFFF0000)==0 ) c = 0xFFFD;                             \
18155   }                                                                   \
18156 }
18157
18158 /*
18159 ** Translate a single UTF-8 character.  Return the unicode value.
18160 **
18161 ** During translation, assume that the byte that zTerm points
18162 ** is a 0x00.
18163 **
18164 ** Write a pointer to the next unread byte back into *pzNext.
18165 **
18166 ** Notes On Invalid UTF-8:
18167 **
18168 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
18169 **     be encoded as a multi-byte character.  Any multi-byte character that
18170 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
18171 **
18172 **  *  This routine never allows a UTF16 surrogate value to be encoded.
18173 **     If a multi-byte character attempts to encode a value between
18174 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
18175 **
18176 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
18177 **     byte of a character are interpreted as single-byte characters
18178 **     and rendered as themselves even though they are technically
18179 **     invalid characters.
18180 **
18181 **  *  This routine accepts an infinite number of different UTF8 encodings
18182 **     for unicode values 0x80 and greater.  It do not change over-length
18183 **     encodings to 0xfffd as some systems recommend.
18184 */
18185 #define READ_UTF8(zIn, zTerm, c)                           \
18186   c = *(zIn++);                                            \
18187   if( c>=0xc0 ){                                           \
18188     c = sqlite3UtfTrans1[c-0xc0];                          \
18189     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
18190       c = (c<<6) + (0x3f & *(zIn++));                      \
18191     }                                                      \
18192     if( c<0x80                                             \
18193         || (c&0xFFFFF800)==0xD800                          \
18194         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
18195   }
18196 SQLITE_PRIVATE int sqlite3Utf8Read(
18197   const unsigned char *z,         /* First byte of UTF-8 character */
18198   const unsigned char *zTerm,     /* Pretend this byte is 0x00 */
18199   const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
18200 ){
18201   int c;
18202   READ_UTF8(z, zTerm, c);
18203   *pzNext = z;
18204   return c;
18205 }
18206
18207
18208
18209
18210 /*
18211 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
18212 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
18213 */ 
18214 /* #define TRANSLATE_TRACE 1 */
18215
18216 #ifndef SQLITE_OMIT_UTF16
18217 /*
18218 ** This routine transforms the internal text encoding used by pMem to
18219 ** desiredEnc. It is an error if the string is already of the desired
18220 ** encoding, or if *pMem does not contain a string value.
18221 */
18222 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
18223   int len;                    /* Maximum length of output string in bytes */
18224   unsigned char *zOut;                  /* Output buffer */
18225   unsigned char *zIn;                   /* Input iterator */
18226   unsigned char *zTerm;                 /* End of input */
18227   unsigned char *z;                     /* Output iterator */
18228   unsigned int c;
18229
18230   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
18231   assert( pMem->flags&MEM_Str );
18232   assert( pMem->enc!=desiredEnc );
18233   assert( pMem->enc!=0 );
18234   assert( pMem->n>=0 );
18235
18236 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
18237   {
18238     char zBuf[100];
18239     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
18240     fprintf(stderr, "INPUT:  %s\n", zBuf);
18241   }
18242 #endif
18243
18244   /* If the translation is between UTF-16 little and big endian, then 
18245   ** all that is required is to swap the byte order. This case is handled
18246   ** differently from the others.
18247   */
18248   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
18249     u8 temp;
18250     int rc;
18251     rc = sqlite3VdbeMemMakeWriteable(pMem);
18252     if( rc!=SQLITE_OK ){
18253       assert( rc==SQLITE_NOMEM );
18254       return SQLITE_NOMEM;
18255     }
18256     zIn = (u8*)pMem->z;
18257     zTerm = &zIn[pMem->n];
18258     while( zIn<zTerm ){
18259       temp = *zIn;
18260       *zIn = *(zIn+1);
18261       zIn++;
18262       *zIn++ = temp;
18263     }
18264     pMem->enc = desiredEnc;
18265     goto translate_out;
18266   }
18267
18268   /* Set len to the maximum number of bytes required in the output buffer. */
18269   if( desiredEnc==SQLITE_UTF8 ){
18270     /* When converting from UTF-16, the maximum growth results from
18271     ** translating a 2-byte character to a 4-byte UTF-8 character.
18272     ** A single byte is required for the output string
18273     ** nul-terminator.
18274     */
18275     len = pMem->n * 2 + 1;
18276   }else{
18277     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
18278     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
18279     ** character. Two bytes are required in the output buffer for the
18280     ** nul-terminator.
18281     */
18282     len = pMem->n * 2 + 2;
18283   }
18284
18285   /* Set zIn to point at the start of the input buffer and zTerm to point 1
18286   ** byte past the end.
18287   **
18288   ** Variable zOut is set to point at the output buffer, space obtained
18289   ** from sqlite3_malloc().
18290   */
18291   zIn = (u8*)pMem->z;
18292   zTerm = &zIn[pMem->n];
18293   zOut = sqlite3DbMallocRaw(pMem->db, len);
18294   if( !zOut ){
18295     return SQLITE_NOMEM;
18296   }
18297   z = zOut;
18298
18299   if( pMem->enc==SQLITE_UTF8 ){
18300     if( desiredEnc==SQLITE_UTF16LE ){
18301       /* UTF-8 -> UTF-16 Little-endian */
18302       while( zIn<zTerm ){
18303         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
18304         READ_UTF8(zIn, zTerm, c);
18305         WRITE_UTF16LE(z, c);
18306       }
18307     }else{
18308       assert( desiredEnc==SQLITE_UTF16BE );
18309       /* UTF-8 -> UTF-16 Big-endian */
18310       while( zIn<zTerm ){
18311         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
18312         READ_UTF8(zIn, zTerm, c);
18313         WRITE_UTF16BE(z, c);
18314       }
18315     }
18316     pMem->n = z - zOut;
18317     *z++ = 0;
18318   }else{
18319     assert( desiredEnc==SQLITE_UTF8 );
18320     if( pMem->enc==SQLITE_UTF16LE ){
18321       /* UTF-16 Little-endian -> UTF-8 */
18322       while( zIn<zTerm ){
18323         READ_UTF16LE(zIn, c); 
18324         WRITE_UTF8(z, c);
18325       }
18326     }else{
18327       /* UTF-16 Big-endian -> UTF-8 */
18328       while( zIn<zTerm ){
18329         READ_UTF16BE(zIn, c); 
18330         WRITE_UTF8(z, c);
18331       }
18332     }
18333     pMem->n = z - zOut;
18334   }
18335   *z = 0;
18336   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
18337
18338   sqlite3VdbeMemRelease(pMem);
18339   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
18340   pMem->enc = desiredEnc;
18341   pMem->flags |= (MEM_Term|MEM_Dyn);
18342   pMem->z = (char*)zOut;
18343   pMem->zMalloc = pMem->z;
18344
18345 translate_out:
18346 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
18347   {
18348     char zBuf[100];
18349     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
18350     fprintf(stderr, "OUTPUT: %s\n", zBuf);
18351   }
18352 #endif
18353   return SQLITE_OK;
18354 }
18355
18356 /*
18357 ** This routine checks for a byte-order mark at the beginning of the 
18358 ** UTF-16 string stored in *pMem. If one is present, it is removed and
18359 ** the encoding of the Mem adjusted. This routine does not do any
18360 ** byte-swapping, it just sets Mem.enc appropriately.
18361 **
18362 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
18363 ** changed by this function.
18364 */
18365 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
18366   int rc = SQLITE_OK;
18367   u8 bom = 0;
18368
18369   if( pMem->n<0 || pMem->n>1 ){
18370     u8 b1 = *(u8 *)pMem->z;
18371     u8 b2 = *(((u8 *)pMem->z) + 1);
18372     if( b1==0xFE && b2==0xFF ){
18373       bom = SQLITE_UTF16BE;
18374     }
18375     if( b1==0xFF && b2==0xFE ){
18376       bom = SQLITE_UTF16LE;
18377     }
18378   }
18379   
18380   if( bom ){
18381     rc = sqlite3VdbeMemMakeWriteable(pMem);
18382     if( rc==SQLITE_OK ){
18383       pMem->n -= 2;
18384       memmove(pMem->z, &pMem->z[2], pMem->n);
18385       pMem->z[pMem->n] = '\0';
18386       pMem->z[pMem->n+1] = '\0';
18387       pMem->flags |= MEM_Term;
18388       pMem->enc = bom;
18389     }
18390   }
18391   return rc;
18392 }
18393 #endif /* SQLITE_OMIT_UTF16 */
18394
18395 /*
18396 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
18397 ** return the number of unicode characters in pZ up to (but not including)
18398 ** the first 0x00 byte. If nByte is not less than zero, return the
18399 ** number of unicode characters in the first nByte of pZ (or up to 
18400 ** the first 0x00, whichever comes first).
18401 */
18402 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
18403   int r = 0;
18404   const u8 *z = (const u8*)zIn;
18405   const u8 *zTerm;
18406   if( nByte>=0 ){
18407     zTerm = &z[nByte];
18408   }else{
18409     zTerm = (const u8*)(-1);
18410   }
18411   assert( z<=zTerm );
18412   while( *z!=0 && z<zTerm ){
18413     SQLITE_SKIP_UTF8(z);
18414     r++;
18415   }
18416   return r;
18417 }
18418
18419 /* This test function is not currently used by the automated test-suite. 
18420 ** Hence it is only available in debug builds.
18421 */
18422 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
18423 /*
18424 ** Translate UTF-8 to UTF-8.
18425 **
18426 ** This has the effect of making sure that the string is well-formed
18427 ** UTF-8.  Miscoded characters are removed.
18428 **
18429 ** The translation is done in-place (since it is impossible for the
18430 ** correct UTF-8 encoding to be longer than a malformed encoding).
18431 */
18432 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
18433   unsigned char *zOut = zIn;
18434   unsigned char *zStart = zIn;
18435   unsigned char *zTerm = &zIn[strlen((char *)zIn)];
18436   u32 c;
18437
18438   while( zIn[0] ){
18439     c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn);
18440     if( c!=0xfffd ){
18441       WRITE_UTF8(zOut, c);
18442     }
18443   }
18444   *zOut = 0;
18445   return zOut - zStart;
18446 }
18447 #endif
18448
18449 #ifndef SQLITE_OMIT_UTF16
18450 /*
18451 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
18452 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
18453 ** be freed by the calling function.
18454 **
18455 ** NULL is returned if there is an allocation error.
18456 */
18457 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte){
18458   Mem m;
18459   memset(&m, 0, sizeof(m));
18460   m.db = db;
18461   sqlite3VdbeMemSetStr(&m, z, nByte, SQLITE_UTF16NATIVE, SQLITE_STATIC);
18462   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
18463   if( db->mallocFailed ){
18464     sqlite3VdbeMemRelease(&m);
18465     m.z = 0;
18466   }
18467   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
18468   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
18469   return (m.flags & MEM_Dyn)!=0 ? m.z : sqlite3DbStrDup(db, m.z);
18470 }
18471
18472 /*
18473 ** pZ is a UTF-16 encoded unicode string. If nChar is less than zero,
18474 ** return the number of bytes up to (but not including), the first pair
18475 ** of consecutive 0x00 bytes in pZ. If nChar is not less than zero,
18476 ** then return the number of bytes in the first nChar unicode characters
18477 ** in pZ (or up until the first pair of 0x00 bytes, whichever comes first).
18478 */
18479 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
18480   unsigned int c = 1;
18481   char const *z = zIn;
18482   int n = 0;
18483   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
18484     /* Using an "if (SQLITE_UTF16NATIVE==SQLITE_UTF16BE)" construct here
18485     ** and in other parts of this file means that at one branch will
18486     ** not be covered by coverage testing on any single host. But coverage
18487     ** will be complete if the tests are run on both a little-endian and 
18488     ** big-endian host. Because both the UTF16NATIVE and SQLITE_UTF16BE
18489     ** macros are constant at compile time the compiler can determine
18490     ** which branch will be followed. It is therefore assumed that no runtime
18491     ** penalty is paid for this "if" statement.
18492     */
18493     while( c && ((nChar<0) || n<nChar) ){
18494       READ_UTF16BE(z, c);
18495       n++;
18496     }
18497   }else{
18498     while( c && ((nChar<0) || n<nChar) ){
18499       READ_UTF16LE(z, c);
18500       n++;
18501     }
18502   }
18503   return (z-(char const *)zIn)-((c==0)?2:0);
18504 }
18505
18506 #if defined(SQLITE_TEST)
18507 /*
18508 ** This routine is called from the TCL test function "translate_selftest".
18509 ** It checks that the primitives for serializing and deserializing
18510 ** characters in each encoding are inverses of each other.
18511 */
18512 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
18513   unsigned int i, t;
18514   unsigned char zBuf[20];
18515   unsigned char *z;
18516   unsigned char *zTerm;
18517   int n;
18518   unsigned int c;
18519
18520   for(i=0; i<0x00110000; i++){
18521     z = zBuf;
18522     WRITE_UTF8(z, i);
18523     n = z-zBuf;
18524     z[0] = 0;
18525     zTerm = z;
18526     z = zBuf;
18527     c = sqlite3Utf8Read(z, zTerm, (const u8**)&z);
18528     t = i;
18529     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
18530     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
18531     assert( c==t );
18532     assert( (z-zBuf)==n );
18533   }
18534   for(i=0; i<0x00110000; i++){
18535     if( i>=0xD800 && i<0xE000 ) continue;
18536     z = zBuf;
18537     WRITE_UTF16LE(z, i);
18538     n = z-zBuf;
18539     z[0] = 0;
18540     z = zBuf;
18541     READ_UTF16LE(z, c);
18542     assert( c==i );
18543     assert( (z-zBuf)==n );
18544   }
18545   for(i=0; i<0x00110000; i++){
18546     if( i>=0xD800 && i<0xE000 ) continue;
18547     z = zBuf;
18548     WRITE_UTF16BE(z, i);
18549     n = z-zBuf;
18550     z[0] = 0;
18551     z = zBuf;
18552     READ_UTF16BE(z, c);
18553     assert( c==i );
18554     assert( (z-zBuf)==n );
18555   }
18556 }
18557 #endif /* SQLITE_TEST */
18558 #endif /* SQLITE_OMIT_UTF16 */
18559
18560 /************** End of utf.c *************************************************/
18561 /************** Begin file util.c ********************************************/
18562 /*
18563 ** 2001 September 15
18564 **
18565 ** The author disclaims copyright to this source code.  In place of
18566 ** a legal notice, here is a blessing:
18567 **
18568 **    May you do good and not evil.
18569 **    May you find forgiveness for yourself and forgive others.
18570 **    May you share freely, never taking more than you give.
18571 **
18572 *************************************************************************
18573 ** Utility functions used throughout sqlite.
18574 **
18575 ** This file contains functions for allocating memory, comparing
18576 ** strings, and stuff like that.
18577 **
18578 ** $Id: util.c,v 1.241 2008/07/28 19:34:54 drh Exp $
18579 */
18580
18581
18582 /*
18583 ** Return true if the floating point value is Not a Number (NaN).
18584 */
18585 SQLITE_PRIVATE int sqlite3IsNaN(double x){
18586   /* This NaN test sometimes fails if compiled on GCC with -ffast-math.
18587   ** On the other hand, the use of -ffast-math comes with the following
18588   ** warning:
18589   **
18590   **      This option [-ffast-math] should never be turned on by any
18591   **      -O option since it can result in incorrect output for programs
18592   **      which depend on an exact implementation of IEEE or ISO 
18593   **      rules/specifications for math functions.
18594   **
18595   ** Under MSVC, this NaN test may fail if compiled with a floating-
18596   ** point precision mode other than /fp:precise.  From the MSDN 
18597   ** documentation:
18598   **
18599   **      The compiler [with /fp:precise] will properly handle comparisons 
18600   **      involving NaN. For example, x != x evaluates to true if x is NaN 
18601   **      ...
18602   */
18603 #ifdef __FAST_MATH__
18604 # error SQLite will not work correctly with the -ffast-math option of GCC.
18605 #endif
18606   volatile double y = x;
18607   volatile double z = y;
18608   return y!=z;
18609 }
18610
18611 /*
18612 ** Return the length of a string, except do not allow the string length
18613 ** to exceed the SQLITE_LIMIT_LENGTH setting.
18614 */
18615 SQLITE_PRIVATE int sqlite3Strlen(sqlite3 *db, const char *z){
18616   const char *z2 = z;
18617   int len;
18618   size_t x;
18619   while( *z2 ){ z2++; }
18620   x = z2 - z;
18621   len = 0x7fffffff & x;
18622   if( len!=x || len > db->aLimit[SQLITE_LIMIT_LENGTH] ){
18623     return db->aLimit[SQLITE_LIMIT_LENGTH];
18624   }else{
18625     return len;
18626   }
18627 }
18628
18629 /*
18630 ** Set the most recent error code and error string for the sqlite
18631 ** handle "db". The error code is set to "err_code".
18632 **
18633 ** If it is not NULL, string zFormat specifies the format of the
18634 ** error string in the style of the printf functions: The following
18635 ** format characters are allowed:
18636 **
18637 **      %s      Insert a string
18638 **      %z      A string that should be freed after use
18639 **      %d      Insert an integer
18640 **      %T      Insert a token
18641 **      %S      Insert the first element of a SrcList
18642 **
18643 ** zFormat and any string tokens that follow it are assumed to be
18644 ** encoded in UTF-8.
18645 **
18646 ** To clear the most recent error for sqlite handle "db", sqlite3Error
18647 ** should be called with err_code set to SQLITE_OK and zFormat set
18648 ** to NULL.
18649 */
18650 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
18651   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
18652     db->errCode = err_code;
18653     if( zFormat ){
18654       char *z;
18655       va_list ap;
18656       va_start(ap, zFormat);
18657       z = sqlite3VMPrintf(db, zFormat, ap);
18658       va_end(ap);
18659       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
18660     }else{
18661       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
18662     }
18663   }
18664 }
18665
18666 /*
18667 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
18668 ** The following formatting characters are allowed:
18669 **
18670 **      %s      Insert a string
18671 **      %z      A string that should be freed after use
18672 **      %d      Insert an integer
18673 **      %T      Insert a token
18674 **      %S      Insert the first element of a SrcList
18675 **
18676 ** This function should be used to report any error that occurs whilst
18677 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
18678 ** last thing the sqlite3_prepare() function does is copy the error
18679 ** stored by this function into the database handle using sqlite3Error().
18680 ** Function sqlite3Error() should be used during statement execution
18681 ** (sqlite3_step() etc.).
18682 */
18683 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
18684   va_list ap;
18685   sqlite3 *db = pParse->db;
18686   pParse->nErr++;
18687   sqlite3DbFree(db, pParse->zErrMsg);
18688   va_start(ap, zFormat);
18689   pParse->zErrMsg = sqlite3VMPrintf(db, zFormat, ap);
18690   va_end(ap);
18691   if( pParse->rc==SQLITE_OK ){
18692     pParse->rc = SQLITE_ERROR;
18693   }
18694 }
18695
18696 /*
18697 ** Clear the error message in pParse, if any
18698 */
18699 SQLITE_PRIVATE void sqlite3ErrorClear(Parse *pParse){
18700   sqlite3DbFree(pParse->db, pParse->zErrMsg);
18701   pParse->zErrMsg = 0;
18702   pParse->nErr = 0;
18703 }
18704
18705 /*
18706 ** Convert an SQL-style quoted string into a normal string by removing
18707 ** the quote characters.  The conversion is done in-place.  If the
18708 ** input does not begin with a quote character, then this routine
18709 ** is a no-op.
18710 **
18711 ** 2002-Feb-14: This routine is extended to remove MS-Access style
18712 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
18713 ** "a-b-c".
18714 */
18715 SQLITE_PRIVATE void sqlite3Dequote(char *z){
18716   int quote;
18717   int i, j;
18718   if( z==0 ) return;
18719   quote = z[0];
18720   switch( quote ){
18721     case '\'':  break;
18722     case '"':   break;
18723     case '`':   break;                /* For MySQL compatibility */
18724     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
18725     default:    return;
18726   }
18727   for(i=1, j=0; z[i]; i++){
18728     if( z[i]==quote ){
18729       if( z[i+1]==quote ){
18730         z[j++] = quote;
18731         i++;
18732       }else{
18733         z[j++] = 0;
18734         break;
18735       }
18736     }else{
18737       z[j++] = z[i];
18738     }
18739   }
18740 }
18741
18742 /* Convenient short-hand */
18743 #define UpperToLower sqlite3UpperToLower
18744
18745 /*
18746 ** Some systems have stricmp().  Others have strcasecmp().  Because
18747 ** there is no consistency, we will define our own.
18748 */
18749 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
18750   register unsigned char *a, *b;
18751   a = (unsigned char *)zLeft;
18752   b = (unsigned char *)zRight;
18753   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
18754   return UpperToLower[*a] - UpperToLower[*b];
18755 }
18756 SQLITE_PRIVATE int sqlite3StrNICmp(const char *zLeft, const char *zRight, int N){
18757   register unsigned char *a, *b;
18758   a = (unsigned char *)zLeft;
18759   b = (unsigned char *)zRight;
18760   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
18761   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
18762 }
18763
18764 /*
18765 ** Return TRUE if z is a pure numeric string.  Return FALSE if the
18766 ** string contains any character which is not part of a number. If
18767 ** the string is numeric and contains the '.' character, set *realnum
18768 ** to TRUE (otherwise FALSE).
18769 **
18770 ** An empty string is considered non-numeric.
18771 */
18772 SQLITE_PRIVATE int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
18773   int incr = (enc==SQLITE_UTF8?1:2);
18774   if( enc==SQLITE_UTF16BE ) z++;
18775   if( *z=='-' || *z=='+' ) z += incr;
18776   if( !isdigit(*(u8*)z) ){
18777     return 0;
18778   }
18779   z += incr;
18780   if( realnum ) *realnum = 0;
18781   while( isdigit(*(u8*)z) ){ z += incr; }
18782   if( *z=='.' ){
18783     z += incr;
18784     if( !isdigit(*(u8*)z) ) return 0;
18785     while( isdigit(*(u8*)z) ){ z += incr; }
18786     if( realnum ) *realnum = 1;
18787   }
18788   if( *z=='e' || *z=='E' ){
18789     z += incr;
18790     if( *z=='+' || *z=='-' ) z += incr;
18791     if( !isdigit(*(u8*)z) ) return 0;
18792     while( isdigit(*(u8*)z) ){ z += incr; }
18793     if( realnum ) *realnum = 1;
18794   }
18795   return *z==0;
18796 }
18797
18798 /*
18799 ** The string z[] is an ascii representation of a real number.
18800 ** Convert this string to a double.
18801 **
18802 ** This routine assumes that z[] really is a valid number.  If it
18803 ** is not, the result is undefined.
18804 **
18805 ** This routine is used instead of the library atof() function because
18806 ** the library atof() might want to use "," as the decimal point instead
18807 ** of "." depending on how locale is set.  But that would cause problems
18808 ** for SQL.  So this routine always uses "." regardless of locale.
18809 */
18810 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult){
18811 #ifndef SQLITE_OMIT_FLOATING_POINT
18812   int sign = 1;
18813   const char *zBegin = z;
18814   LONGDOUBLE_TYPE v1 = 0.0;
18815   int nSignificant = 0;
18816   while( isspace(*(u8*)z) ) z++;
18817   if( *z=='-' ){
18818     sign = -1;
18819     z++;
18820   }else if( *z=='+' ){
18821     z++;
18822   }
18823   while( z[0]=='0' ){
18824     z++;
18825   }
18826   while( isdigit(*(u8*)z) ){
18827     v1 = v1*10.0 + (*z - '0');
18828     z++;
18829     nSignificant++;
18830   }
18831   if( *z=='.' ){
18832     LONGDOUBLE_TYPE divisor = 1.0;
18833     z++;
18834     if( nSignificant==0 ){
18835       while( z[0]=='0' ){
18836         divisor *= 10.0;
18837         z++;
18838       }
18839     }
18840     while( isdigit(*(u8*)z) ){
18841       if( nSignificant<18 ){
18842         v1 = v1*10.0 + (*z - '0');
18843         divisor *= 10.0;
18844         nSignificant++;
18845       }
18846       z++;
18847     }
18848     v1 /= divisor;
18849   }
18850   if( *z=='e' || *z=='E' ){
18851     int esign = 1;
18852     int eval = 0;
18853     LONGDOUBLE_TYPE scale = 1.0;
18854     z++;
18855     if( *z=='-' ){
18856       esign = -1;
18857       z++;
18858     }else if( *z=='+' ){
18859       z++;
18860     }
18861     while( isdigit(*(u8*)z) ){
18862       eval = eval*10 + *z - '0';
18863       z++;
18864     }
18865     while( eval>=64 ){ scale *= 1.0e+64; eval -= 64; }
18866     while( eval>=16 ){ scale *= 1.0e+16; eval -= 16; }
18867     while( eval>=4 ){ scale *= 1.0e+4; eval -= 4; }
18868     while( eval>=1 ){ scale *= 1.0e+1; eval -= 1; }
18869     if( esign<0 ){
18870       v1 /= scale;
18871     }else{
18872       v1 *= scale;
18873     }
18874   }
18875   *pResult = sign<0 ? -v1 : v1;
18876   return z - zBegin;
18877 #else
18878   return sqlite3Atoi64(z, pResult);
18879 #endif /* SQLITE_OMIT_FLOATING_POINT */
18880 }
18881
18882 /*
18883 ** Compare the 19-character string zNum against the text representation
18884 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
18885 ** if zNum is less than, equal to, or greater than the string.
18886 **
18887 ** Unlike memcmp() this routine is guaranteed to return the difference
18888 ** in the values of the last digit if the only difference is in the
18889 ** last digit.  So, for example,
18890 **
18891 **      compare2pow63("9223372036854775800")
18892 **
18893 ** will return -8.
18894 */
18895 static int compare2pow63(const char *zNum){
18896   int c;
18897   c = memcmp(zNum,"922337203685477580",18);
18898   if( c==0 ){
18899     c = zNum[18] - '8';
18900   }
18901   return c;
18902 }
18903
18904
18905 /*
18906 ** Return TRUE if zNum is a 64-bit signed integer and write
18907 ** the value of the integer into *pNum.  If zNum is not an integer
18908 ** or is an integer that is too large to be expressed with 64 bits,
18909 ** then return false.
18910 **
18911 ** When this routine was originally written it dealt with only
18912 ** 32-bit numbers.  At that time, it was much faster than the
18913 ** atoi() library routine in RedHat 7.2.
18914 */
18915 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum){
18916   i64 v = 0;
18917   int neg;
18918   int i, c;
18919   const char *zStart;
18920   while( isspace(*(u8*)zNum) ) zNum++;
18921   if( *zNum=='-' ){
18922     neg = 1;
18923     zNum++;
18924   }else if( *zNum=='+' ){
18925     neg = 0;
18926     zNum++;
18927   }else{
18928     neg = 0;
18929   }
18930   zStart = zNum;
18931   while( zNum[0]=='0' ){ zNum++; } /* Skip over leading zeros. Ticket #2454 */
18932   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
18933     v = v*10 + c - '0';
18934   }
18935   *pNum = neg ? -v : v;
18936   if( c!=0 || (i==0 && zStart==zNum) || i>19 ){
18937     /* zNum is empty or contains non-numeric text or is longer
18938     ** than 19 digits (thus guaranting that it is too large) */
18939     return 0;
18940   }else if( i<19 ){
18941     /* Less than 19 digits, so we know that it fits in 64 bits */
18942     return 1;
18943   }else{
18944     /* 19-digit numbers must be no larger than 9223372036854775807 if positive
18945     ** or 9223372036854775808 if negative.  Note that 9223372036854665808
18946     ** is 2^63. */
18947     return compare2pow63(zNum)<neg;
18948   }
18949 }
18950
18951 /*
18952 ** The string zNum represents an integer.  There might be some other
18953 ** information following the integer too, but that part is ignored.
18954 ** If the integer that the prefix of zNum represents will fit in a
18955 ** 64-bit signed integer, return TRUE.  Otherwise return FALSE.
18956 **
18957 ** This routine returns FALSE for the string -9223372036854775808 even that
18958 ** that number will, in theory fit in a 64-bit integer.  Positive
18959 ** 9223373036854775808 will not fit in 64 bits.  So it seems safer to return
18960 ** false.
18961 */
18962 SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *zNum, int negFlag){
18963   int i, c;
18964   int neg = 0;
18965   if( *zNum=='-' ){
18966     neg = 1;
18967     zNum++;
18968   }else if( *zNum=='+' ){
18969     zNum++;
18970   }
18971   if( negFlag ) neg = 1-neg;
18972   while( *zNum=='0' ){
18973     zNum++;   /* Skip leading zeros.  Ticket #2454 */
18974   }
18975   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
18976   if( i<19 ){
18977     /* Guaranteed to fit if less than 19 digits */
18978     return 1;
18979   }else if( i>19 ){
18980     /* Guaranteed to be too big if greater than 19 digits */
18981     return 0;
18982   }else{
18983     /* Compare against 2^63. */
18984     return compare2pow63(zNum)<neg;
18985   }
18986 }
18987
18988 /*
18989 ** If zNum represents an integer that will fit in 32-bits, then set
18990 ** *pValue to that integer and return true.  Otherwise return false.
18991 **
18992 ** Any non-numeric characters that following zNum are ignored.
18993 ** This is different from sqlite3Atoi64() which requires the
18994 ** input number to be zero-terminated.
18995 */
18996 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
18997   sqlite_int64 v = 0;
18998   int i, c;
18999   int neg = 0;
19000   if( zNum[0]=='-' ){
19001     neg = 1;
19002     zNum++;
19003   }else if( zNum[0]=='+' ){
19004     zNum++;
19005   }
19006   while( zNum[0]=='0' ) zNum++;
19007   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
19008     v = v*10 + c;
19009   }
19010
19011   /* The longest decimal representation of a 32 bit integer is 10 digits:
19012   **
19013   **             1234567890
19014   **     2^31 -> 2147483648
19015   */
19016   if( i>10 ){
19017     return 0;
19018   }
19019   if( v-neg>2147483647 ){
19020     return 0;
19021   }
19022   if( neg ){
19023     v = -v;
19024   }
19025   *pValue = (int)v;
19026   return 1;
19027 }
19028
19029 /*
19030 ** The variable-length integer encoding is as follows:
19031 **
19032 ** KEY:
19033 **         A = 0xxxxxxx    7 bits of data and one flag bit
19034 **         B = 1xxxxxxx    7 bits of data and one flag bit
19035 **         C = xxxxxxxx    8 bits of data
19036 **
19037 **  7 bits - A
19038 ** 14 bits - BA
19039 ** 21 bits - BBA
19040 ** 28 bits - BBBA
19041 ** 35 bits - BBBBA
19042 ** 42 bits - BBBBBA
19043 ** 49 bits - BBBBBBA
19044 ** 56 bits - BBBBBBBA
19045 ** 64 bits - BBBBBBBBC
19046 */
19047
19048 /*
19049 ** Write a 64-bit variable-length integer to memory starting at p[0].
19050 ** The length of data write will be between 1 and 9 bytes.  The number
19051 ** of bytes written is returned.
19052 **
19053 ** A variable-length integer consists of the lower 7 bits of each byte
19054 ** for all bytes that have the 8th bit set and one byte with the 8th
19055 ** bit clear.  Except, if we get to the 9th byte, it stores the full
19056 ** 8 bits and is the last byte.
19057 */
19058 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
19059   int i, j, n;
19060   u8 buf[10];
19061   if( v & (((u64)0xff000000)<<32) ){
19062     p[8] = v;
19063     v >>= 8;
19064     for(i=7; i>=0; i--){
19065       p[i] = (v & 0x7f) | 0x80;
19066       v >>= 7;
19067     }
19068     return 9;
19069   }    
19070   n = 0;
19071   do{
19072     buf[n++] = (v & 0x7f) | 0x80;
19073     v >>= 7;
19074   }while( v!=0 );
19075   buf[0] &= 0x7f;
19076   assert( n<=9 );
19077   for(i=0, j=n-1; j>=0; j--, i++){
19078     p[i] = buf[j];
19079   }
19080   return n;
19081 }
19082
19083 /*
19084 ** This routine is a faster version of sqlite3PutVarint() that only
19085 ** works for 32-bit positive integers and which is optimized for
19086 ** the common case of small integers.  A MACRO version, putVarint32,
19087 ** is provided which inlines the single-byte case.  All code should use
19088 ** the MACRO version as this function assumes the single-byte case has
19089 ** already been handled.
19090 */
19091 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
19092 #ifndef putVarint32
19093   if( (v & ~0x7f)==0 ){
19094     p[0] = v;
19095     return 1;
19096   }
19097 #endif
19098   if( (v & ~0x3fff)==0 ){
19099     p[0] = (v>>7) | 0x80;
19100     p[1] = v & 0x7f;
19101     return 2;
19102   }
19103   return sqlite3PutVarint(p, v);
19104 }
19105
19106 /*
19107 ** Read a 64-bit variable-length integer from memory starting at p[0].
19108 ** Return the number of bytes read.  The value is stored in *v.
19109 */
19110 SQLITE_PRIVATE int sqlite3GetVarint(const unsigned char *p, u64 *v){
19111   u32 a,b,s;
19112
19113   a = *p;
19114   /* a: p0 (unmasked) */
19115   if (!(a&0x80))
19116   {
19117     *v = a;
19118     return 1;
19119   }
19120
19121   p++;
19122   b = *p;
19123   /* b: p1 (unmasked) */
19124   if (!(b&0x80))
19125   {
19126     a &= 0x7f;
19127     a = a<<7;
19128     a |= b;
19129     *v = a;
19130     return 2;
19131   }
19132
19133   p++;
19134   a = a<<14;
19135   a |= *p;
19136   /* a: p0<<14 | p2 (unmasked) */
19137   if (!(a&0x80))
19138   {
19139     a &= (0x7f<<14)|(0x7f);
19140     b &= 0x7f;
19141     b = b<<7;
19142     a |= b;
19143     *v = a;
19144     return 3;
19145   }
19146
19147   /* CSE1 from below */
19148   a &= (0x7f<<14)|(0x7f);
19149   p++;
19150   b = b<<14;
19151   b |= *p;
19152   /* b: p1<<14 | p3 (unmasked) */
19153   if (!(b&0x80))
19154   {
19155     b &= (0x7f<<14)|(0x7f);
19156     /* moved CSE1 up */
19157     /* a &= (0x7f<<14)|(0x7f); */
19158     a = a<<7;
19159     a |= b;
19160     *v = a;
19161     return 4;
19162   }
19163
19164   /* a: p0<<14 | p2 (masked) */
19165   /* b: p1<<14 | p3 (unmasked) */
19166   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
19167   /* moved CSE1 up */
19168   /* a &= (0x7f<<14)|(0x7f); */
19169   b &= (0x7f<<14)|(0x7f);
19170   s = a;
19171   /* s: p0<<14 | p2 (masked) */
19172
19173   p++;
19174   a = a<<14;
19175   a |= *p;
19176   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
19177   if (!(a&0x80))
19178   {
19179     /* we can skip these cause they were (effectively) done above in calc'ing s */
19180     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
19181     /* b &= (0x7f<<14)|(0x7f); */
19182     b = b<<7;
19183     a |= b;
19184     s = s>>18;
19185     *v = ((u64)s)<<32 | a;
19186     return 5;
19187   }
19188
19189   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
19190   s = s<<7;
19191   s |= b;
19192   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
19193
19194   p++;
19195   b = b<<14;
19196   b |= *p;
19197   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
19198   if (!(b&0x80))
19199   {
19200     /* we can skip this cause it was (effectively) done above in calc'ing s */
19201     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
19202     a &= (0x7f<<14)|(0x7f);
19203     a = a<<7;
19204     a |= b;
19205     s = s>>18;
19206     *v = ((u64)s)<<32 | a;
19207     return 6;
19208   }
19209
19210   p++;
19211   a = a<<14;
19212   a |= *p;
19213   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
19214   if (!(a&0x80))
19215   {
19216     a &= (0x7f<<28)|(0x7f<<14)|(0x7f);
19217     b &= (0x7f<<14)|(0x7f);
19218     b = b<<7;
19219     a |= b;
19220     s = s>>11;
19221     *v = ((u64)s)<<32 | a;
19222     return 7;
19223   }
19224
19225   /* CSE2 from below */
19226   a &= (0x7f<<14)|(0x7f);
19227   p++;
19228   b = b<<14;
19229   b |= *p;
19230   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
19231   if (!(b&0x80))
19232   {
19233     b &= (0x7f<<28)|(0x7f<<14)|(0x7f);
19234     /* moved CSE2 up */
19235     /* a &= (0x7f<<14)|(0x7f); */
19236     a = a<<7;
19237     a |= b;
19238     s = s>>4;
19239     *v = ((u64)s)<<32 | a;
19240     return 8;
19241   }
19242
19243   p++;
19244   a = a<<15;
19245   a |= *p;
19246   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
19247
19248   /* moved CSE2 up */
19249   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
19250   b &= (0x7f<<14)|(0x7f);
19251   b = b<<8;
19252   a |= b;
19253
19254   s = s<<4;
19255   b = p[-4];
19256   b &= 0x7f;
19257   b = b>>3;
19258   s |= b;
19259
19260   *v = ((u64)s)<<32 | a;
19261
19262   return 9;
19263 }
19264
19265 /*
19266 ** Read a 32-bit variable-length integer from memory starting at p[0].
19267 ** Return the number of bytes read.  The value is stored in *v.
19268 ** A MACRO version, getVarint32, is provided which inlines the 
19269 ** single-byte case.  All code should use the MACRO version as 
19270 ** this function assumes the single-byte case has already been handled.
19271 */
19272 SQLITE_PRIVATE int sqlite3GetVarint32(const unsigned char *p, u32 *v){
19273   u32 a,b;
19274
19275   a = *p;
19276   /* a: p0 (unmasked) */
19277 #ifndef getVarint32
19278   if (!(a&0x80))
19279   {
19280     *v = a;
19281     return 1;
19282   }
19283 #endif
19284
19285   p++;
19286   b = *p;
19287   /* b: p1 (unmasked) */
19288   if (!(b&0x80))
19289   {
19290     a &= 0x7f;
19291     a = a<<7;
19292     *v = a | b;
19293     return 2;
19294   }
19295
19296   p++;
19297   a = a<<14;
19298   a |= *p;
19299   /* a: p0<<14 | p2 (unmasked) */
19300   if (!(a&0x80))
19301   {
19302     a &= (0x7f<<14)|(0x7f);
19303     b &= 0x7f;
19304     b = b<<7;
19305     *v = a | b;
19306     return 3;
19307   }
19308
19309   p++;
19310   b = b<<14;
19311   b |= *p;
19312   /* b: p1<<14 | p3 (unmasked) */
19313   if (!(b&0x80))
19314   {
19315     b &= (0x7f<<14)|(0x7f);
19316     a &= (0x7f<<14)|(0x7f);
19317     a = a<<7;
19318     *v = a | b;
19319     return 4;
19320   }
19321
19322   p++;
19323   a = a<<14;
19324   a |= *p;
19325   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
19326   if (!(a&0x80))
19327   {
19328     a &= (0x7f<<28)|(0x7f<<14)|(0x7f);
19329     b &= (0x7f<<28)|(0x7f<<14)|(0x7f);
19330     b = b<<7;
19331     *v = a | b;
19332     return 5;
19333   }
19334
19335   /* We can only reach this point when reading a corrupt database
19336   ** file.  In that case we are not in any hurry.  Use the (relatively
19337   ** slow) general-purpose sqlite3GetVarint() routine to extract the
19338   ** value. */
19339   {
19340     u64 v64;
19341     int n;
19342
19343     p -= 4;
19344     n = sqlite3GetVarint(p, &v64);
19345     assert( n>5 && n<=9 );
19346     *v = (u32)v64;
19347     return n;
19348   }
19349 }
19350
19351 /*
19352 ** Return the number of bytes that will be needed to store the given
19353 ** 64-bit integer.
19354 */
19355 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
19356   int i = 0;
19357   do{
19358     i++;
19359     v >>= 7;
19360   }while( v!=0 && i<9 );
19361   return i;
19362 }
19363
19364
19365 /*
19366 ** Read or write a four-byte big-endian integer value.
19367 */
19368 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
19369   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
19370 }
19371 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
19372   p[0] = v>>24;
19373   p[1] = v>>16;
19374   p[2] = v>>8;
19375   p[3] = v;
19376 }
19377
19378
19379
19380 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
19381 /*
19382 ** Translate a single byte of Hex into an integer.
19383 ** This routinen only works if h really is a valid hexadecimal
19384 ** character:  0..9a..fA..F
19385 */
19386 static int hexToInt(int h){
19387   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
19388 #ifdef SQLITE_ASCII
19389   h += 9*(1&(h>>6));
19390 #endif
19391 #ifdef SQLITE_EBCDIC
19392   h += 9*(1&~(h>>4));
19393 #endif
19394   return h & 0xf;
19395 }
19396 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
19397
19398 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
19399 /*
19400 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
19401 ** value.  Return a pointer to its binary value.  Space to hold the
19402 ** binary value has been obtained from malloc and must be freed by
19403 ** the calling routine.
19404 */
19405 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
19406   char *zBlob;
19407   int i;
19408
19409   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
19410   n--;
19411   if( zBlob ){
19412     for(i=0; i<n; i+=2){
19413       zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
19414     }
19415     zBlob[i/2] = 0;
19416   }
19417   return zBlob;
19418 }
19419 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
19420
19421
19422 /*
19423 ** Change the sqlite.magic from SQLITE_MAGIC_OPEN to SQLITE_MAGIC_BUSY.
19424 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_OPEN
19425 ** when this routine is called.
19426 **
19427 ** This routine is called when entering an SQLite API.  The SQLITE_MAGIC_OPEN
19428 ** value indicates that the database connection passed into the API is
19429 ** open and is not being used by another thread.  By changing the value
19430 ** to SQLITE_MAGIC_BUSY we indicate that the connection is in use.
19431 ** sqlite3SafetyOff() below will change the value back to SQLITE_MAGIC_OPEN
19432 ** when the API exits. 
19433 **
19434 ** This routine is a attempt to detect if two threads use the
19435 ** same sqlite* pointer at the same time.  There is a race 
19436 ** condition so it is possible that the error is not detected.
19437 ** But usually the problem will be seen.  The result will be an
19438 ** error which can be used to debug the application that is
19439 ** using SQLite incorrectly.
19440 **
19441 ** Ticket #202:  If db->magic is not a valid open value, take care not
19442 ** to modify the db structure at all.  It could be that db is a stale
19443 ** pointer.  In other words, it could be that there has been a prior
19444 ** call to sqlite3_close(db) and db has been deallocated.  And we do
19445 ** not want to write into deallocated memory.
19446 */
19447 #ifdef SQLITE_DEBUG
19448 SQLITE_PRIVATE int sqlite3SafetyOn(sqlite3 *db){
19449   if( db->magic==SQLITE_MAGIC_OPEN ){
19450     db->magic = SQLITE_MAGIC_BUSY;
19451     assert( sqlite3_mutex_held(db->mutex) );
19452     return 0;
19453   }else if( db->magic==SQLITE_MAGIC_BUSY ){
19454     db->magic = SQLITE_MAGIC_ERROR;
19455     db->u1.isInterrupted = 1;
19456   }
19457   return 1;
19458 }
19459 #endif
19460
19461 /*
19462 ** Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN.
19463 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY
19464 ** when this routine is called.
19465 */
19466 #ifdef SQLITE_DEBUG
19467 SQLITE_PRIVATE int sqlite3SafetyOff(sqlite3 *db){
19468   if( db->magic==SQLITE_MAGIC_BUSY ){
19469     db->magic = SQLITE_MAGIC_OPEN;
19470     assert( sqlite3_mutex_held(db->mutex) );
19471     return 0;
19472   }else{
19473     db->magic = SQLITE_MAGIC_ERROR;
19474     db->u1.isInterrupted = 1;
19475     return 1;
19476   }
19477 }
19478 #endif
19479
19480 /*
19481 ** Check to make sure we have a valid db pointer.  This test is not
19482 ** foolproof but it does provide some measure of protection against
19483 ** misuse of the interface such as passing in db pointers that are
19484 ** NULL or which have been previously closed.  If this routine returns
19485 ** 1 it means that the db pointer is valid and 0 if it should not be
19486 ** dereferenced for any reason.  The calling function should invoke
19487 ** SQLITE_MISUSE immediately.
19488 **
19489 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
19490 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
19491 ** open properly and is not fit for general use but which can be
19492 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
19493 */
19494 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
19495   int magic;
19496   if( db==0 ) return 0;
19497   magic = db->magic;
19498   if( magic!=SQLITE_MAGIC_OPEN &&
19499       magic!=SQLITE_MAGIC_BUSY ) return 0;
19500   return 1;
19501 }
19502 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
19503   int magic;
19504   if( db==0 ) return 0;
19505   magic = db->magic;
19506   if( magic!=SQLITE_MAGIC_SICK &&
19507       magic!=SQLITE_MAGIC_OPEN &&
19508       magic!=SQLITE_MAGIC_BUSY ) return 0;
19509   return 1;
19510 }
19511
19512 /************** End of util.c ************************************************/
19513 /************** Begin file hash.c ********************************************/
19514 /*
19515 ** 2001 September 22
19516 **
19517 ** The author disclaims copyright to this source code.  In place of
19518 ** a legal notice, here is a blessing:
19519 **
19520 **    May you do good and not evil.
19521 **    May you find forgiveness for yourself and forgive others.
19522 **    May you share freely, never taking more than you give.
19523 **
19524 *************************************************************************
19525 ** This is the implementation of generic hash-tables
19526 ** used in SQLite.
19527 **
19528 ** $Id: hash.c,v 1.30 2008/06/20 14:59:51 danielk1977 Exp $
19529 */
19530
19531 /* Turn bulk memory into a hash table object by initializing the
19532 ** fields of the Hash structure.
19533 **
19534 ** "pNew" is a pointer to the hash table that is to be initialized.
19535 ** keyClass is one of the constants SQLITE_HASH_INT, SQLITE_HASH_POINTER,
19536 ** SQLITE_HASH_BINARY, or SQLITE_HASH_STRING.  The value of keyClass 
19537 ** determines what kind of key the hash table will use.  "copyKey" is
19538 ** true if the hash table should make its own private copy of keys and
19539 ** false if it should just use the supplied pointer.  CopyKey only makes
19540 ** sense for SQLITE_HASH_STRING and SQLITE_HASH_BINARY and is ignored
19541 ** for other key classes.
19542 */
19543 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew, int keyClass, int copyKey){
19544   assert( pNew!=0 );
19545   assert( keyClass>=SQLITE_HASH_STRING && keyClass<=SQLITE_HASH_BINARY );
19546   pNew->keyClass = keyClass;
19547 #if 0
19548   if( keyClass==SQLITE_HASH_POINTER || keyClass==SQLITE_HASH_INT ) copyKey = 0;
19549 #endif
19550   pNew->copyKey = copyKey;
19551   pNew->first = 0;
19552   pNew->count = 0;
19553   pNew->htsize = 0;
19554   pNew->ht = 0;
19555 }
19556
19557 /* Remove all entries from a hash table.  Reclaim all memory.
19558 ** Call this routine to delete a hash table or to reset a hash table
19559 ** to the empty state.
19560 */
19561 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
19562   HashElem *elem;         /* For looping over all elements of the table */
19563
19564   assert( pH!=0 );
19565   elem = pH->first;
19566   pH->first = 0;
19567   sqlite3_free(pH->ht);
19568   pH->ht = 0;
19569   pH->htsize = 0;
19570   while( elem ){
19571     HashElem *next_elem = elem->next;
19572     if( pH->copyKey && elem->pKey ){
19573       sqlite3_free(elem->pKey);
19574     }
19575     sqlite3_free(elem);
19576     elem = next_elem;
19577   }
19578   pH->count = 0;
19579 }
19580
19581 #if 0 /* NOT USED */
19582 /*
19583 ** Hash and comparison functions when the mode is SQLITE_HASH_INT
19584 */
19585 static int intHash(const void *pKey, int nKey){
19586   return nKey ^ (nKey<<8) ^ (nKey>>8);
19587 }
19588 static int intCompare(const void *pKey1, int n1, const void *pKey2, int n2){
19589   return n2 - n1;
19590 }
19591 #endif
19592
19593 #if 0 /* NOT USED */
19594 /*
19595 ** Hash and comparison functions when the mode is SQLITE_HASH_POINTER
19596 */
19597 static int ptrHash(const void *pKey, int nKey){
19598   uptr x = Addr(pKey);
19599   return x ^ (x<<8) ^ (x>>8);
19600 }
19601 static int ptrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
19602   if( pKey1==pKey2 ) return 0;
19603   if( pKey1<pKey2 ) return -1;
19604   return 1;
19605 }
19606 #endif
19607
19608 /*
19609 ** Hash and comparison functions when the mode is SQLITE_HASH_STRING
19610 */
19611 static int strHash(const void *pKey, int nKey){
19612   const char *z = (const char *)pKey;
19613   int h = 0;
19614   if( nKey<=0 ) nKey = strlen(z);
19615   while( nKey > 0  ){
19616     h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
19617     nKey--;
19618   }
19619   return h & 0x7fffffff;
19620 }
19621 static int strCompare(const void *pKey1, int n1, const void *pKey2, int n2){
19622   if( n1!=n2 ) return 1;
19623   return sqlite3StrNICmp((const char*)pKey1,(const char*)pKey2,n1);
19624 }
19625
19626 /*
19627 ** Hash and comparison functions when the mode is SQLITE_HASH_BINARY
19628 */
19629 static int binHash(const void *pKey, int nKey){
19630   int h = 0;
19631   const char *z = (const char *)pKey;
19632   while( nKey-- > 0 ){
19633     h = (h<<3) ^ h ^ *(z++);
19634   }
19635   return h & 0x7fffffff;
19636 }
19637 static int binCompare(const void *pKey1, int n1, const void *pKey2, int n2){
19638   if( n1!=n2 ) return 1;
19639   return memcmp(pKey1,pKey2,n1);
19640 }
19641
19642 /*
19643 ** Return a pointer to the appropriate hash function given the key class.
19644 **
19645 ** The C syntax in this function definition may be unfamilar to some 
19646 ** programmers, so we provide the following additional explanation:
19647 **
19648 ** The name of the function is "hashFunction".  The function takes a
19649 ** single parameter "keyClass".  The return value of hashFunction()
19650 ** is a pointer to another function.  Specifically, the return value
19651 ** of hashFunction() is a pointer to a function that takes two parameters
19652 ** with types "const void*" and "int" and returns an "int".
19653 */
19654 static int (*hashFunction(int keyClass))(const void*,int){
19655 #if 0  /* HASH_INT and HASH_POINTER are never used */
19656   switch( keyClass ){
19657     case SQLITE_HASH_INT:     return &intHash;
19658     case SQLITE_HASH_POINTER: return &ptrHash;
19659     case SQLITE_HASH_STRING:  return &strHash;
19660     case SQLITE_HASH_BINARY:  return &binHash;;
19661     default: break;
19662   }
19663   return 0;
19664 #else
19665   if( keyClass==SQLITE_HASH_STRING ){
19666     return &strHash;
19667   }else{
19668     assert( keyClass==SQLITE_HASH_BINARY );
19669     return &binHash;
19670   }
19671 #endif
19672 }
19673
19674 /*
19675 ** Return a pointer to the appropriate hash function given the key class.
19676 **
19677 ** For help in interpreted the obscure C code in the function definition,
19678 ** see the header comment on the previous function.
19679 */
19680 static int (*compareFunction(int keyClass))(const void*,int,const void*,int){
19681 #if 0 /* HASH_INT and HASH_POINTER are never used */
19682   switch( keyClass ){
19683     case SQLITE_HASH_INT:     return &intCompare;
19684     case SQLITE_HASH_POINTER: return &ptrCompare;
19685     case SQLITE_HASH_STRING:  return &strCompare;
19686     case SQLITE_HASH_BINARY:  return &binCompare;
19687     default: break;
19688   }
19689   return 0;
19690 #else
19691   if( keyClass==SQLITE_HASH_STRING ){
19692     return &strCompare;
19693   }else{
19694     assert( keyClass==SQLITE_HASH_BINARY );
19695     return &binCompare;
19696   }
19697 #endif
19698 }
19699
19700 /* Link an element into the hash table
19701 */
19702 static void insertElement(
19703   Hash *pH,              /* The complete hash table */
19704   struct _ht *pEntry,    /* The entry into which pNew is inserted */
19705   HashElem *pNew         /* The element to be inserted */
19706 ){
19707   HashElem *pHead;       /* First element already in pEntry */
19708   pHead = pEntry->chain;
19709   if( pHead ){
19710     pNew->next = pHead;
19711     pNew->prev = pHead->prev;
19712     if( pHead->prev ){ pHead->prev->next = pNew; }
19713     else             { pH->first = pNew; }
19714     pHead->prev = pNew;
19715   }else{
19716     pNew->next = pH->first;
19717     if( pH->first ){ pH->first->prev = pNew; }
19718     pNew->prev = 0;
19719     pH->first = pNew;
19720   }
19721   pEntry->count++;
19722   pEntry->chain = pNew;
19723 }
19724
19725
19726 /* Resize the hash table so that it cantains "new_size" buckets.
19727 ** "new_size" must be a power of 2.  The hash table might fail 
19728 ** to resize if sqlite3_malloc() fails.
19729 */
19730 static void rehash(Hash *pH, int new_size){
19731   struct _ht *new_ht;            /* The new hash table */
19732   HashElem *elem, *next_elem;    /* For looping over existing elements */
19733   int (*xHash)(const void*,int); /* The hash function */
19734
19735 #ifdef SQLITE_MALLOC_SOFT_LIMIT
19736   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
19737     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
19738   }
19739   if( new_size==pH->htsize ) return;
19740 #endif
19741
19742   /* There is a call to sqlite3_malloc() inside rehash(). If there is
19743   ** already an allocation at pH->ht, then if this malloc() fails it
19744   ** is benign (since failing to resize a hash table is a performance
19745   ** hit only, not a fatal error).
19746   */
19747   if( pH->htsize>0 ) sqlite3BeginBenignMalloc();
19748   new_ht = (struct _ht *)sqlite3MallocZero( new_size*sizeof(struct _ht) );
19749   if( pH->htsize>0 ) sqlite3EndBenignMalloc();
19750
19751   if( new_ht==0 ) return;
19752   sqlite3_free(pH->ht);
19753   pH->ht = new_ht;
19754   pH->htsize = new_size;
19755   xHash = hashFunction(pH->keyClass);
19756   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
19757     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
19758     next_elem = elem->next;
19759     insertElement(pH, &new_ht[h], elem);
19760   }
19761 }
19762
19763 /* This function (for internal use only) locates an element in an
19764 ** hash table that matches the given key.  The hash for this key has
19765 ** already been computed and is passed as the 4th parameter.
19766 */
19767 static HashElem *findElementGivenHash(
19768   const Hash *pH,     /* The pH to be searched */
19769   const void *pKey,   /* The key we are searching for */
19770   int nKey,
19771   int h               /* The hash for this key. */
19772 ){
19773   HashElem *elem;                /* Used to loop thru the element list */
19774   int count;                     /* Number of elements left to test */
19775   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
19776
19777   if( pH->ht ){
19778     struct _ht *pEntry = &pH->ht[h];
19779     elem = pEntry->chain;
19780     count = pEntry->count;
19781     xCompare = compareFunction(pH->keyClass);
19782     while( count-- && elem ){
19783       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
19784         return elem;
19785       }
19786       elem = elem->next;
19787     }
19788   }
19789   return 0;
19790 }
19791
19792 /* Remove a single entry from the hash table given a pointer to that
19793 ** element and a hash on the element's key.
19794 */
19795 static void removeElementGivenHash(
19796   Hash *pH,         /* The pH containing "elem" */
19797   HashElem* elem,   /* The element to be removed from the pH */
19798   int h             /* Hash value for the element */
19799 ){
19800   struct _ht *pEntry;
19801   if( elem->prev ){
19802     elem->prev->next = elem->next; 
19803   }else{
19804     pH->first = elem->next;
19805   }
19806   if( elem->next ){
19807     elem->next->prev = elem->prev;
19808   }
19809   pEntry = &pH->ht[h];
19810   if( pEntry->chain==elem ){
19811     pEntry->chain = elem->next;
19812   }
19813   pEntry->count--;
19814   if( pEntry->count<=0 ){
19815     pEntry->chain = 0;
19816   }
19817   if( pH->copyKey ){
19818     sqlite3_free(elem->pKey);
19819   }
19820   sqlite3_free( elem );
19821   pH->count--;
19822   if( pH->count<=0 ){
19823     assert( pH->first==0 );
19824     assert( pH->count==0 );
19825     sqlite3HashClear(pH);
19826   }
19827 }
19828
19829 /* Attempt to locate an element of the hash table pH with a key
19830 ** that matches pKey,nKey.  Return a pointer to the corresponding 
19831 ** HashElem structure for this element if it is found, or NULL
19832 ** otherwise.
19833 */
19834 SQLITE_PRIVATE HashElem *sqlite3HashFindElem(const Hash *pH, const void *pKey, int nKey){
19835   int h;             /* A hash on key */
19836   HashElem *elem;    /* The element that matches key */
19837   int (*xHash)(const void*,int);  /* The hash function */
19838
19839   if( pH==0 || pH->ht==0 ) return 0;
19840   xHash = hashFunction(pH->keyClass);
19841   assert( xHash!=0 );
19842   h = (*xHash)(pKey,nKey);
19843   elem = findElementGivenHash(pH,pKey,nKey, h % pH->htsize);
19844   return elem;
19845 }
19846
19847 /* Attempt to locate an element of the hash table pH with a key
19848 ** that matches pKey,nKey.  Return the data for this element if it is
19849 ** found, or NULL if there is no match.
19850 */
19851 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const void *pKey, int nKey){
19852   HashElem *elem;    /* The element that matches key */
19853   elem = sqlite3HashFindElem(pH, pKey, nKey);
19854   return elem ? elem->data : 0;
19855 }
19856
19857 /* Insert an element into the hash table pH.  The key is pKey,nKey
19858 ** and the data is "data".
19859 **
19860 ** If no element exists with a matching key, then a new
19861 ** element is created.  A copy of the key is made if the copyKey
19862 ** flag is set.  NULL is returned.
19863 **
19864 ** If another element already exists with the same key, then the
19865 ** new data replaces the old data and the old data is returned.
19866 ** The key is not copied in this instance.  If a malloc fails, then
19867 ** the new data is returned and the hash table is unchanged.
19868 **
19869 ** If the "data" parameter to this function is NULL, then the
19870 ** element corresponding to "key" is removed from the hash table.
19871 */
19872 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const void *pKey, int nKey, void *data){
19873   int hraw;             /* Raw hash value of the key */
19874   int h;                /* the hash of the key modulo hash table size */
19875   HashElem *elem;       /* Used to loop thru the element list */
19876   HashElem *new_elem;   /* New element added to the pH */
19877   int (*xHash)(const void*,int);  /* The hash function */
19878
19879   assert( pH!=0 );
19880   xHash = hashFunction(pH->keyClass);
19881   assert( xHash!=0 );
19882   hraw = (*xHash)(pKey, nKey);
19883   if( pH->htsize ){
19884     h = hraw % pH->htsize;
19885     elem = findElementGivenHash(pH,pKey,nKey,h);
19886     if( elem ){
19887       void *old_data = elem->data;
19888       if( data==0 ){
19889         removeElementGivenHash(pH,elem,h);
19890       }else{
19891         elem->data = data;
19892         if( !pH->copyKey ){
19893           elem->pKey = (void *)pKey;
19894         }
19895         assert(nKey==elem->nKey);
19896       }
19897       return old_data;
19898     }
19899   }
19900   if( data==0 ) return 0;
19901   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
19902   if( new_elem==0 ) return data;
19903   if( pH->copyKey && pKey!=0 ){
19904     new_elem->pKey = sqlite3Malloc( nKey );
19905     if( new_elem->pKey==0 ){
19906       sqlite3_free(new_elem);
19907       return data;
19908     }
19909     memcpy((void*)new_elem->pKey, pKey, nKey);
19910   }else{
19911     new_elem->pKey = (void*)pKey;
19912   }
19913   new_elem->nKey = nKey;
19914   pH->count++;
19915   if( pH->htsize==0 ){
19916     rehash(pH, 128/sizeof(pH->ht[0]));
19917     if( pH->htsize==0 ){
19918       pH->count = 0;
19919       if( pH->copyKey ){
19920         sqlite3_free(new_elem->pKey);
19921       }
19922       sqlite3_free(new_elem);
19923       return data;
19924     }
19925   }
19926   if( pH->count > pH->htsize ){
19927     rehash(pH,pH->htsize*2);
19928   }
19929   assert( pH->htsize>0 );
19930   h = hraw % pH->htsize;
19931   insertElement(pH, &pH->ht[h], new_elem);
19932   new_elem->data = data;
19933   return 0;
19934 }
19935
19936 /************** End of hash.c ************************************************/
19937 /************** Begin file opcodes.c *****************************************/
19938 /* Automatically generated.  Do not edit */
19939 /* See the mkopcodec.awk script for details. */
19940 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
19941 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
19942  static const char *const azName[] = { "?",
19943      /*   1 */ "VNext",
19944      /*   2 */ "Affinity",
19945      /*   3 */ "Column",
19946      /*   4 */ "SetCookie",
19947      /*   5 */ "Sequence",
19948      /*   6 */ "MoveGt",
19949      /*   7 */ "RowKey",
19950      /*   8 */ "SCopy",
19951      /*   9 */ "OpenWrite",
19952      /*  10 */ "If",
19953      /*  11 */ "VRowid",
19954      /*  12 */ "CollSeq",
19955      /*  13 */ "OpenRead",
19956      /*  14 */ "Expire",
19957      /*  15 */ "AutoCommit",
19958      /*  16 */ "Not",
19959      /*  17 */ "Pagecount",
19960      /*  18 */ "IntegrityCk",
19961      /*  19 */ "Sort",
19962      /*  20 */ "Copy",
19963      /*  21 */ "Trace",
19964      /*  22 */ "Function",
19965      /*  23 */ "IfNeg",
19966      /*  24 */ "Noop",
19967      /*  25 */ "Return",
19968      /*  26 */ "NewRowid",
19969      /*  27 */ "Variable",
19970      /*  28 */ "String",
19971      /*  29 */ "RealAffinity",
19972      /*  30 */ "VRename",
19973      /*  31 */ "ParseSchema",
19974      /*  32 */ "VOpen",
19975      /*  33 */ "Close",
19976      /*  34 */ "CreateIndex",
19977      /*  35 */ "IsUnique",
19978      /*  36 */ "NotFound",
19979      /*  37 */ "Int64",
19980      /*  38 */ "MustBeInt",
19981      /*  39 */ "Halt",
19982      /*  40 */ "Rowid",
19983      /*  41 */ "IdxLT",
19984      /*  42 */ "AddImm",
19985      /*  43 */ "Statement",
19986      /*  44 */ "RowData",
19987      /*  45 */ "MemMax",
19988      /*  46 */ "NotExists",
19989      /*  47 */ "Gosub",
19990      /*  48 */ "Integer",
19991      /*  49 */ "Prev",
19992      /*  50 */ "VColumn",
19993      /*  51 */ "CreateTable",
19994      /*  52 */ "Last",
19995      /*  53 */ "IncrVacuum",
19996      /*  54 */ "IdxRowid",
19997      /*  55 */ "ResetCount",
19998      /*  56 */ "FifoWrite",
19999      /*  57 */ "ContextPush",
20000      /*  58 */ "Yield",
20001      /*  59 */ "DropTrigger",
20002      /*  60 */ "Or",
20003      /*  61 */ "And",
20004      /*  62 */ "DropIndex",
20005      /*  63 */ "IdxGE",
20006      /*  64 */ "IdxDelete",
20007      /*  65 */ "IsNull",
20008      /*  66 */ "NotNull",
20009      /*  67 */ "Ne",
20010      /*  68 */ "Eq",
20011      /*  69 */ "Gt",
20012      /*  70 */ "Le",
20013      /*  71 */ "Lt",
20014      /*  72 */ "Ge",
20015      /*  73 */ "Vacuum",
20016      /*  74 */ "BitAnd",
20017      /*  75 */ "BitOr",
20018      /*  76 */ "ShiftLeft",
20019      /*  77 */ "ShiftRight",
20020      /*  78 */ "Add",
20021      /*  79 */ "Subtract",
20022      /*  80 */ "Multiply",
20023      /*  81 */ "Divide",
20024      /*  82 */ "Remainder",
20025      /*  83 */ "Concat",
20026      /*  84 */ "MoveLe",
20027      /*  85 */ "IfNot",
20028      /*  86 */ "DropTable",
20029      /*  87 */ "BitNot",
20030      /*  88 */ "String8",
20031      /*  89 */ "MakeRecord",
20032      /*  90 */ "ResultRow",
20033      /*  91 */ "Delete",
20034      /*  92 */ "AggFinal",
20035      /*  93 */ "Compare",
20036      /*  94 */ "Goto",
20037      /*  95 */ "TableLock",
20038      /*  96 */ "FifoRead",
20039      /*  97 */ "Clear",
20040      /*  98 */ "MoveLt",
20041      /*  99 */ "VerifyCookie",
20042      /* 100 */ "AggStep",
20043      /* 101 */ "SetNumColumns",
20044      /* 102 */ "Transaction",
20045      /* 103 */ "VFilter",
20046      /* 104 */ "VDestroy",
20047      /* 105 */ "ContextPop",
20048      /* 106 */ "Next",
20049      /* 107 */ "IdxInsert",
20050      /* 108 */ "Insert",
20051      /* 109 */ "Destroy",
20052      /* 110 */ "ReadCookie",
20053      /* 111 */ "ForceInt",
20054      /* 112 */ "LoadAnalysis",
20055      /* 113 */ "Explain",
20056      /* 114 */ "OpenPseudo",
20057      /* 115 */ "OpenEphemeral",
20058      /* 116 */ "Null",
20059      /* 117 */ "Move",
20060      /* 118 */ "Blob",
20061      /* 119 */ "Rewind",
20062      /* 120 */ "MoveGe",
20063      /* 121 */ "VBegin",
20064      /* 122 */ "VUpdate",
20065      /* 123 */ "IfZero",
20066      /* 124 */ "VCreate",
20067      /* 125 */ "Real",
20068      /* 126 */ "Found",
20069      /* 127 */ "IfPos",
20070      /* 128 */ "NullRow",
20071      /* 129 */ "Jump",
20072      /* 130 */ "Permutation",
20073      /* 131 */ "NotUsed_131",
20074      /* 132 */ "NotUsed_132",
20075      /* 133 */ "NotUsed_133",
20076      /* 134 */ "NotUsed_134",
20077      /* 135 */ "NotUsed_135",
20078      /* 136 */ "NotUsed_136",
20079      /* 137 */ "NotUsed_137",
20080      /* 138 */ "ToText",
20081      /* 139 */ "ToBlob",
20082      /* 140 */ "ToNumeric",
20083      /* 141 */ "ToInt",
20084      /* 142 */ "ToReal",
20085   };
20086   return azName[i];
20087 }
20088 #endif
20089
20090 /************** End of opcodes.c *********************************************/
20091 /************** Begin file os_os2.c ******************************************/
20092 /*
20093 ** 2006 Feb 14
20094 **
20095 ** The author disclaims copyright to this source code.  In place of
20096 ** a legal notice, here is a blessing:
20097 **
20098 **    May you do good and not evil.
20099 **    May you find forgiveness for yourself and forgive others.
20100 **    May you share freely, never taking more than you give.
20101 **
20102 ******************************************************************************
20103 **
20104 ** This file contains code that is specific to OS/2.
20105 **
20106 ** $Id: os_os2.c,v 1.56 2008/08/22 13:47:57 pweilbacher Exp $
20107 */
20108
20109
20110 #if SQLITE_OS_OS2
20111
20112 /*
20113 ** A Note About Memory Allocation:
20114 **
20115 ** This driver uses malloc()/free() directly rather than going through
20116 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
20117 ** are designed for use on embedded systems where memory is scarce and
20118 ** malloc failures happen frequently.  OS/2 does not typically run on
20119 ** embedded systems, and when it does the developers normally have bigger
20120 ** problems to worry about than running out of memory.  So there is not
20121 ** a compelling need to use the wrappers.
20122 **
20123 ** But there is a good reason to not use the wrappers.  If we use the
20124 ** wrappers then we will get simulated malloc() failures within this
20125 ** driver.  And that causes all kinds of problems for our tests.  We
20126 ** could enhance SQLite to deal with simulated malloc failures within
20127 ** the OS driver, but the code to deal with those failure would not
20128 ** be exercised on Linux (which does not need to malloc() in the driver)
20129 ** and so we would have difficulty writing coverage tests for that
20130 ** code.  Better to leave the code out, we think.
20131 **
20132 ** The point of this discussion is as follows:  When creating a new
20133 ** OS layer for an embedded system, if you use this file as an example,
20134 ** avoid the use of malloc()/free().  Those routines work ok on OS/2
20135 ** desktops but not so well in embedded systems.
20136 */
20137
20138 /*
20139 ** Macros used to determine whether or not to use threads.
20140 */
20141 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
20142 # define SQLITE_OS2_THREADS 1
20143 #endif
20144
20145 /*
20146 ** Include code that is common to all os_*.c files
20147 */
20148 /************** Include os_common.h in the middle of os_os2.c ****************/
20149 /************** Begin file os_common.h ***************************************/
20150 /*
20151 ** 2004 May 22
20152 **
20153 ** The author disclaims copyright to this source code.  In place of
20154 ** a legal notice, here is a blessing:
20155 **
20156 **    May you do good and not evil.
20157 **    May you find forgiveness for yourself and forgive others.
20158 **    May you share freely, never taking more than you give.
20159 **
20160 ******************************************************************************
20161 **
20162 ** This file contains macros and a little bit of code that is common to
20163 ** all of the platform-specific files (os_*.c) and is #included into those
20164 ** files.
20165 **
20166 ** This file should be #included by the os_*.c files only.  It is not a
20167 ** general purpose header file.
20168 **
20169 ** $Id: os_common.h,v 1.37 2008/05/29 20:22:37 shane Exp $
20170 */
20171 #ifndef _OS_COMMON_H_
20172 #define _OS_COMMON_H_
20173
20174 /*
20175 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
20176 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
20177 ** switch.  The following code should catch this problem at compile-time.
20178 */
20179 #ifdef MEMORY_DEBUG
20180 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
20181 #endif
20182
20183
20184 /*
20185  * When testing, this global variable stores the location of the
20186  * pending-byte in the database file.
20187  */
20188 #ifdef SQLITE_TEST
20189 SQLITE_API unsigned int sqlite3_pending_byte = 0x40000000;
20190 #endif
20191
20192 #ifdef SQLITE_DEBUG
20193 SQLITE_PRIVATE int sqlite3OSTrace = 0;
20194 #define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
20195 #define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
20196 #define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
20197 #define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
20198 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
20199 #define OSTRACE6(X,Y,Z,A,B,C) \
20200     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
20201 #define OSTRACE7(X,Y,Z,A,B,C,D) \
20202     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
20203 #else
20204 #define OSTRACE1(X)
20205 #define OSTRACE2(X,Y)
20206 #define OSTRACE3(X,Y,Z)
20207 #define OSTRACE4(X,Y,Z,A)
20208 #define OSTRACE5(X,Y,Z,A,B)
20209 #define OSTRACE6(X,Y,Z,A,B,C)
20210 #define OSTRACE7(X,Y,Z,A,B,C,D)
20211 #endif
20212
20213 /*
20214 ** Macros for performance tracing.  Normally turned off.  Only works
20215 ** on i486 hardware.
20216 */
20217 #ifdef SQLITE_PERFORMANCE_TRACE
20218
20219 /* 
20220 ** hwtime.h contains inline assembler code for implementing 
20221 ** high-performance timing routines.
20222 */
20223 /************** Include hwtime.h in the middle of os_common.h ****************/
20224 /************** Begin file hwtime.h ******************************************/
20225 /*
20226 ** 2008 May 27
20227 **
20228 ** The author disclaims copyright to this source code.  In place of
20229 ** a legal notice, here is a blessing:
20230 **
20231 **    May you do good and not evil.
20232 **    May you find forgiveness for yourself and forgive others.
20233 **    May you share freely, never taking more than you give.
20234 **
20235 ******************************************************************************
20236 **
20237 ** This file contains inline asm code for retrieving "high-performance"
20238 ** counters for x86 class CPUs.
20239 **
20240 ** $Id: hwtime.h,v 1.3 2008/08/01 14:33:15 shane Exp $
20241 */
20242 #ifndef _HWTIME_H_
20243 #define _HWTIME_H_
20244
20245 /*
20246 ** The following routine only works on pentium-class (or newer) processors.
20247 ** It uses the RDTSC opcode to read the cycle count value out of the
20248 ** processor and returns that value.  This can be used for high-res
20249 ** profiling.
20250 */
20251 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
20252       (defined(i386) || defined(__i386__) || defined(_M_IX86))
20253
20254   #if defined(__GNUC__)
20255
20256   __inline__ sqlite_uint64 sqlite3Hwtime(void){
20257      unsigned int lo, hi;
20258      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
20259      return (sqlite_uint64)hi << 32 | lo;
20260   }
20261
20262   #elif defined(_MSC_VER)
20263
20264   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
20265      __asm {
20266         rdtsc
20267         ret       ; return value at EDX:EAX
20268      }
20269   }
20270
20271   #endif
20272
20273 #elif (defined(__GNUC__) && defined(__x86_64__))
20274
20275   __inline__ sqlite_uint64 sqlite3Hwtime(void){
20276       unsigned long val;
20277       __asm__ __volatile__ ("rdtsc" : "=A" (val));
20278       return val;
20279   }
20280  
20281 #elif (defined(__GNUC__) && defined(__ppc__))
20282
20283   __inline__ sqlite_uint64 sqlite3Hwtime(void){
20284       unsigned long long retval;
20285       unsigned long junk;
20286       __asm__ __volatile__ ("\n\
20287           1:      mftbu   %1\n\
20288                   mftb    %L0\n\
20289                   mftbu   %0\n\
20290                   cmpw    %0,%1\n\
20291                   bne     1b"
20292                   : "=r" (retval), "=r" (junk));
20293       return retval;
20294   }
20295
20296 #else
20297
20298   #error Need implementation of sqlite3Hwtime() for your platform.
20299
20300   /*
20301   ** To compile without implementing sqlite3Hwtime() for your platform,
20302   ** you can remove the above #error and use the following
20303   ** stub function.  You will lose timing support for many
20304   ** of the debugging and testing utilities, but it should at
20305   ** least compile and run.
20306   */
20307 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
20308
20309 #endif
20310
20311 #endif /* !defined(_HWTIME_H_) */
20312
20313 /************** End of hwtime.h **********************************************/
20314 /************** Continuing where we left off in os_common.h ******************/
20315
20316 static sqlite_uint64 g_start;
20317 static sqlite_uint64 g_elapsed;
20318 #define TIMER_START       g_start=sqlite3Hwtime()
20319 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
20320 #define TIMER_ELAPSED     g_elapsed
20321 #else
20322 #define TIMER_START
20323 #define TIMER_END
20324 #define TIMER_ELAPSED     ((sqlite_uint64)0)
20325 #endif
20326
20327 /*
20328 ** If we compile with the SQLITE_TEST macro set, then the following block
20329 ** of code will give us the ability to simulate a disk I/O error.  This
20330 ** is used for testing the I/O recovery logic.
20331 */
20332 #ifdef SQLITE_TEST
20333 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
20334 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
20335 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
20336 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
20337 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
20338 SQLITE_API int sqlite3_diskfull_pending = 0;
20339 SQLITE_API int sqlite3_diskfull = 0;
20340 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
20341 #define SimulateIOError(CODE)  \
20342   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
20343        || sqlite3_io_error_pending-- == 1 )  \
20344               { local_ioerr(); CODE; }
20345 static void local_ioerr(){
20346   IOTRACE(("IOERR\n"));
20347   sqlite3_io_error_hit++;
20348   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
20349 }
20350 #define SimulateDiskfullError(CODE) \
20351    if( sqlite3_diskfull_pending ){ \
20352      if( sqlite3_diskfull_pending == 1 ){ \
20353        local_ioerr(); \
20354        sqlite3_diskfull = 1; \
20355        sqlite3_io_error_hit = 1; \
20356        CODE; \
20357      }else{ \
20358        sqlite3_diskfull_pending--; \
20359      } \
20360    }
20361 #else
20362 #define SimulateIOErrorBenign(X)
20363 #define SimulateIOError(A)
20364 #define SimulateDiskfullError(A)
20365 #endif
20366
20367 /*
20368 ** When testing, keep a count of the number of open files.
20369 */
20370 #ifdef SQLITE_TEST
20371 SQLITE_API int sqlite3_open_file_count = 0;
20372 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
20373 #else
20374 #define OpenCounter(X)
20375 #endif
20376
20377 #endif /* !defined(_OS_COMMON_H_) */
20378
20379 /************** End of os_common.h *******************************************/
20380 /************** Continuing where we left off in os_os2.c *********************/
20381
20382 /*
20383 ** The os2File structure is subclass of sqlite3_file specific for the OS/2
20384 ** protability layer.
20385 */
20386 typedef struct os2File os2File;
20387 struct os2File {
20388   const sqlite3_io_methods *pMethod;  /* Always the first entry */
20389   HFILE h;                  /* Handle for accessing the file */
20390   char* pathToDel;          /* Name of file to delete on close, NULL if not */
20391   unsigned char locktype;   /* Type of lock currently held on this file */
20392 };
20393
20394 #define LOCK_TIMEOUT 10L /* the default locking timeout */
20395
20396 /*****************************************************************************
20397 ** The next group of routines implement the I/O methods specified
20398 ** by the sqlite3_io_methods object.
20399 ******************************************************************************/
20400
20401 /*
20402 ** Close a file.
20403 */
20404 static int os2Close( sqlite3_file *id ){
20405   APIRET rc = NO_ERROR;
20406   os2File *pFile;
20407   if( id && (pFile = (os2File*)id) != 0 ){
20408     OSTRACE2( "CLOSE %d\n", pFile->h );
20409     rc = DosClose( pFile->h );
20410     pFile->locktype = NO_LOCK;
20411     if( pFile->pathToDel != NULL ){
20412       rc = DosForceDelete( (PSZ)pFile->pathToDel );
20413       free( pFile->pathToDel );
20414       pFile->pathToDel = NULL;
20415     }
20416     id = 0;
20417     OpenCounter( -1 );
20418   }
20419
20420   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
20421 }
20422
20423 /*
20424 ** Read data from a file into a buffer.  Return SQLITE_OK if all
20425 ** bytes were read successfully and SQLITE_IOERR if anything goes
20426 ** wrong.
20427 */
20428 static int os2Read(
20429   sqlite3_file *id,               /* File to read from */
20430   void *pBuf,                     /* Write content into this buffer */
20431   int amt,                        /* Number of bytes to read */
20432   sqlite3_int64 offset            /* Begin reading at this offset */
20433 ){
20434   ULONG fileLocation = 0L;
20435   ULONG got;
20436   os2File *pFile = (os2File*)id;
20437   assert( id!=0 );
20438   SimulateIOError( return SQLITE_IOERR_READ );
20439   OSTRACE3( "READ %d lock=%d\n", pFile->h, pFile->locktype );
20440   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
20441     return SQLITE_IOERR;
20442   }
20443   if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
20444     return SQLITE_IOERR_READ;
20445   }
20446   if( got == (ULONG)amt )
20447     return SQLITE_OK;
20448   else {
20449     memset(&((char*)pBuf)[got], 0, amt-got);
20450     return SQLITE_IOERR_SHORT_READ;
20451   }
20452 }
20453
20454 /*
20455 ** Write data from a buffer into a file.  Return SQLITE_OK on success
20456 ** or some other error code on failure.
20457 */
20458 static int os2Write(
20459   sqlite3_file *id,               /* File to write into */
20460   const void *pBuf,               /* The bytes to be written */
20461   int amt,                        /* Number of bytes to write */
20462   sqlite3_int64 offset            /* Offset into the file to begin writing at */
20463 ){
20464   ULONG fileLocation = 0L;
20465   APIRET rc = NO_ERROR;
20466   ULONG wrote;
20467   os2File *pFile = (os2File*)id;
20468   assert( id!=0 );
20469   SimulateIOError( return SQLITE_IOERR_WRITE );
20470   SimulateDiskfullError( return SQLITE_FULL );
20471   OSTRACE3( "WRITE %d lock=%d\n", pFile->h, pFile->locktype );
20472   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
20473     return SQLITE_IOERR;
20474   }
20475   assert( amt>0 );
20476   while( amt > 0 &&
20477          ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
20478          wrote > 0
20479   ){
20480     amt -= wrote;
20481     pBuf = &((char*)pBuf)[wrote];
20482   }
20483
20484   return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
20485 }
20486
20487 /*
20488 ** Truncate an open file to a specified size
20489 */
20490 static int os2Truncate( sqlite3_file *id, i64 nByte ){
20491   APIRET rc = NO_ERROR;
20492   os2File *pFile = (os2File*)id;
20493   OSTRACE3( "TRUNCATE %d %lld\n", pFile->h, nByte );
20494   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
20495   rc = DosSetFileSize( pFile->h, nByte );
20496   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
20497 }
20498
20499 #ifdef SQLITE_TEST
20500 /*
20501 ** Count the number of fullsyncs and normal syncs.  This is used to test
20502 ** that syncs and fullsyncs are occuring at the right times.
20503 */
20504 SQLITE_API int sqlite3_sync_count = 0;
20505 SQLITE_API int sqlite3_fullsync_count = 0;
20506 #endif
20507
20508 /*
20509 ** Make sure all writes to a particular file are committed to disk.
20510 */
20511 static int os2Sync( sqlite3_file *id, int flags ){
20512   os2File *pFile = (os2File*)id;
20513   OSTRACE3( "SYNC %d lock=%d\n", pFile->h, pFile->locktype );
20514 #ifdef SQLITE_TEST
20515   if( flags & SQLITE_SYNC_FULL){
20516     sqlite3_fullsync_count++;
20517   }
20518   sqlite3_sync_count++;
20519 #endif
20520   return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
20521 }
20522
20523 /*
20524 ** Determine the current size of a file in bytes
20525 */
20526 static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
20527   APIRET rc = NO_ERROR;
20528   FILESTATUS3 fsts3FileInfo;
20529   memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
20530   assert( id!=0 );
20531   SimulateIOError( return SQLITE_IOERR );
20532   rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
20533   if( rc == NO_ERROR ){
20534     *pSize = fsts3FileInfo.cbFile;
20535     return SQLITE_OK;
20536   }else{
20537     return SQLITE_IOERR;
20538   }
20539 }
20540
20541 /*
20542 ** Acquire a reader lock.
20543 */
20544 static int getReadLock( os2File *pFile ){
20545   FILELOCK  LockArea,
20546             UnlockArea;
20547   APIRET res;
20548   memset(&LockArea, 0, sizeof(LockArea));
20549   memset(&UnlockArea, 0, sizeof(UnlockArea));
20550   LockArea.lOffset = SHARED_FIRST;
20551   LockArea.lRange = SHARED_SIZE;
20552   UnlockArea.lOffset = 0L;
20553   UnlockArea.lRange = 0L;
20554   res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
20555   OSTRACE3( "GETREADLOCK %d res=%d\n", pFile->h, res );
20556   return res;
20557 }
20558
20559 /*
20560 ** Undo a readlock
20561 */
20562 static int unlockReadLock( os2File *id ){
20563   FILELOCK  LockArea,
20564             UnlockArea;
20565   APIRET res;
20566   memset(&LockArea, 0, sizeof(LockArea));
20567   memset(&UnlockArea, 0, sizeof(UnlockArea));
20568   LockArea.lOffset = 0L;
20569   LockArea.lRange = 0L;
20570   UnlockArea.lOffset = SHARED_FIRST;
20571   UnlockArea.lRange = SHARED_SIZE;
20572   res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
20573   OSTRACE3( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res );
20574   return res;
20575 }
20576
20577 /*
20578 ** Lock the file with the lock specified by parameter locktype - one
20579 ** of the following:
20580 **
20581 **     (1) SHARED_LOCK
20582 **     (2) RESERVED_LOCK
20583 **     (3) PENDING_LOCK
20584 **     (4) EXCLUSIVE_LOCK
20585 **
20586 ** Sometimes when requesting one lock state, additional lock states
20587 ** are inserted in between.  The locking might fail on one of the later
20588 ** transitions leaving the lock state different from what it started but
20589 ** still short of its goal.  The following chart shows the allowed
20590 ** transitions and the inserted intermediate states:
20591 **
20592 **    UNLOCKED -> SHARED
20593 **    SHARED -> RESERVED
20594 **    SHARED -> (PENDING) -> EXCLUSIVE
20595 **    RESERVED -> (PENDING) -> EXCLUSIVE
20596 **    PENDING -> EXCLUSIVE
20597 **
20598 ** This routine will only increase a lock.  The os2Unlock() routine
20599 ** erases all locks at once and returns us immediately to locking level 0.
20600 ** It is not possible to lower the locking level one step at a time.  You
20601 ** must go straight to locking level 0.
20602 */
20603 static int os2Lock( sqlite3_file *id, int locktype ){
20604   int rc = SQLITE_OK;       /* Return code from subroutines */
20605   APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
20606   int newLocktype;       /* Set pFile->locktype to this value before exiting */
20607   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
20608   FILELOCK  LockArea,
20609             UnlockArea;
20610   os2File *pFile = (os2File*)id;
20611   memset(&LockArea, 0, sizeof(LockArea));
20612   memset(&UnlockArea, 0, sizeof(UnlockArea));
20613   assert( pFile!=0 );
20614   OSTRACE4( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype );
20615
20616   /* If there is already a lock of this type or more restrictive on the
20617   ** os2File, do nothing. Don't use the end_lock: exit path, as
20618   ** sqlite3_mutex_enter() hasn't been called yet.
20619   */
20620   if( pFile->locktype>=locktype ){
20621     OSTRACE3( "LOCK %d %d ok (already held)\n", pFile->h, locktype );
20622     return SQLITE_OK;
20623   }
20624
20625   /* Make sure the locking sequence is correct
20626   */
20627   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
20628   assert( locktype!=PENDING_LOCK );
20629   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
20630
20631   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
20632   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
20633   ** the PENDING_LOCK byte is temporary.
20634   */
20635   newLocktype = pFile->locktype;
20636   if( pFile->locktype==NO_LOCK
20637       || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
20638   ){
20639     LockArea.lOffset = PENDING_BYTE;
20640     LockArea.lRange = 1L;
20641     UnlockArea.lOffset = 0L;
20642     UnlockArea.lRange = 0L;
20643
20644     /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
20645     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
20646     if( res == NO_ERROR ){
20647       gotPendingLock = 1;
20648       OSTRACE3( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res );
20649     }
20650   }
20651
20652   /* Acquire a shared lock
20653   */
20654   if( locktype==SHARED_LOCK && res == NO_ERROR ){
20655     assert( pFile->locktype==NO_LOCK );
20656     res = getReadLock(pFile);
20657     if( res == NO_ERROR ){
20658       newLocktype = SHARED_LOCK;
20659     }
20660     OSTRACE3( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res );
20661   }
20662
20663   /* Acquire a RESERVED lock
20664   */
20665   if( locktype==RESERVED_LOCK && res == NO_ERROR ){
20666     assert( pFile->locktype==SHARED_LOCK );
20667     LockArea.lOffset = RESERVED_BYTE;
20668     LockArea.lRange = 1L;
20669     UnlockArea.lOffset = 0L;
20670     UnlockArea.lRange = 0L;
20671     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20672     if( res == NO_ERROR ){
20673       newLocktype = RESERVED_LOCK;
20674     }
20675     OSTRACE3( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res );
20676   }
20677
20678   /* Acquire a PENDING lock
20679   */
20680   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
20681     newLocktype = PENDING_LOCK;
20682     gotPendingLock = 0;
20683     OSTRACE2( "LOCK %d acquire pending lock. pending lock boolean unset.\n", pFile->h );
20684   }
20685
20686   /* Acquire an EXCLUSIVE lock
20687   */
20688   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
20689     assert( pFile->locktype>=SHARED_LOCK );
20690     res = unlockReadLock(pFile);
20691     OSTRACE2( "unreadlock = %d\n", res );
20692     LockArea.lOffset = SHARED_FIRST;
20693     LockArea.lRange = SHARED_SIZE;
20694     UnlockArea.lOffset = 0L;
20695     UnlockArea.lRange = 0L;
20696     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20697     if( res == NO_ERROR ){
20698       newLocktype = EXCLUSIVE_LOCK;
20699     }else{
20700       OSTRACE2( "OS/2 error-code = %d\n", res );
20701       getReadLock(pFile);
20702     }
20703     OSTRACE3( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res );
20704   }
20705
20706   /* If we are holding a PENDING lock that ought to be released, then
20707   ** release it now.
20708   */
20709   if( gotPendingLock && locktype==SHARED_LOCK ){
20710     int r;
20711     LockArea.lOffset = 0L;
20712     LockArea.lRange = 0L;
20713     UnlockArea.lOffset = PENDING_BYTE;
20714     UnlockArea.lRange = 1L;
20715     r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20716     OSTRACE3( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r );
20717   }
20718
20719   /* Update the state of the lock has held in the file descriptor then
20720   ** return the appropriate result code.
20721   */
20722   if( res == NO_ERROR ){
20723     rc = SQLITE_OK;
20724   }else{
20725     OSTRACE4( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
20726               locktype, newLocktype );
20727     rc = SQLITE_BUSY;
20728   }
20729   pFile->locktype = newLocktype;
20730   OSTRACE3( "LOCK %d now %d\n", pFile->h, pFile->locktype );
20731   return rc;
20732 }
20733
20734 /*
20735 ** This routine checks if there is a RESERVED lock held on the specified
20736 ** file by this or any other process. If such a lock is held, return
20737 ** non-zero, otherwise zero.
20738 */
20739 static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
20740   int r = 0;
20741   os2File *pFile = (os2File*)id;
20742   assert( pFile!=0 );
20743   if( pFile->locktype>=RESERVED_LOCK ){
20744     r = 1;
20745     OSTRACE3( "TEST WR-LOCK %d %d (local)\n", pFile->h, r );
20746   }else{
20747     FILELOCK  LockArea,
20748               UnlockArea;
20749     APIRET rc = NO_ERROR;
20750     memset(&LockArea, 0, sizeof(LockArea));
20751     memset(&UnlockArea, 0, sizeof(UnlockArea));
20752     LockArea.lOffset = RESERVED_BYTE;
20753     LockArea.lRange = 1L;
20754     UnlockArea.lOffset = 0L;
20755     UnlockArea.lRange = 0L;
20756     rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20757     OSTRACE3( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc );
20758     if( rc == NO_ERROR ){
20759       APIRET rcu = NO_ERROR; /* return code for unlocking */
20760       LockArea.lOffset = 0L;
20761       LockArea.lRange = 0L;
20762       UnlockArea.lOffset = RESERVED_BYTE;
20763       UnlockArea.lRange = 1L;
20764       rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20765       OSTRACE3( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu );
20766     }
20767     r = !(rc == NO_ERROR);
20768     OSTRACE3( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r );
20769   }
20770   *pOut = r;
20771   return SQLITE_OK;
20772 }
20773
20774 /*
20775 ** Lower the locking level on file descriptor id to locktype.  locktype
20776 ** must be either NO_LOCK or SHARED_LOCK.
20777 **
20778 ** If the locking level of the file descriptor is already at or below
20779 ** the requested locking level, this routine is a no-op.
20780 **
20781 ** It is not possible for this routine to fail if the second argument
20782 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
20783 ** might return SQLITE_IOERR;
20784 */
20785 static int os2Unlock( sqlite3_file *id, int locktype ){
20786   int type;
20787   os2File *pFile = (os2File*)id;
20788   APIRET rc = SQLITE_OK;
20789   APIRET res = NO_ERROR;
20790   FILELOCK  LockArea,
20791             UnlockArea;
20792   memset(&LockArea, 0, sizeof(LockArea));
20793   memset(&UnlockArea, 0, sizeof(UnlockArea));
20794   assert( pFile!=0 );
20795   assert( locktype<=SHARED_LOCK );
20796   OSTRACE4( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype );
20797   type = pFile->locktype;
20798   if( type>=EXCLUSIVE_LOCK ){
20799     LockArea.lOffset = 0L;
20800     LockArea.lRange = 0L;
20801     UnlockArea.lOffset = SHARED_FIRST;
20802     UnlockArea.lRange = SHARED_SIZE;
20803     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20804     OSTRACE3( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res );
20805     if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
20806       /* This should never happen.  We should always be able to
20807       ** reacquire the read lock */
20808       OSTRACE3( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype );
20809       rc = SQLITE_IOERR_UNLOCK;
20810     }
20811   }
20812   if( type>=RESERVED_LOCK ){
20813     LockArea.lOffset = 0L;
20814     LockArea.lRange = 0L;
20815     UnlockArea.lOffset = RESERVED_BYTE;
20816     UnlockArea.lRange = 1L;
20817     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20818     OSTRACE3( "UNLOCK %d reserved res=%d\n", pFile->h, res );
20819   }
20820   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
20821     res = unlockReadLock(pFile);
20822     OSTRACE5( "UNLOCK %d is %d want %d res=%d\n", pFile->h, type, locktype, res );
20823   }
20824   if( type>=PENDING_LOCK ){
20825     LockArea.lOffset = 0L;
20826     LockArea.lRange = 0L;
20827     UnlockArea.lOffset = PENDING_BYTE;
20828     UnlockArea.lRange = 1L;
20829     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20830     OSTRACE3( "UNLOCK %d pending res=%d\n", pFile->h, res );
20831   }
20832   pFile->locktype = locktype;
20833   OSTRACE3( "UNLOCK %d now %d\n", pFile->h, pFile->locktype );
20834   return rc;
20835 }
20836
20837 /*
20838 ** Control and query of the open file handle.
20839 */
20840 static int os2FileControl(sqlite3_file *id, int op, void *pArg){
20841   switch( op ){
20842     case SQLITE_FCNTL_LOCKSTATE: {
20843       *(int*)pArg = ((os2File*)id)->locktype;
20844       OSTRACE3( "FCNTL_LOCKSTATE %d lock=%d\n", ((os2File*)id)->h, ((os2File*)id)->locktype );
20845       return SQLITE_OK;
20846     }
20847   }
20848   return SQLITE_ERROR;
20849 }
20850
20851 /*
20852 ** Return the sector size in bytes of the underlying block device for
20853 ** the specified file. This is almost always 512 bytes, but may be
20854 ** larger for some devices.
20855 **
20856 ** SQLite code assumes this function cannot fail. It also assumes that
20857 ** if two files are created in the same file-system directory (i.e.
20858 ** a database and its journal file) that the sector size will be the
20859 ** same for both.
20860 */
20861 static int os2SectorSize(sqlite3_file *id){
20862   return SQLITE_DEFAULT_SECTOR_SIZE;
20863 }
20864
20865 /*
20866 ** Return a vector of device characteristics.
20867 */
20868 static int os2DeviceCharacteristics(sqlite3_file *id){
20869   return 0;
20870 }
20871
20872
20873 /*
20874 ** Character set conversion objects used by conversion routines.
20875 */
20876 static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
20877 static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */
20878
20879 /*
20880 ** Helper function to initialize the conversion objects from and to UTF-8.
20881 */
20882 static void initUconvObjects( void ){
20883   if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
20884     ucUtf8 = NULL;
20885   if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
20886     uclCp = NULL;
20887 }
20888
20889 /*
20890 ** Helper function to free the conversion objects from and to UTF-8.
20891 */
20892 static void freeUconvObjects( void ){
20893   if ( ucUtf8 )
20894     UniFreeUconvObject( ucUtf8 );
20895   if ( uclCp )
20896     UniFreeUconvObject( uclCp );
20897   ucUtf8 = NULL;
20898   uclCp = NULL;
20899 }
20900
20901 /*
20902 ** Helper function to convert UTF-8 filenames to local OS/2 codepage.
20903 ** The two-step process: first convert the incoming UTF-8 string
20904 ** into UCS-2 and then from UCS-2 to the current codepage.
20905 ** The returned char pointer has to be freed.
20906 */
20907 static char *convertUtf8PathToCp( const char *in ){
20908   UniChar tempPath[CCHMAXPATH];
20909   char *out = (char *)calloc( CCHMAXPATH, 1 );
20910
20911   if( !out )
20912     return NULL;
20913
20914   if( !ucUtf8 || !uclCp )
20915     initUconvObjects();
20916
20917   /* determine string for the conversion of UTF-8 which is CP1208 */
20918   if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
20919     return out; /* if conversion fails, return the empty string */
20920
20921   /* conversion for current codepage which can be used for paths */
20922   UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
20923
20924   return out;
20925 }
20926
20927 /*
20928 ** Helper function to convert filenames from local codepage to UTF-8.
20929 ** The two-step process: first convert the incoming codepage-specific
20930 ** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
20931 ** The returned char pointer has to be freed.
20932 **
20933 ** This function is non-static to be able to use this in shell.c and
20934 ** similar applications that take command line arguments.
20935 */
20936 char *convertCpPathToUtf8( const char *in ){
20937   UniChar tempPath[CCHMAXPATH];
20938   char *out = (char *)calloc( CCHMAXPATH, 1 );
20939
20940   if( !out )
20941     return NULL;
20942
20943   if( !ucUtf8 || !uclCp )
20944     initUconvObjects();
20945
20946   /* conversion for current codepage which can be used for paths */
20947   if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
20948     return out; /* if conversion fails, return the empty string */
20949
20950   /* determine string for the conversion of UTF-8 which is CP1208 */
20951   UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
20952
20953   return out;
20954 }
20955
20956 /*
20957 ** This vector defines all the methods that can operate on an
20958 ** sqlite3_file for os2.
20959 */
20960 static const sqlite3_io_methods os2IoMethod = {
20961   1,                        /* iVersion */
20962   os2Close,
20963   os2Read,
20964   os2Write,
20965   os2Truncate,
20966   os2Sync,
20967   os2FileSize,
20968   os2Lock,
20969   os2Unlock,
20970   os2CheckReservedLock,
20971   os2FileControl,
20972   os2SectorSize,
20973   os2DeviceCharacteristics
20974 };
20975
20976 /***************************************************************************
20977 ** Here ends the I/O methods that form the sqlite3_io_methods object.
20978 **
20979 ** The next block of code implements the VFS methods.
20980 ****************************************************************************/
20981
20982 /*
20983 ** Create a temporary file name in zBuf.  zBuf must be big enough to
20984 ** hold at pVfs->mxPathname characters.
20985 */
20986 static int getTempname(int nBuf, char *zBuf ){
20987   static const unsigned char zChars[] =
20988     "abcdefghijklmnopqrstuvwxyz"
20989     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
20990     "0123456789";
20991   int i, j;
20992   char zTempPathBuf[3];
20993   PSZ zTempPath = (PSZ)&zTempPathBuf;
20994   if( sqlite3_temp_directory ){
20995     zTempPath = sqlite3_temp_directory;
20996   }else{
20997     if( DosScanEnv( (PSZ)"TEMP", &zTempPath ) ){
20998       if( DosScanEnv( (PSZ)"TMP", &zTempPath ) ){
20999         if( DosScanEnv( (PSZ)"TMPDIR", &zTempPath ) ){
21000            ULONG ulDriveNum = 0, ulDriveMap = 0;
21001            DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
21002            sprintf( (char*)zTempPath, "%c:", (char)( 'A' + ulDriveNum - 1 ) );
21003         }
21004       }
21005     }
21006   }
21007   /* Strip off a trailing slashes or backslashes, otherwise we would get *
21008    * multiple (back)slashes which causes DosOpen() to fail.              *
21009    * Trailing spaces are not allowed, either.                            */
21010   j = strlen(zTempPath);
21011   while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/'
21012                     || zTempPath[j-1] == ' ' ) ){
21013     j--;
21014   }
21015   zTempPath[j] = '\0';
21016   if( !sqlite3_temp_directory ){
21017     char *zTempPathUTF = convertCpPathToUtf8( zTempPath );
21018     sqlite3_snprintf( nBuf-30, zBuf,
21019                       "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPathUTF );
21020     free( zTempPathUTF );
21021   }else{
21022     sqlite3_snprintf( nBuf-30, zBuf,
21023                       "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath );
21024   }
21025   j = strlen( zBuf );
21026   sqlite3_randomness( 20, &zBuf[j] );
21027   for( i = 0; i < 20; i++, j++ ){
21028     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
21029   }
21030   zBuf[j] = 0;
21031   OSTRACE2( "TEMP FILENAME: %s\n", zBuf );
21032   return SQLITE_OK;
21033 }
21034
21035
21036 /*
21037 ** Turn a relative pathname into a full pathname.  Write the full
21038 ** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
21039 ** bytes in size.
21040 */
21041 static int os2FullPathname(
21042   sqlite3_vfs *pVfs,          /* Pointer to vfs object */
21043   const char *zRelative,      /* Possibly relative input path */
21044   int nFull,                  /* Size of output buffer in bytes */
21045   char *zFull                 /* Output buffer */
21046 ){
21047   char *zRelativeCp = convertUtf8PathToCp( zRelative );
21048   char zFullCp[CCHMAXPATH] = "\0";
21049   char *zFullUTF;
21050   APIRET rc = DosQueryPathInfo( zRelativeCp, FIL_QUERYFULLNAME, zFullCp,
21051                                 CCHMAXPATH );
21052   free( zRelativeCp );
21053   zFullUTF = convertCpPathToUtf8( zFullCp );
21054   sqlite3_snprintf( nFull, zFull, zFullUTF );
21055   free( zFullUTF );
21056   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
21057 }
21058
21059
21060 /*
21061 ** Open a file.
21062 */
21063 static int os2Open(
21064   sqlite3_vfs *pVfs,            /* Not used */
21065   const char *zName,            /* Name of the file */
21066   sqlite3_file *id,             /* Write the SQLite file handle here */
21067   int flags,                    /* Open mode flags */
21068   int *pOutFlags                /* Status return flags */
21069 ){
21070   HFILE h;
21071   ULONG ulFileAttribute = FILE_NORMAL;
21072   ULONG ulOpenFlags = 0;
21073   ULONG ulOpenMode = 0;
21074   os2File *pFile = (os2File*)id;
21075   APIRET rc = NO_ERROR;
21076   ULONG ulAction;
21077   char *zNameCp;
21078   char zTmpname[CCHMAXPATH+1];    /* Buffer to hold name of temp file */
21079
21080   /* If the second argument to this function is NULL, generate a 
21081   ** temporary file name to use 
21082   */
21083   if( !zName ){
21084     int rc = getTempname(CCHMAXPATH+1, zTmpname);
21085     if( rc!=SQLITE_OK ){
21086       return rc;
21087     }
21088     zName = zTmpname;
21089   }
21090
21091
21092   memset( pFile, 0, sizeof(*pFile) );
21093
21094   OSTRACE2( "OPEN want %d\n", flags );
21095
21096   if( flags & SQLITE_OPEN_READWRITE ){
21097     ulOpenMode |= OPEN_ACCESS_READWRITE;
21098     OSTRACE1( "OPEN read/write\n" );
21099   }else{
21100     ulOpenMode |= OPEN_ACCESS_READONLY;
21101     OSTRACE1( "OPEN read only\n" );
21102   }
21103
21104   if( flags & SQLITE_OPEN_CREATE ){
21105     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW;
21106     OSTRACE1( "OPEN open new/create\n" );
21107   }else{
21108     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW;
21109     OSTRACE1( "OPEN open existing\n" );
21110   }
21111
21112   if( flags & SQLITE_OPEN_MAIN_DB ){
21113     ulOpenMode |= OPEN_SHARE_DENYNONE;
21114     OSTRACE1( "OPEN share read/write\n" );
21115   }else{
21116     ulOpenMode |= OPEN_SHARE_DENYWRITE;
21117     OSTRACE1( "OPEN share read only\n" );
21118   }
21119
21120   if( flags & SQLITE_OPEN_DELETEONCLOSE ){
21121     char pathUtf8[CCHMAXPATH];
21122 #ifdef NDEBUG /* when debugging we want to make sure it is deleted */
21123     ulFileAttribute = FILE_HIDDEN;
21124 #endif
21125     os2FullPathname( pVfs, zName, CCHMAXPATH, pathUtf8 );
21126     pFile->pathToDel = convertUtf8PathToCp( pathUtf8 );
21127     OSTRACE1( "OPEN hidden/delete on close file attributes\n" );
21128   }else{
21129     pFile->pathToDel = NULL;
21130     OSTRACE1( "OPEN normal file attribute\n" );
21131   }
21132
21133   /* always open in random access mode for possibly better speed */
21134   ulOpenMode |= OPEN_FLAGS_RANDOM;
21135   ulOpenMode |= OPEN_FLAGS_FAIL_ON_ERROR;
21136   ulOpenMode |= OPEN_FLAGS_NOINHERIT;
21137
21138   zNameCp = convertUtf8PathToCp( zName );
21139   rc = DosOpen( (PSZ)zNameCp,
21140                 &h,
21141                 &ulAction,
21142                 0L,
21143                 ulFileAttribute,
21144                 ulOpenFlags,
21145                 ulOpenMode,
21146                 (PEAOP2)NULL );
21147   free( zNameCp );
21148   if( rc != NO_ERROR ){
21149     OSTRACE7( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulAttr=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
21150               rc, zName, ulAction, ulFileAttribute, ulOpenFlags, ulOpenMode );
21151     if( pFile->pathToDel )
21152       free( pFile->pathToDel );
21153     pFile->pathToDel = NULL;
21154     if( flags & SQLITE_OPEN_READWRITE ){
21155       OSTRACE2( "OPEN %d Invalid handle\n", ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE) );
21156       return os2Open( pVfs, zName, id,
21157                       ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE),
21158                       pOutFlags );
21159     }else{
21160       return SQLITE_CANTOPEN;
21161     }
21162   }
21163
21164   if( pOutFlags ){
21165     *pOutFlags = flags & SQLITE_OPEN_READWRITE ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
21166   }
21167
21168   pFile->pMethod = &os2IoMethod;
21169   pFile->h = h;
21170   OpenCounter(+1);
21171   OSTRACE3( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags );
21172   return SQLITE_OK;
21173 }
21174
21175 /*
21176 ** Delete the named file.
21177 */
21178 static int os2Delete(
21179   sqlite3_vfs *pVfs,                     /* Not used on os2 */
21180   const char *zFilename,                 /* Name of file to delete */
21181   int syncDir                            /* Not used on os2 */
21182 ){
21183   APIRET rc = NO_ERROR;
21184   char *zFilenameCp = convertUtf8PathToCp( zFilename );
21185   SimulateIOError( return SQLITE_IOERR_DELETE );
21186   rc = DosDelete( (PSZ)zFilenameCp );
21187   free( zFilenameCp );
21188   OSTRACE2( "DELETE \"%s\"\n", zFilename );
21189   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
21190 }
21191
21192 /*
21193 ** Check the existance and status of a file.
21194 */
21195 static int os2Access(
21196   sqlite3_vfs *pVfs,        /* Not used on os2 */
21197   const char *zFilename,    /* Name of file to check */
21198   int flags,                /* Type of test to make on this file */
21199   int *pOut                 /* Write results here */
21200 ){
21201   FILESTATUS3 fsts3ConfigInfo;
21202   APIRET rc = NO_ERROR;
21203   char *zFilenameCp = convertUtf8PathToCp( zFilename );
21204
21205   memset( &fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo) );
21206   rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
21207                          &fsts3ConfigInfo, sizeof(FILESTATUS3) );
21208   free( zFilenameCp );
21209   OSTRACE4( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
21210             fsts3ConfigInfo.attrFile, flags, rc );
21211   switch( flags ){
21212     case SQLITE_ACCESS_READ:
21213     case SQLITE_ACCESS_EXISTS:
21214       rc = (rc == NO_ERROR);
21215       OSTRACE3( "ACCESS %s access of read and exists  rc=%d\n", zFilename, rc );
21216       break;
21217     case SQLITE_ACCESS_READWRITE:
21218       rc = (rc == NO_ERROR) && ( (fsts3ConfigInfo.attrFile & FILE_READONLY) == 0 );
21219       OSTRACE3( "ACCESS %s access of read/write  rc=%d\n", zFilename, rc );
21220       break;
21221     default:
21222       assert( !"Invalid flags argument" );
21223   }
21224   *pOut = rc;
21225   return SQLITE_OK;
21226 }
21227
21228
21229 #ifndef SQLITE_OMIT_LOAD_EXTENSION
21230 /*
21231 ** Interfaces for opening a shared library, finding entry points
21232 ** within the shared library, and closing the shared library.
21233 */
21234 /*
21235 ** Interfaces for opening a shared library, finding entry points
21236 ** within the shared library, and closing the shared library.
21237 */
21238 static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
21239   UCHAR loadErr[256];
21240   HMODULE hmod;
21241   APIRET rc;
21242   char *zFilenameCp = convertUtf8PathToCp(zFilename);
21243   rc = DosLoadModule((PSZ)loadErr, sizeof(loadErr), zFilenameCp, &hmod);
21244   free(zFilenameCp);
21245   return rc != NO_ERROR ? 0 : (void*)hmod;
21246 }
21247 /*
21248 ** A no-op since the error code is returned on the DosLoadModule call.
21249 ** os2Dlopen returns zero if DosLoadModule is not successful.
21250 */
21251 static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
21252 /* no-op */
21253 }
21254 static void *os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
21255   PFN pfn;
21256   APIRET rc;
21257   rc = DosQueryProcAddr((HMODULE)pHandle, 0L, zSymbol, &pfn);
21258   if( rc != NO_ERROR ){
21259     /* if the symbol itself was not found, search again for the same
21260      * symbol with an extra underscore, that might be needed depending
21261      * on the calling convention */
21262     char _zSymbol[256] = "_";
21263     strncat(_zSymbol, zSymbol, 255);
21264     rc = DosQueryProcAddr((HMODULE)pHandle, 0L, _zSymbol, &pfn);
21265   }
21266   return rc != NO_ERROR ? 0 : (void*)pfn;
21267 }
21268 static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
21269   DosFreeModule((HMODULE)pHandle);
21270 }
21271 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
21272   #define os2DlOpen 0
21273   #define os2DlError 0
21274   #define os2DlSym 0
21275   #define os2DlClose 0
21276 #endif
21277
21278
21279 /*
21280 ** Write up to nBuf bytes of randomness into zBuf.
21281 */
21282 static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
21283   ULONG sizeofULong = sizeof(ULONG);
21284   int n = 0;
21285   if( sizeof(DATETIME) <= nBuf - n ){
21286     DATETIME x;
21287     DosGetDateTime(&x);
21288     memcpy(&zBuf[n], &x, sizeof(x));
21289     n += sizeof(x);
21290   }
21291
21292   if( sizeofULong <= nBuf - n ){
21293     PPIB ppib;
21294     DosGetInfoBlocks(NULL, &ppib);
21295     memcpy(&zBuf[n], &ppib->pib_ulpid, sizeofULong);
21296     n += sizeofULong;
21297   }
21298
21299   if( sizeofULong <= nBuf - n ){
21300     PTIB ptib;
21301     DosGetInfoBlocks(&ptib, NULL);
21302     memcpy(&zBuf[n], &ptib->tib_ptib2->tib2_ultid, sizeofULong);
21303     n += sizeofULong;
21304   }
21305
21306   /* if we still haven't filled the buffer yet the following will */
21307   /* grab everything once instead of making several calls for a single item */
21308   if( sizeofULong <= nBuf - n ){
21309     ULONG ulSysInfo[QSV_MAX];
21310     DosQuerySysInfo(1L, QSV_MAX, ulSysInfo, sizeofULong * QSV_MAX);
21311
21312     memcpy(&zBuf[n], &ulSysInfo[QSV_MS_COUNT - 1], sizeofULong);
21313     n += sizeofULong;
21314
21315     if( sizeofULong <= nBuf - n ){
21316       memcpy(&zBuf[n], &ulSysInfo[QSV_TIMER_INTERVAL - 1], sizeofULong);
21317       n += sizeofULong;
21318     }
21319     if( sizeofULong <= nBuf - n ){
21320       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_LOW - 1], sizeofULong);
21321       n += sizeofULong;
21322     }
21323     if( sizeofULong <= nBuf - n ){
21324       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_HIGH - 1], sizeofULong);
21325       n += sizeofULong;
21326     }
21327     if( sizeofULong <= nBuf - n ){
21328       memcpy(&zBuf[n], &ulSysInfo[QSV_TOTAVAILMEM - 1], sizeofULong);
21329       n += sizeofULong;
21330     }
21331   }
21332
21333   return n;
21334 }
21335
21336 /*
21337 ** Sleep for a little while.  Return the amount of time slept.
21338 ** The argument is the number of microseconds we want to sleep.
21339 ** The return value is the number of microseconds of sleep actually
21340 ** requested from the underlying operating system, a number which
21341 ** might be greater than or equal to the argument, but not less
21342 ** than the argument.
21343 */
21344 static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
21345   DosSleep( (microsec/1000) );
21346   return microsec;
21347 }
21348
21349 /*
21350 ** The following variable, if set to a non-zero value, becomes the result
21351 ** returned from sqlite3OsCurrentTime().  This is used for testing.
21352 */
21353 #ifdef SQLITE_TEST
21354 SQLITE_API int sqlite3_current_time = 0;
21355 #endif
21356
21357 /*
21358 ** Find the current time (in Universal Coordinated Time).  Write the
21359 ** current time and date as a Julian Day number into *prNow and
21360 ** return 0.  Return 1 if the time and date cannot be found.
21361 */
21362 int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
21363   double now;
21364   SHORT minute; /* needs to be able to cope with negative timezone offset */
21365   USHORT second, hour,
21366          day, month, year;
21367   DATETIME dt;
21368   DosGetDateTime( &dt );
21369   second = (USHORT)dt.seconds;
21370   minute = (SHORT)dt.minutes + dt.timezone;
21371   hour = (USHORT)dt.hours;
21372   day = (USHORT)dt.day;
21373   month = (USHORT)dt.month;
21374   year = (USHORT)dt.year;
21375
21376   /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
21377      http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c */
21378   /* Calculate the Julian days */
21379   now = day - 32076 +
21380     1461*(year + 4800 + (month - 14)/12)/4 +
21381     367*(month - 2 - (month - 14)/12*12)/12 -
21382     3*((year + 4900 + (month - 14)/12)/100)/4;
21383
21384   /* Add the fractional hours, mins and seconds */
21385   now += (hour + 12.0)/24.0;
21386   now += minute/1440.0;
21387   now += second/86400.0;
21388   *prNow = now;
21389 #ifdef SQLITE_TEST
21390   if( sqlite3_current_time ){
21391     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
21392   }
21393 #endif
21394   return 0;
21395 }
21396
21397 static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
21398   return 0;
21399 }
21400
21401 /*
21402 ** Initialize and deinitialize the operating system interface.
21403 */
21404 SQLITE_API int sqlite3_os_init(void){
21405   static sqlite3_vfs os2Vfs = {
21406     1,                 /* iVersion */
21407     sizeof(os2File),   /* szOsFile */
21408     CCHMAXPATH,        /* mxPathname */
21409     0,                 /* pNext */
21410     "os2",             /* zName */
21411     0,                 /* pAppData */
21412
21413     os2Open,           /* xOpen */
21414     os2Delete,         /* xDelete */
21415     os2Access,         /* xAccess */
21416     os2FullPathname,   /* xFullPathname */
21417     os2DlOpen,         /* xDlOpen */
21418     os2DlError,        /* xDlError */
21419     os2DlSym,          /* xDlSym */
21420     os2DlClose,        /* xDlClose */
21421     os2Randomness,     /* xRandomness */
21422     os2Sleep,          /* xSleep */
21423     os2CurrentTime,    /* xCurrentTime */
21424     os2GetLastError    /* xGetLastError */
21425   };
21426   sqlite3_vfs_register(&os2Vfs, 1);
21427   initUconvObjects();
21428   return SQLITE_OK;
21429 }
21430 SQLITE_API int sqlite3_os_end(void){
21431   freeUconvObjects();
21432   return SQLITE_OK;
21433 }
21434
21435 #endif /* SQLITE_OS_OS2 */
21436
21437 /************** End of os_os2.c **********************************************/
21438 /************** Begin file os_unix.c *****************************************/
21439 /*
21440 ** 2004 May 22
21441 **
21442 ** The author disclaims copyright to this source code.  In place of
21443 ** a legal notice, here is a blessing:
21444 **
21445 **    May you do good and not evil.
21446 **    May you find forgiveness for yourself and forgive others.
21447 **    May you share freely, never taking more than you give.
21448 **
21449 ******************************************************************************
21450 **
21451 ** This file contains code that is specific to Unix systems.
21452 **
21453 ** $Id: os_unix.c,v 1.201 2008/09/15 04:20:32 danielk1977 Exp $
21454 */
21455 #if SQLITE_OS_UNIX              /* This file is used on unix only */
21456
21457 /*
21458 ** If SQLITE_ENABLE_LOCKING_STYLE is defined, then several different 
21459 ** locking implementations are provided:
21460 **
21461 **   * POSIX locking (the default),
21462 **   * No locking,
21463 **   * Dot-file locking,
21464 **   * flock() locking,
21465 **   * AFP locking (OSX only).
21466 */
21467 /* #define SQLITE_ENABLE_LOCKING_STYLE 0 */
21468
21469 /*
21470 ** These #defines should enable >2GB file support on Posix if the
21471 ** underlying operating system supports it.  If the OS lacks
21472 ** large file support, these should be no-ops.
21473 **
21474 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
21475 ** on the compiler command line.  This is necessary if you are compiling
21476 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
21477 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
21478 ** without this option, LFS is enable.  But LFS does not exist in the kernel
21479 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
21480 ** portability you should omit LFS.
21481 */
21482 #ifndef SQLITE_DISABLE_LFS
21483 # define _LARGE_FILE       1
21484 # ifndef _FILE_OFFSET_BITS
21485 #   define _FILE_OFFSET_BITS 64
21486 # endif
21487 # define _LARGEFILE_SOURCE 1
21488 #endif
21489
21490 /*
21491 ** standard include files.
21492 */
21493 #include <sys/types.h>
21494 #include <sys/stat.h>
21495 #include <fcntl.h>
21496 #include <unistd.h>
21497 #include <sys/time.h>
21498 #include <errno.h>
21499
21500 #ifdef SQLITE_ENABLE_LOCKING_STYLE
21501 #include <sys/ioctl.h>
21502 #include <sys/param.h>
21503 #include <sys/mount.h>
21504 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
21505
21506 /*
21507 ** If we are to be thread-safe, include the pthreads header and define
21508 ** the SQLITE_UNIX_THREADS macro.
21509 */
21510 #if SQLITE_THREADSAFE
21511 # define SQLITE_UNIX_THREADS 1
21512 #endif
21513
21514 /*
21515 ** Default permissions when creating a new file
21516 */
21517 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
21518 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
21519 #endif
21520
21521 /*
21522 ** Maximum supported path-length.
21523 */
21524 #define MAX_PATHNAME 512
21525
21526
21527 /*
21528 ** The unixFile structure is subclass of sqlite3_file specific for the unix
21529 ** protability layer.
21530 */
21531 typedef struct unixFile unixFile;
21532 struct unixFile {
21533   sqlite3_io_methods const *pMethod;  /* Always the first entry */
21534 #ifdef SQLITE_TEST
21535   /* In test mode, increase the size of this structure a bit so that 
21536   ** it is larger than the struct CrashFile defined in test6.c.
21537   */
21538   char aPadding[32];
21539 #endif
21540   struct openCnt *pOpen;    /* Info about all open fd's on this inode */
21541   struct lockInfo *pLock;   /* Info about locks on this inode */
21542 #ifdef SQLITE_ENABLE_LOCKING_STYLE
21543   void *lockingContext;     /* Locking style specific state */
21544 #endif
21545   int h;                    /* The file descriptor */
21546   unsigned char locktype;   /* The type of lock held on this fd */
21547   int dirfd;                /* File descriptor for the directory */
21548 #if SQLITE_THREADSAFE
21549   pthread_t tid;            /* The thread that "owns" this unixFile */
21550 #endif
21551   int lastErrno;            /* The unix errno from the last I/O error */
21552 };
21553
21554 /*
21555 ** Include code that is common to all os_*.c files
21556 */
21557 /************** Include os_common.h in the middle of os_unix.c ***************/
21558 /************** Begin file os_common.h ***************************************/
21559 /*
21560 ** 2004 May 22
21561 **
21562 ** The author disclaims copyright to this source code.  In place of
21563 ** a legal notice, here is a blessing:
21564 **
21565 **    May you do good and not evil.
21566 **    May you find forgiveness for yourself and forgive others.
21567 **    May you share freely, never taking more than you give.
21568 **
21569 ******************************************************************************
21570 **
21571 ** This file contains macros and a little bit of code that is common to
21572 ** all of the platform-specific files (os_*.c) and is #included into those
21573 ** files.
21574 **
21575 ** This file should be #included by the os_*.c files only.  It is not a
21576 ** general purpose header file.
21577 **
21578 ** $Id: os_common.h,v 1.37 2008/05/29 20:22:37 shane Exp $
21579 */
21580 #ifndef _OS_COMMON_H_
21581 #define _OS_COMMON_H_
21582
21583 /*
21584 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
21585 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
21586 ** switch.  The following code should catch this problem at compile-time.
21587 */
21588 #ifdef MEMORY_DEBUG
21589 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
21590 #endif
21591
21592
21593 /*
21594  * When testing, this global variable stores the location of the
21595  * pending-byte in the database file.
21596  */
21597 #ifdef SQLITE_TEST
21598 SQLITE_API unsigned int sqlite3_pending_byte = 0x40000000;
21599 #endif
21600
21601 #ifdef SQLITE_DEBUG
21602 SQLITE_PRIVATE int sqlite3OSTrace = 0;
21603 #define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
21604 #define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
21605 #define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
21606 #define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
21607 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
21608 #define OSTRACE6(X,Y,Z,A,B,C) \
21609     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
21610 #define OSTRACE7(X,Y,Z,A,B,C,D) \
21611     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
21612 #else
21613 #define OSTRACE1(X)
21614 #define OSTRACE2(X,Y)
21615 #define OSTRACE3(X,Y,Z)
21616 #define OSTRACE4(X,Y,Z,A)
21617 #define OSTRACE5(X,Y,Z,A,B)
21618 #define OSTRACE6(X,Y,Z,A,B,C)
21619 #define OSTRACE7(X,Y,Z,A,B,C,D)
21620 #endif
21621
21622 /*
21623 ** Macros for performance tracing.  Normally turned off.  Only works
21624 ** on i486 hardware.
21625 */
21626 #ifdef SQLITE_PERFORMANCE_TRACE
21627
21628 /* 
21629 ** hwtime.h contains inline assembler code for implementing 
21630 ** high-performance timing routines.
21631 */
21632 /************** Include hwtime.h in the middle of os_common.h ****************/
21633 /************** Begin file hwtime.h ******************************************/
21634 /*
21635 ** 2008 May 27
21636 **
21637 ** The author disclaims copyright to this source code.  In place of
21638 ** a legal notice, here is a blessing:
21639 **
21640 **    May you do good and not evil.
21641 **    May you find forgiveness for yourself and forgive others.
21642 **    May you share freely, never taking more than you give.
21643 **
21644 ******************************************************************************
21645 **
21646 ** This file contains inline asm code for retrieving "high-performance"
21647 ** counters for x86 class CPUs.
21648 **
21649 ** $Id: hwtime.h,v 1.3 2008/08/01 14:33:15 shane Exp $
21650 */
21651 #ifndef _HWTIME_H_
21652 #define _HWTIME_H_
21653
21654 /*
21655 ** The following routine only works on pentium-class (or newer) processors.
21656 ** It uses the RDTSC opcode to read the cycle count value out of the
21657 ** processor and returns that value.  This can be used for high-res
21658 ** profiling.
21659 */
21660 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
21661       (defined(i386) || defined(__i386__) || defined(_M_IX86))
21662
21663   #if defined(__GNUC__)
21664
21665   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21666      unsigned int lo, hi;
21667      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
21668      return (sqlite_uint64)hi << 32 | lo;
21669   }
21670
21671   #elif defined(_MSC_VER)
21672
21673   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
21674      __asm {
21675         rdtsc
21676         ret       ; return value at EDX:EAX
21677      }
21678   }
21679
21680   #endif
21681
21682 #elif (defined(__GNUC__) && defined(__x86_64__))
21683
21684   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21685       unsigned long val;
21686       __asm__ __volatile__ ("rdtsc" : "=A" (val));
21687       return val;
21688   }
21689  
21690 #elif (defined(__GNUC__) && defined(__ppc__))
21691
21692   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21693       unsigned long long retval;
21694       unsigned long junk;
21695       __asm__ __volatile__ ("\n\
21696           1:      mftbu   %1\n\
21697                   mftb    %L0\n\
21698                   mftbu   %0\n\
21699                   cmpw    %0,%1\n\
21700                   bne     1b"
21701                   : "=r" (retval), "=r" (junk));
21702       return retval;
21703   }
21704
21705 #else
21706
21707   #error Need implementation of sqlite3Hwtime() for your platform.
21708
21709   /*
21710   ** To compile without implementing sqlite3Hwtime() for your platform,
21711   ** you can remove the above #error and use the following
21712   ** stub function.  You will lose timing support for many
21713   ** of the debugging and testing utilities, but it should at
21714   ** least compile and run.
21715   */
21716 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
21717
21718 #endif
21719
21720 #endif /* !defined(_HWTIME_H_) */
21721
21722 /************** End of hwtime.h **********************************************/
21723 /************** Continuing where we left off in os_common.h ******************/
21724
21725 static sqlite_uint64 g_start;
21726 static sqlite_uint64 g_elapsed;
21727 #define TIMER_START       g_start=sqlite3Hwtime()
21728 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
21729 #define TIMER_ELAPSED     g_elapsed
21730 #else
21731 #define TIMER_START
21732 #define TIMER_END
21733 #define TIMER_ELAPSED     ((sqlite_uint64)0)
21734 #endif
21735
21736 /*
21737 ** If we compile with the SQLITE_TEST macro set, then the following block
21738 ** of code will give us the ability to simulate a disk I/O error.  This
21739 ** is used for testing the I/O recovery logic.
21740 */
21741 #ifdef SQLITE_TEST
21742 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
21743 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
21744 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
21745 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
21746 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
21747 SQLITE_API int sqlite3_diskfull_pending = 0;
21748 SQLITE_API int sqlite3_diskfull = 0;
21749 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
21750 #define SimulateIOError(CODE)  \
21751   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
21752        || sqlite3_io_error_pending-- == 1 )  \
21753               { local_ioerr(); CODE; }
21754 static void local_ioerr(){
21755   IOTRACE(("IOERR\n"));
21756   sqlite3_io_error_hit++;
21757   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
21758 }
21759 #define SimulateDiskfullError(CODE) \
21760    if( sqlite3_diskfull_pending ){ \
21761      if( sqlite3_diskfull_pending == 1 ){ \
21762        local_ioerr(); \
21763        sqlite3_diskfull = 1; \
21764        sqlite3_io_error_hit = 1; \
21765        CODE; \
21766      }else{ \
21767        sqlite3_diskfull_pending--; \
21768      } \
21769    }
21770 #else
21771 #define SimulateIOErrorBenign(X)
21772 #define SimulateIOError(A)
21773 #define SimulateDiskfullError(A)
21774 #endif
21775
21776 /*
21777 ** When testing, keep a count of the number of open files.
21778 */
21779 #ifdef SQLITE_TEST
21780 SQLITE_API int sqlite3_open_file_count = 0;
21781 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
21782 #else
21783 #define OpenCounter(X)
21784 #endif
21785
21786 #endif /* !defined(_OS_COMMON_H_) */
21787
21788 /************** End of os_common.h *******************************************/
21789 /************** Continuing where we left off in os_unix.c ********************/
21790
21791 /*
21792 ** Define various macros that are missing from some systems.
21793 */
21794 #ifndef O_LARGEFILE
21795 # define O_LARGEFILE 0
21796 #endif
21797 #ifdef SQLITE_DISABLE_LFS
21798 # undef O_LARGEFILE
21799 # define O_LARGEFILE 0
21800 #endif
21801 #ifndef O_NOFOLLOW
21802 # define O_NOFOLLOW 0
21803 #endif
21804 #ifndef O_BINARY
21805 # define O_BINARY 0
21806 #endif
21807
21808 /*
21809 ** The DJGPP compiler environment looks mostly like Unix, but it
21810 ** lacks the fcntl() system call.  So redefine fcntl() to be something
21811 ** that always succeeds.  This means that locking does not occur under
21812 ** DJGPP.  But it is DOS - what did you expect?
21813 */
21814 #ifdef __DJGPP__
21815 # define fcntl(A,B,C) 0
21816 #endif
21817
21818 /*
21819 ** The threadid macro resolves to the thread-id or to 0.  Used for
21820 ** testing and debugging only.
21821 */
21822 #if SQLITE_THREADSAFE
21823 #define threadid pthread_self()
21824 #else
21825 #define threadid 0
21826 #endif
21827
21828 /*
21829 ** Set or check the unixFile.tid field.  This field is set when an unixFile
21830 ** is first opened.  All subsequent uses of the unixFile verify that the
21831 ** same thread is operating on the unixFile.  Some operating systems do
21832 ** not allow locks to be overridden by other threads and that restriction
21833 ** means that sqlite3* database handles cannot be moved from one thread
21834 ** to another.  This logic makes sure a user does not try to do that
21835 ** by mistake.
21836 **
21837 ** Version 3.3.1 (2006-01-15):  unixFile can be moved from one thread to
21838 ** another as long as we are running on a system that supports threads
21839 ** overriding each others locks (which now the most common behavior)
21840 ** or if no locks are held.  But the unixFile.pLock field needs to be
21841 ** recomputed because its key includes the thread-id.  See the 
21842 ** transferOwnership() function below for additional information
21843 */
21844 #if SQLITE_THREADSAFE
21845 # define SET_THREADID(X)   (X)->tid = pthread_self()
21846 # define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
21847                             !pthread_equal((X)->tid, pthread_self()))
21848 #else
21849 # define SET_THREADID(X)
21850 # define CHECK_THREADID(X) 0
21851 #endif
21852
21853 /*
21854 ** Here is the dirt on POSIX advisory locks:  ANSI STD 1003.1 (1996)
21855 ** section 6.5.2.2 lines 483 through 490 specify that when a process
21856 ** sets or clears a lock, that operation overrides any prior locks set
21857 ** by the same process.  It does not explicitly say so, but this implies
21858 ** that it overrides locks set by the same process using a different
21859 ** file descriptor.  Consider this test case:
21860 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
21861 **
21862 ** Suppose ./file1 and ./file2 are really the same file (because
21863 ** one is a hard or symbolic link to the other) then if you set
21864 ** an exclusive lock on fd1, then try to get an exclusive lock
21865 ** on fd2, it works.  I would have expected the second lock to
21866 ** fail since there was already a lock on the file due to fd1.
21867 ** But not so.  Since both locks came from the same process, the
21868 ** second overrides the first, even though they were on different
21869 ** file descriptors opened on different file names.
21870 **
21871 ** Bummer.  If you ask me, this is broken.  Badly broken.  It means
21872 ** that we cannot use POSIX locks to synchronize file access among
21873 ** competing threads of the same process.  POSIX locks will work fine
21874 ** to synchronize access for threads in separate processes, but not
21875 ** threads within the same process.
21876 **
21877 ** To work around the problem, SQLite has to manage file locks internally
21878 ** on its own.  Whenever a new database is opened, we have to find the
21879 ** specific inode of the database file (the inode is determined by the
21880 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
21881 ** and check for locks already existing on that inode.  When locks are
21882 ** created or removed, we have to look at our own internal record of the
21883 ** locks to see if another thread has previously set a lock on that same
21884 ** inode.
21885 **
21886 ** The sqlite3_file structure for POSIX is no longer just an integer file
21887 ** descriptor.  It is now a structure that holds the integer file
21888 ** descriptor and a pointer to a structure that describes the internal
21889 ** locks on the corresponding inode.  There is one locking structure
21890 ** per inode, so if the same inode is opened twice, both unixFile structures
21891 ** point to the same locking structure.  The locking structure keeps
21892 ** a reference count (so we will know when to delete it) and a "cnt"
21893 ** field that tells us its internal lock status.  cnt==0 means the
21894 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
21895 ** cnt>0 means there are cnt shared locks on the file.
21896 **
21897 ** Any attempt to lock or unlock a file first checks the locking
21898 ** structure.  The fcntl() system call is only invoked to set a 
21899 ** POSIX lock if the internal lock structure transitions between
21900 ** a locked and an unlocked state.
21901 **
21902 ** 2004-Jan-11:
21903 ** More recent discoveries about POSIX advisory locks.  (The more
21904 ** I discover, the more I realize the a POSIX advisory locks are
21905 ** an abomination.)
21906 **
21907 ** If you close a file descriptor that points to a file that has locks,
21908 ** all locks on that file that are owned by the current process are
21909 ** released.  To work around this problem, each unixFile structure contains
21910 ** a pointer to an openCnt structure.  There is one openCnt structure
21911 ** per open inode, which means that multiple unixFile can point to a single
21912 ** openCnt.  When an attempt is made to close an unixFile, if there are
21913 ** other unixFile open on the same inode that are holding locks, the call
21914 ** to close() the file descriptor is deferred until all of the locks clear.
21915 ** The openCnt structure keeps a list of file descriptors that need to
21916 ** be closed and that list is walked (and cleared) when the last lock
21917 ** clears.
21918 **
21919 ** First, under Linux threads, because each thread has a separate
21920 ** process ID, lock operations in one thread do not override locks
21921 ** to the same file in other threads.  Linux threads behave like
21922 ** separate processes in this respect.  But, if you close a file
21923 ** descriptor in linux threads, all locks are cleared, even locks
21924 ** on other threads and even though the other threads have different
21925 ** process IDs.  Linux threads is inconsistent in this respect.
21926 ** (I'm beginning to think that linux threads is an abomination too.)
21927 ** The consequence of this all is that the hash table for the lockInfo
21928 ** structure has to include the process id as part of its key because
21929 ** locks in different threads are treated as distinct.  But the 
21930 ** openCnt structure should not include the process id in its
21931 ** key because close() clears lock on all threads, not just the current
21932 ** thread.  Were it not for this goofiness in linux threads, we could
21933 ** combine the lockInfo and openCnt structures into a single structure.
21934 **
21935 ** 2004-Jun-28:
21936 ** On some versions of linux, threads can override each others locks.
21937 ** On others not.  Sometimes you can change the behavior on the same
21938 ** system by setting the LD_ASSUME_KERNEL environment variable.  The
21939 ** POSIX standard is silent as to which behavior is correct, as far
21940 ** as I can tell, so other versions of unix might show the same
21941 ** inconsistency.  There is no little doubt in my mind that posix
21942 ** advisory locks and linux threads are profoundly broken.
21943 **
21944 ** To work around the inconsistencies, we have to test at runtime 
21945 ** whether or not threads can override each others locks.  This test
21946 ** is run once, the first time any lock is attempted.  A static 
21947 ** variable is set to record the results of this test for future
21948 ** use.
21949 */
21950
21951 /*
21952 ** An instance of the following structure serves as the key used
21953 ** to locate a particular lockInfo structure given its inode.
21954 **
21955 ** If threads cannot override each others locks, then we set the
21956 ** lockKey.tid field to the thread ID.  If threads can override
21957 ** each others locks then tid is always set to zero.  tid is omitted
21958 ** if we compile without threading support.
21959 */
21960 struct lockKey {
21961   dev_t dev;       /* Device number */
21962   ino_t ino;       /* Inode number */
21963 #if SQLITE_THREADSAFE
21964   pthread_t tid;   /* Thread ID or zero if threads can override each other */
21965 #endif
21966 };
21967
21968 /*
21969 ** An instance of the following structure is allocated for each open
21970 ** inode on each thread with a different process ID.  (Threads have
21971 ** different process IDs on linux, but not on most other unixes.)
21972 **
21973 ** A single inode can have multiple file descriptors, so each unixFile
21974 ** structure contains a pointer to an instance of this object and this
21975 ** object keeps a count of the number of unixFile pointing to it.
21976 */
21977 struct lockInfo {
21978   struct lockKey key;  /* The lookup key */
21979   int cnt;             /* Number of SHARED locks held */
21980   int locktype;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
21981   int nRef;            /* Number of pointers to this structure */
21982   struct lockInfo *pNext, *pPrev;   /* List of all lockInfo objects */
21983 };
21984
21985 /*
21986 ** An instance of the following structure serves as the key used
21987 ** to locate a particular openCnt structure given its inode.  This
21988 ** is the same as the lockKey except that the thread ID is omitted.
21989 */
21990 struct openKey {
21991   dev_t dev;   /* Device number */
21992   ino_t ino;   /* Inode number */
21993 };
21994
21995 /*
21996 ** An instance of the following structure is allocated for each open
21997 ** inode.  This structure keeps track of the number of locks on that
21998 ** inode.  If a close is attempted against an inode that is holding
21999 ** locks, the close is deferred until all locks clear by adding the
22000 ** file descriptor to be closed to the pending list.
22001 */
22002 struct openCnt {
22003   struct openKey key;   /* The lookup key */
22004   int nRef;             /* Number of pointers to this structure */
22005   int nLock;            /* Number of outstanding locks */
22006   int nPending;         /* Number of pending close() operations */
22007   int *aPending;        /* Malloced space holding fd's awaiting a close() */
22008   struct openCnt *pNext, *pPrev;   /* List of all openCnt objects */
22009 };
22010
22011 /*
22012 ** List of all lockInfo and openCnt objects.  This used to be a hash
22013 ** table.  But the number of objects is rarely more than a dozen and
22014 ** never exceeds a few thousand.  And lookup is not on a critical
22015 ** path oo a simple linked list will suffice.
22016 */
22017 static struct lockInfo *lockList = 0;
22018 static struct openCnt *openList = 0;
22019
22020 /*
22021 ** The locking styles are associated with the different file locking
22022 ** capabilities supported by different file systems.  
22023 **
22024 ** POSIX locking style fully supports shared and exclusive byte-range locks 
22025 ** AFP locking only supports exclusive byte-range locks
22026 ** FLOCK only supports a single file-global exclusive lock
22027 ** DOTLOCK isn't a true locking style, it refers to the use of a special
22028 **   file named the same as the database file with a '.lock' extension, this
22029 **   can be used on file systems that do not offer any reliable file locking
22030 ** NO locking means that no locking will be attempted, this is only used for
22031 **   read-only file systems currently
22032 ** UNSUPPORTED means that no locking will be attempted, this is only used for
22033 **   file systems that are known to be unsupported
22034 */
22035 #define LOCKING_STYLE_POSIX        1
22036 #define LOCKING_STYLE_NONE         2
22037 #define LOCKING_STYLE_DOTFILE      3
22038 #define LOCKING_STYLE_FLOCK        4
22039 #define LOCKING_STYLE_AFP          5
22040
22041 /*
22042 ** Only set the lastErrno if the error code is a real error and not 
22043 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
22044 */
22045 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
22046
22047 /*
22048 ** Helper functions to obtain and relinquish the global mutex.
22049 */
22050 static void enterMutex(){
22051   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22052 }
22053 static void leaveMutex(){
22054   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22055 }
22056
22057 #if SQLITE_THREADSAFE
22058 /*
22059 ** This variable records whether or not threads can override each others
22060 ** locks.
22061 **
22062 **    0:  No.  Threads cannot override each others locks.
22063 **    1:  Yes.  Threads can override each others locks.
22064 **   -1:  We don't know yet.
22065 **
22066 ** On some systems, we know at compile-time if threads can override each
22067 ** others locks.  On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
22068 ** will be set appropriately.  On other systems, we have to check at
22069 ** runtime.  On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
22070 ** undefined.
22071 **
22072 ** This variable normally has file scope only.  But during testing, we make
22073 ** it a global so that the test code can change its value in order to verify
22074 ** that the right stuff happens in either case.
22075 */
22076 #ifndef SQLITE_THREAD_OVERRIDE_LOCK
22077 # define SQLITE_THREAD_OVERRIDE_LOCK -1
22078 #endif
22079 #ifdef SQLITE_TEST
22080 int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
22081 #else
22082 static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
22083 #endif
22084
22085 /*
22086 ** This structure holds information passed into individual test
22087 ** threads by the testThreadLockingBehavior() routine.
22088 */
22089 struct threadTestData {
22090   int fd;                /* File to be locked */
22091   struct flock lock;     /* The locking operation */
22092   int result;            /* Result of the locking operation */
22093 };
22094
22095 #ifdef SQLITE_LOCK_TRACE
22096 /*
22097 ** Print out information about all locking operations.
22098 **
22099 ** This routine is used for troubleshooting locks on multithreaded
22100 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
22101 ** command-line option on the compiler.  This code is normally
22102 ** turned off.
22103 */
22104 static int lockTrace(int fd, int op, struct flock *p){
22105   char *zOpName, *zType;
22106   int s;
22107   int savedErrno;
22108   if( op==F_GETLK ){
22109     zOpName = "GETLK";
22110   }else if( op==F_SETLK ){
22111     zOpName = "SETLK";
22112   }else{
22113     s = fcntl(fd, op, p);
22114     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
22115     return s;
22116   }
22117   if( p->l_type==F_RDLCK ){
22118     zType = "RDLCK";
22119   }else if( p->l_type==F_WRLCK ){
22120     zType = "WRLCK";
22121   }else if( p->l_type==F_UNLCK ){
22122     zType = "UNLCK";
22123   }else{
22124     assert( 0 );
22125   }
22126   assert( p->l_whence==SEEK_SET );
22127   s = fcntl(fd, op, p);
22128   savedErrno = errno;
22129   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
22130      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
22131      (int)p->l_pid, s);
22132   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
22133     struct flock l2;
22134     l2 = *p;
22135     fcntl(fd, F_GETLK, &l2);
22136     if( l2.l_type==F_RDLCK ){
22137       zType = "RDLCK";
22138     }else if( l2.l_type==F_WRLCK ){
22139       zType = "WRLCK";
22140     }else if( l2.l_type==F_UNLCK ){
22141       zType = "UNLCK";
22142     }else{
22143       assert( 0 );
22144     }
22145     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
22146        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
22147   }
22148   errno = savedErrno;
22149   return s;
22150 }
22151 #define fcntl lockTrace
22152 #endif /* SQLITE_LOCK_TRACE */
22153
22154 /*
22155 ** The testThreadLockingBehavior() routine launches two separate
22156 ** threads on this routine.  This routine attempts to lock a file
22157 ** descriptor then returns.  The success or failure of that attempt
22158 ** allows the testThreadLockingBehavior() procedure to determine
22159 ** whether or not threads can override each others locks.
22160 */
22161 static void *threadLockingTest(void *pArg){
22162   struct threadTestData *pData = (struct threadTestData*)pArg;
22163   pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
22164   return pArg;
22165 }
22166
22167 /*
22168 ** This procedure attempts to determine whether or not threads
22169 ** can override each others locks then sets the 
22170 ** threadsOverrideEachOthersLocks variable appropriately.
22171 */
22172 static void testThreadLockingBehavior(int fd_orig){
22173   int fd;
22174   struct threadTestData d[2];
22175   pthread_t t[2];
22176
22177   fd = dup(fd_orig);
22178   if( fd<0 ) return;
22179   memset(d, 0, sizeof(d));
22180   d[0].fd = fd;
22181   d[0].lock.l_type = F_RDLCK;
22182   d[0].lock.l_len = 1;
22183   d[0].lock.l_start = 0;
22184   d[0].lock.l_whence = SEEK_SET;
22185   d[1] = d[0];
22186   d[1].lock.l_type = F_WRLCK;
22187   pthread_create(&t[0], 0, threadLockingTest, &d[0]);
22188   pthread_create(&t[1], 0, threadLockingTest, &d[1]);
22189   pthread_join(t[0], 0);
22190   pthread_join(t[1], 0);
22191   close(fd);
22192   threadsOverrideEachOthersLocks =  d[0].result==0 && d[1].result==0;
22193 }
22194 #endif /* SQLITE_THREADSAFE */
22195
22196 /*
22197 ** Release a lockInfo structure previously allocated by findLockInfo().
22198 */
22199 static void releaseLockInfo(struct lockInfo *pLock){
22200   if( pLock ){
22201     pLock->nRef--;
22202     if( pLock->nRef==0 ){
22203       if( pLock->pPrev ){
22204         assert( pLock->pPrev->pNext==pLock );
22205         pLock->pPrev->pNext = pLock->pNext;
22206       }else{
22207         assert( lockList==pLock );
22208         lockList = pLock->pNext;
22209       }
22210       if( pLock->pNext ){
22211         assert( pLock->pNext->pPrev==pLock );
22212         pLock->pNext->pPrev = pLock->pPrev;
22213       }
22214       sqlite3_free(pLock);
22215     }
22216   }
22217 }
22218
22219 /*
22220 ** Release a openCnt structure previously allocated by findLockInfo().
22221 */
22222 static void releaseOpenCnt(struct openCnt *pOpen){
22223   if( pOpen ){
22224     pOpen->nRef--;
22225     if( pOpen->nRef==0 ){
22226       if( pOpen->pPrev ){
22227         assert( pOpen->pPrev->pNext==pOpen );
22228         pOpen->pPrev->pNext = pOpen->pNext;
22229       }else{
22230         assert( openList==pOpen );
22231         openList = pOpen->pNext;
22232       }
22233       if( pOpen->pNext ){
22234         assert( pOpen->pNext->pPrev==pOpen );
22235         pOpen->pNext->pPrev = pOpen->pPrev;
22236       }
22237       sqlite3_free(pOpen->aPending);
22238       sqlite3_free(pOpen);
22239     }
22240   }
22241 }
22242
22243 #ifdef SQLITE_ENABLE_LOCKING_STYLE
22244 /*
22245 ** Tests a byte-range locking query to see if byte range locks are 
22246 ** supported, if not we fall back to dotlockLockingStyle.
22247 */
22248 static int testLockingStyle(int fd){
22249   struct flock lockInfo;
22250
22251   /* Test byte-range lock using fcntl(). If the call succeeds, 
22252   ** assume that the file-system supports POSIX style locks. 
22253   */
22254   lockInfo.l_len = 1;
22255   lockInfo.l_start = 0;
22256   lockInfo.l_whence = SEEK_SET;
22257   lockInfo.l_type = F_RDLCK;
22258   if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
22259     return LOCKING_STYLE_POSIX;
22260   }
22261   
22262   /* Testing for flock() can give false positives.  So if if the above 
22263   ** test fails, then we fall back to using dot-file style locking.
22264   */  
22265   return LOCKING_STYLE_DOTFILE;
22266 }
22267 #endif
22268
22269 /* 
22270 ** If SQLITE_ENABLE_LOCKING_STYLE is defined, this function Examines the 
22271 ** f_fstypename entry in the statfs structure as returned by stat() for 
22272 ** the file system hosting the database file and selects  the appropriate
22273 ** locking style based on its value.  These values and assignments are 
22274 ** based on Darwin/OSX behavior and have not been thoroughly tested on 
22275 ** other systems.
22276 **
22277 ** If SQLITE_ENABLE_LOCKING_STYLE is not defined, this function always
22278 ** returns LOCKING_STYLE_POSIX.
22279 */
22280 static int detectLockingStyle(
22281   sqlite3_vfs *pVfs,
22282   const char *filePath, 
22283   int fd
22284 ){
22285 #ifdef SQLITE_ENABLE_LOCKING_STYLE
22286   struct Mapping {
22287     const char *zFilesystem;
22288     int eLockingStyle;
22289   } aMap[] = {
22290     { "hfs",    LOCKING_STYLE_POSIX },
22291     { "ufs",    LOCKING_STYLE_POSIX },
22292     { "afpfs",  LOCKING_STYLE_AFP },
22293 #ifdef SQLITE_ENABLE_AFP_LOCKING_SMB
22294     { "smbfs",  LOCKING_STYLE_AFP },
22295 #else
22296     { "smbfs",  LOCKING_STYLE_FLOCK },
22297 #endif
22298     { "msdos",  LOCKING_STYLE_DOTFILE },
22299     { "webdav", LOCKING_STYLE_NONE },
22300     { 0, 0 }
22301   };
22302   int i;
22303   struct statfs fsInfo;
22304
22305   if( !filePath ){
22306     return LOCKING_STYLE_NONE;
22307   }
22308   if( pVfs->pAppData ){
22309     return SQLITE_PTR_TO_INT(pVfs->pAppData);
22310   }
22311
22312   if( statfs(filePath, &fsInfo) != -1 ){
22313     if( fsInfo.f_flags & MNT_RDONLY ){
22314       return LOCKING_STYLE_NONE;
22315     }
22316     for(i=0; aMap[i].zFilesystem; i++){
22317       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
22318         return aMap[i].eLockingStyle;
22319       }
22320     }
22321   }
22322
22323   /* Default case. Handles, amongst others, "nfs". */
22324   return testLockingStyle(fd);  
22325 #endif
22326   return LOCKING_STYLE_POSIX;
22327 }
22328
22329 /*
22330 ** Given a file descriptor, locate lockInfo and openCnt structures that
22331 ** describes that file descriptor.  Create new ones if necessary.  The
22332 ** return values might be uninitialized if an error occurs.
22333 **
22334 ** Return an appropriate error code.
22335 */
22336 static int findLockInfo(
22337   int fd,                      /* The file descriptor used in the key */
22338   struct lockInfo **ppLock,    /* Return the lockInfo structure here */
22339   struct openCnt **ppOpen      /* Return the openCnt structure here */
22340 ){
22341   int rc;
22342   struct lockKey key1;
22343   struct openKey key2;
22344   struct stat statbuf;
22345   struct lockInfo *pLock;
22346   struct openCnt *pOpen;
22347   rc = fstat(fd, &statbuf);
22348   if( rc!=0 ){
22349 #ifdef EOVERFLOW
22350     if( errno==EOVERFLOW ) return SQLITE_NOLFS;
22351 #endif
22352     return SQLITE_IOERR;
22353   }
22354
22355   /* On OS X on an msdos filesystem, the inode number is reported
22356   ** incorrectly for zero-size files.  See ticket #3260.  To work
22357   ** around this problem (we consider it a bug in OS X, not SQLite)
22358   ** we always increase the file size to 1 by writing a single byte
22359   ** prior to accessing the inode number.  The one byte written is
22360   ** an ASCII 'S' character which also happens to be the first byte
22361   ** in the header of every SQLite database.  In this way, if there
22362   ** is a race condition such that another thread has already populated
22363   ** the first page of the database, no damage is done.
22364   */
22365   if( statbuf.st_size==0 ){
22366     write(fd, "S", 1);
22367     rc = fstat(fd, &statbuf);
22368     if( rc!=0 ){
22369       return SQLITE_IOERR;
22370     }
22371   }
22372
22373   memset(&key1, 0, sizeof(key1));
22374   key1.dev = statbuf.st_dev;
22375   key1.ino = statbuf.st_ino;
22376 #if SQLITE_THREADSAFE
22377   if( threadsOverrideEachOthersLocks<0 ){
22378     testThreadLockingBehavior(fd);
22379   }
22380   key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
22381 #endif
22382   memset(&key2, 0, sizeof(key2));
22383   key2.dev = statbuf.st_dev;
22384   key2.ino = statbuf.st_ino;
22385   pLock = lockList;
22386   while( pLock && memcmp(&key1, &pLock->key, sizeof(key1)) ){
22387     pLock = pLock->pNext;
22388   }
22389   if( pLock==0 ){
22390     pLock = sqlite3_malloc( sizeof(*pLock) );
22391     if( pLock==0 ){
22392       rc = SQLITE_NOMEM;
22393       goto exit_findlockinfo;
22394     }
22395     pLock->key = key1;
22396     pLock->nRef = 1;
22397     pLock->cnt = 0;
22398     pLock->locktype = 0;
22399     pLock->pNext = lockList;
22400     pLock->pPrev = 0;
22401     if( lockList ) lockList->pPrev = pLock;
22402     lockList = pLock;
22403   }else{
22404     pLock->nRef++;
22405   }
22406   *ppLock = pLock;
22407   if( ppOpen!=0 ){
22408     pOpen = openList;
22409     while( pOpen && memcmp(&key2, &pOpen->key, sizeof(key2)) ){
22410       pOpen = pOpen->pNext;
22411     }
22412     if( pOpen==0 ){
22413       pOpen = sqlite3_malloc( sizeof(*pOpen) );
22414       if( pOpen==0 ){
22415         releaseLockInfo(pLock);
22416         rc = SQLITE_NOMEM;
22417         goto exit_findlockinfo;
22418       }
22419       pOpen->key = key2;
22420       pOpen->nRef = 1;
22421       pOpen->nLock = 0;
22422       pOpen->nPending = 0;
22423       pOpen->aPending = 0;
22424       pOpen->pNext = openList;
22425       pOpen->pPrev = 0;
22426       if( openList ) openList->pPrev = pOpen;
22427       openList = pOpen;
22428     }else{
22429       pOpen->nRef++;
22430     }
22431     *ppOpen = pOpen;
22432   }
22433
22434 exit_findlockinfo:
22435   return rc;
22436 }
22437
22438 #ifdef SQLITE_DEBUG
22439 /*
22440 ** Helper function for printing out trace information from debugging
22441 ** binaries. This returns the string represetation of the supplied
22442 ** integer lock-type.
22443 */
22444 static const char *locktypeName(int locktype){
22445   switch( locktype ){
22446   case NO_LOCK: return "NONE";
22447   case SHARED_LOCK: return "SHARED";
22448   case RESERVED_LOCK: return "RESERVED";
22449   case PENDING_LOCK: return "PENDING";
22450   case EXCLUSIVE_LOCK: return "EXCLUSIVE";
22451   }
22452   return "ERROR";
22453 }
22454 #endif
22455
22456 /*
22457 ** If we are currently in a different thread than the thread that the
22458 ** unixFile argument belongs to, then transfer ownership of the unixFile
22459 ** over to the current thread.
22460 **
22461 ** A unixFile is only owned by a thread on systems where one thread is
22462 ** unable to override locks created by a different thread.  RedHat9 is
22463 ** an example of such a system.
22464 **
22465 ** Ownership transfer is only allowed if the unixFile is currently unlocked.
22466 ** If the unixFile is locked and an ownership is wrong, then return
22467 ** SQLITE_MISUSE.  SQLITE_OK is returned if everything works.
22468 */
22469 #if SQLITE_THREADSAFE
22470 static int transferOwnership(unixFile *pFile){
22471   int rc;
22472   pthread_t hSelf;
22473   if( threadsOverrideEachOthersLocks ){
22474     /* Ownership transfers not needed on this system */
22475     return SQLITE_OK;
22476   }
22477   hSelf = pthread_self();
22478   if( pthread_equal(pFile->tid, hSelf) ){
22479     /* We are still in the same thread */
22480     OSTRACE1("No-transfer, same thread\n");
22481     return SQLITE_OK;
22482   }
22483   if( pFile->locktype!=NO_LOCK ){
22484     /* We cannot change ownership while we are holding a lock! */
22485     return SQLITE_MISUSE;
22486   }
22487   OSTRACE4("Transfer ownership of %d from %d to %d\n",
22488             pFile->h, pFile->tid, hSelf);
22489   pFile->tid = hSelf;
22490   if (pFile->pLock != NULL) {
22491     releaseLockInfo(pFile->pLock);
22492     rc = findLockInfo(pFile->h, &pFile->pLock, 0);
22493     OSTRACE5("LOCK    %d is now %s(%s,%d)\n", pFile->h,
22494            locktypeName(pFile->locktype),
22495            locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
22496     return rc;
22497   } else {
22498     return SQLITE_OK;
22499   }
22500 }
22501 #else
22502   /* On single-threaded builds, ownership transfer is a no-op */
22503 # define transferOwnership(X) SQLITE_OK
22504 #endif
22505
22506 /*
22507 ** Seek to the offset passed as the second argument, then read cnt 
22508 ** bytes into pBuf. Return the number of bytes actually read.
22509 **
22510 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
22511 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
22512 ** one system to another.  Since SQLite does not define USE_PREAD
22513 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
22514 ** See tickets #2741 and #2681.
22515 */
22516 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
22517   int got;
22518   i64 newOffset;
22519   TIMER_START;
22520 #if defined(USE_PREAD)
22521   got = pread(id->h, pBuf, cnt, offset);
22522   SimulateIOError( got = -1 );
22523 #elif defined(USE_PREAD64)
22524   got = pread64(id->h, pBuf, cnt, offset);
22525   SimulateIOError( got = -1 );
22526 #else
22527   newOffset = lseek(id->h, offset, SEEK_SET);
22528   SimulateIOError( newOffset-- );
22529   if( newOffset!=offset ){
22530     return -1;
22531   }
22532   got = read(id->h, pBuf, cnt);
22533 #endif
22534   TIMER_END;
22535   OSTRACE5("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
22536   return got;
22537 }
22538
22539 /*
22540 ** Read data from a file into a buffer.  Return SQLITE_OK if all
22541 ** bytes were read successfully and SQLITE_IOERR if anything goes
22542 ** wrong.
22543 */
22544 static int unixRead(
22545   sqlite3_file *id, 
22546   void *pBuf, 
22547   int amt,
22548   sqlite3_int64 offset
22549 ){
22550   int got;
22551   assert( id );
22552   got = seekAndRead((unixFile*)id, offset, pBuf, amt);
22553   if( got==amt ){
22554     return SQLITE_OK;
22555   }else if( got<0 ){
22556     return SQLITE_IOERR_READ;
22557   }else{
22558     memset(&((char*)pBuf)[got], 0, amt-got);
22559     return SQLITE_IOERR_SHORT_READ;
22560   }
22561 }
22562
22563 /*
22564 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
22565 ** Return the number of bytes actually read.  Update the offset.
22566 */
22567 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
22568   int got;
22569   i64 newOffset;
22570   TIMER_START;
22571 #if defined(USE_PREAD)
22572   got = pwrite(id->h, pBuf, cnt, offset);
22573 #elif defined(USE_PREAD64)
22574   got = pwrite64(id->h, pBuf, cnt, offset);
22575 #else
22576   newOffset = lseek(id->h, offset, SEEK_SET);
22577   if( newOffset!=offset ){
22578     return -1;
22579   }
22580   got = write(id->h, pBuf, cnt);
22581 #endif
22582   TIMER_END;
22583   OSTRACE5("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
22584   return got;
22585 }
22586
22587
22588 /*
22589 ** Write data from a buffer into a file.  Return SQLITE_OK on success
22590 ** or some other error code on failure.
22591 */
22592 static int unixWrite(
22593   sqlite3_file *id, 
22594   const void *pBuf, 
22595   int amt,
22596   sqlite3_int64 offset 
22597 ){
22598   int wrote = 0;
22599   assert( id );
22600   assert( amt>0 );
22601   while( amt>0 && (wrote = seekAndWrite((unixFile*)id, offset, pBuf, amt))>0 ){
22602     amt -= wrote;
22603     offset += wrote;
22604     pBuf = &((char*)pBuf)[wrote];
22605   }
22606   SimulateIOError(( wrote=(-1), amt=1 ));
22607   SimulateDiskfullError(( wrote=0, amt=1 ));
22608   if( amt>0 ){
22609     if( wrote<0 ){
22610       return SQLITE_IOERR_WRITE;
22611     }else{
22612       return SQLITE_FULL;
22613     }
22614   }
22615   return SQLITE_OK;
22616 }
22617
22618 #ifdef SQLITE_TEST
22619 /*
22620 ** Count the number of fullsyncs and normal syncs.  This is used to test
22621 ** that syncs and fullsyncs are occuring at the right times.
22622 */
22623 SQLITE_API int sqlite3_sync_count = 0;
22624 SQLITE_API int sqlite3_fullsync_count = 0;
22625 #endif
22626
22627 /*
22628 ** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
22629 ** Otherwise use fsync() in its place.
22630 */
22631 #ifndef HAVE_FDATASYNC
22632 # define fdatasync fsync
22633 #endif
22634
22635 /*
22636 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
22637 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
22638 ** only available on Mac OS X.  But that could change.
22639 */
22640 #ifdef F_FULLFSYNC
22641 # define HAVE_FULLFSYNC 1
22642 #else
22643 # define HAVE_FULLFSYNC 0
22644 #endif
22645
22646
22647 /*
22648 ** The fsync() system call does not work as advertised on many
22649 ** unix systems.  The following procedure is an attempt to make
22650 ** it work better.
22651 **
22652 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
22653 ** for testing when we want to run through the test suite quickly.
22654 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
22655 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
22656 ** or power failure will likely corrupt the database file.
22657 */
22658 static int full_fsync(int fd, int fullSync, int dataOnly){
22659   int rc;
22660
22661   /* Record the number of times that we do a normal fsync() and 
22662   ** FULLSYNC.  This is used during testing to verify that this procedure
22663   ** gets called with the correct arguments.
22664   */
22665 #ifdef SQLITE_TEST
22666   if( fullSync ) sqlite3_fullsync_count++;
22667   sqlite3_sync_count++;
22668 #endif
22669
22670   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
22671   ** no-op
22672   */
22673 #ifdef SQLITE_NO_SYNC
22674   rc = SQLITE_OK;
22675 #else
22676
22677 #if HAVE_FULLFSYNC
22678   if( fullSync ){
22679     rc = fcntl(fd, F_FULLFSYNC, 0);
22680   }else{
22681     rc = 1;
22682   }
22683   /* If the FULLFSYNC failed, fall back to attempting an fsync().
22684    * It shouldn't be possible for fullfsync to fail on the local 
22685    * file system (on OSX), so failure indicates that FULLFSYNC
22686    * isn't supported for this file system. So, attempt an fsync 
22687    * and (for now) ignore the overhead of a superfluous fcntl call.  
22688    * It'd be better to detect fullfsync support once and avoid 
22689    * the fcntl call every time sync is called.
22690    */
22691   if( rc ) rc = fsync(fd);
22692
22693 #else 
22694   if( dataOnly ){
22695     rc = fdatasync(fd);
22696   }else{
22697     rc = fsync(fd);
22698   }
22699 #endif /* HAVE_FULLFSYNC */
22700 #endif /* defined(SQLITE_NO_SYNC) */
22701
22702   return rc;
22703 }
22704
22705 /*
22706 ** Make sure all writes to a particular file are committed to disk.
22707 **
22708 ** If dataOnly==0 then both the file itself and its metadata (file
22709 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
22710 ** file data is synced.
22711 **
22712 ** Under Unix, also make sure that the directory entry for the file
22713 ** has been created by fsync-ing the directory that contains the file.
22714 ** If we do not do this and we encounter a power failure, the directory
22715 ** entry for the journal might not exist after we reboot.  The next
22716 ** SQLite to access the file will not know that the journal exists (because
22717 ** the directory entry for the journal was never created) and the transaction
22718 ** will not roll back - possibly leading to database corruption.
22719 */
22720 static int unixSync(sqlite3_file *id, int flags){
22721   int rc;
22722   unixFile *pFile = (unixFile*)id;
22723
22724   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
22725   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
22726
22727   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
22728   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
22729       || (flags&0x0F)==SQLITE_SYNC_FULL
22730   );
22731
22732   assert( pFile );
22733   OSTRACE2("SYNC    %-3d\n", pFile->h);
22734   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
22735   SimulateIOError( rc=1 );
22736   if( rc ){
22737     return SQLITE_IOERR_FSYNC;
22738   }
22739   if( pFile->dirfd>=0 ){
22740     OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
22741             HAVE_FULLFSYNC, isFullsync);
22742 #ifndef SQLITE_DISABLE_DIRSYNC
22743     /* The directory sync is only attempted if full_fsync is
22744     ** turned off or unavailable.  If a full_fsync occurred above,
22745     ** then the directory sync is superfluous.
22746     */
22747     if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
22748        /*
22749        ** We have received multiple reports of fsync() returning
22750        ** errors when applied to directories on certain file systems.
22751        ** A failed directory sync is not a big deal.  So it seems
22752        ** better to ignore the error.  Ticket #1657
22753        */
22754        /* return SQLITE_IOERR; */
22755     }
22756 #endif
22757     close(pFile->dirfd);  /* Only need to sync once, so close the directory */
22758     pFile->dirfd = -1;    /* when we are done. */
22759   }
22760   return SQLITE_OK;
22761 }
22762
22763 /*
22764 ** Truncate an open file to a specified size
22765 */
22766 static int unixTruncate(sqlite3_file *id, i64 nByte){
22767   int rc;
22768   assert( id );
22769   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
22770   rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
22771   if( rc ){
22772     return SQLITE_IOERR_TRUNCATE;
22773   }else{
22774     return SQLITE_OK;
22775   }
22776 }
22777
22778 /*
22779 ** Determine the current size of a file in bytes
22780 */
22781 static int unixFileSize(sqlite3_file *id, i64 *pSize){
22782   int rc;
22783   struct stat buf;
22784   assert( id );
22785   rc = fstat(((unixFile*)id)->h, &buf);
22786   SimulateIOError( rc=1 );
22787   if( rc!=0 ){
22788     return SQLITE_IOERR_FSTAT;
22789   }
22790   *pSize = buf.st_size;
22791
22792   /* When opening a zero-size database, the findLockInfo() procedure
22793   ** writes a single byte into that file in order to work around a bug
22794   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
22795   ** layers, we need to report this file size as zero even though it is
22796   ** really 1.   Ticket #3260.
22797   */
22798   if( *pSize==1 ) *pSize = 0;
22799
22800
22801   return SQLITE_OK;
22802 }
22803
22804 /*
22805 ** This routine translates a standard POSIX errno code into something
22806 ** useful to the clients of the sqlite3 functions.  Specifically, it is
22807 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
22808 ** and a variety of "please close the file descriptor NOW" errors into 
22809 ** SQLITE_IOERR
22810 ** 
22811 ** Errors during initialization of locks, or file system support for locks,
22812 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
22813 */
22814 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
22815   switch (posixError) {
22816   case 0: 
22817     return SQLITE_OK;
22818     
22819   case EAGAIN:
22820   case ETIMEDOUT:
22821   case EBUSY:
22822   case EINTR:
22823   case ENOLCK:  
22824     /* random NFS retry error, unless during file system support 
22825      * introspection, in which it actually means what it says */
22826     return SQLITE_BUSY;
22827     
22828   case EACCES: 
22829     /* EACCES is like EAGAIN during locking operations, but not any other time*/
22830     if( (sqliteIOErr == SQLITE_IOERR_LOCK) || 
22831         (sqliteIOErr == SQLITE_IOERR_UNLOCK) || 
22832         (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
22833         (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
22834       return SQLITE_BUSY;
22835     }
22836     /* else fall through */
22837   case EPERM: 
22838     return SQLITE_PERM;
22839     
22840   case EDEADLK:
22841     return SQLITE_IOERR_BLOCKED;
22842     
22843 #if EOPNOTSUPP!=ENOTSUP
22844   case EOPNOTSUPP: 
22845     /* something went terribly awry, unless during file system support 
22846      * introspection, in which it actually means what it says */
22847 #endif
22848 #ifdef ENOTSUP
22849   case ENOTSUP: 
22850     /* invalid fd, unless during file system support introspection, in which 
22851      * it actually means what it says */
22852 #endif
22853   case EIO:
22854   case EBADF:
22855   case EINVAL:
22856   case ENOTCONN:
22857   case ENODEV:
22858   case ENXIO:
22859   case ENOENT:
22860   case ESTALE:
22861   case ENOSYS:
22862     /* these should force the client to close the file and reconnect */
22863     
22864   default: 
22865     return sqliteIOErr;
22866   }
22867 }
22868
22869 /*
22870 ** This routine checks if there is a RESERVED lock held on the specified
22871 ** file by this or any other process. If such a lock is held, set *pResOut
22872 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
22873 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
22874 */
22875 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
22876   int rc = SQLITE_OK;
22877   int reserved = 0;
22878   unixFile *pFile = (unixFile*)id;
22879
22880   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
22881
22882   assert( pFile );
22883   enterMutex(); /* Because pFile->pLock is shared across threads */
22884
22885   /* Check if a thread in this process holds such a lock */
22886   if( pFile->pLock->locktype>SHARED_LOCK ){
22887     reserved = 1;
22888   }
22889
22890   /* Otherwise see if some other process holds it.
22891   */
22892   if( !reserved ){
22893     struct flock lock;
22894     lock.l_whence = SEEK_SET;
22895     lock.l_start = RESERVED_BYTE;
22896     lock.l_len = 1;
22897     lock.l_type = F_WRLCK;
22898     if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
22899       int tErrno = errno;
22900       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
22901       pFile->lastErrno = tErrno;
22902     } else if( lock.l_type!=F_UNLCK ){
22903       reserved = 1;
22904     }
22905   }
22906   
22907   leaveMutex();
22908   OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
22909
22910   *pResOut = reserved;
22911   return rc;
22912 }
22913
22914 /*
22915 ** Lock the file with the lock specified by parameter locktype - one
22916 ** of the following:
22917 **
22918 **     (1) SHARED_LOCK
22919 **     (2) RESERVED_LOCK
22920 **     (3) PENDING_LOCK
22921 **     (4) EXCLUSIVE_LOCK
22922 **
22923 ** Sometimes when requesting one lock state, additional lock states
22924 ** are inserted in between.  The locking might fail on one of the later
22925 ** transitions leaving the lock state different from what it started but
22926 ** still short of its goal.  The following chart shows the allowed
22927 ** transitions and the inserted intermediate states:
22928 **
22929 **    UNLOCKED -> SHARED
22930 **    SHARED -> RESERVED
22931 **    SHARED -> (PENDING) -> EXCLUSIVE
22932 **    RESERVED -> (PENDING) -> EXCLUSIVE
22933 **    PENDING -> EXCLUSIVE
22934 **
22935 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
22936 ** routine to lower a locking level.
22937 */
22938 static int unixLock(sqlite3_file *id, int locktype){
22939   /* The following describes the implementation of the various locks and
22940   ** lock transitions in terms of the POSIX advisory shared and exclusive
22941   ** lock primitives (called read-locks and write-locks below, to avoid
22942   ** confusion with SQLite lock names). The algorithms are complicated
22943   ** slightly in order to be compatible with windows systems simultaneously
22944   ** accessing the same database file, in case that is ever required.
22945   **
22946   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
22947   ** byte', each single bytes at well known offsets, and the 'shared byte
22948   ** range', a range of 510 bytes at a well known offset.
22949   **
22950   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
22951   ** byte'.  If this is successful, a random byte from the 'shared byte
22952   ** range' is read-locked and the lock on the 'pending byte' released.
22953   **
22954   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
22955   ** A RESERVED lock is implemented by grabbing a write-lock on the
22956   ** 'reserved byte'. 
22957   **
22958   ** A process may only obtain a PENDING lock after it has obtained a
22959   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
22960   ** on the 'pending byte'. This ensures that no new SHARED locks can be
22961   ** obtained, but existing SHARED locks are allowed to persist. A process
22962   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
22963   ** This property is used by the algorithm for rolling back a journal file
22964   ** after a crash.
22965   **
22966   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
22967   ** implemented by obtaining a write-lock on the entire 'shared byte
22968   ** range'. Since all other locks require a read-lock on one of the bytes
22969   ** within this range, this ensures that no other locks are held on the
22970   ** database. 
22971   **
22972   ** The reason a single byte cannot be used instead of the 'shared byte
22973   ** range' is that some versions of windows do not support read-locks. By
22974   ** locking a random byte from a range, concurrent SHARED locks may exist
22975   ** even if the locking primitive used is always a write-lock.
22976   */
22977   int rc = SQLITE_OK;
22978   unixFile *pFile = (unixFile*)id;
22979   struct lockInfo *pLock = pFile->pLock;
22980   struct flock lock;
22981   int s;
22982
22983   assert( pFile );
22984   OSTRACE7("LOCK    %d %s was %s(%s,%d) pid=%d\n", pFile->h,
22985       locktypeName(locktype), locktypeName(pFile->locktype),
22986       locktypeName(pLock->locktype), pLock->cnt , getpid());
22987
22988   /* If there is already a lock of this type or more restrictive on the
22989   ** unixFile, do nothing. Don't use the end_lock: exit path, as
22990   ** enterMutex() hasn't been called yet.
22991   */
22992   if( pFile->locktype>=locktype ){
22993     OSTRACE3("LOCK    %d %s ok (already held)\n", pFile->h,
22994             locktypeName(locktype));
22995     return SQLITE_OK;
22996   }
22997
22998   /* Make sure the locking sequence is correct
22999   */
23000   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
23001   assert( locktype!=PENDING_LOCK );
23002   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
23003
23004   /* This mutex is needed because pFile->pLock is shared across threads
23005   */
23006   enterMutex();
23007
23008   /* Make sure the current thread owns the pFile.
23009   */
23010   rc = transferOwnership(pFile);
23011   if( rc!=SQLITE_OK ){
23012     leaveMutex();
23013     return rc;
23014   }
23015   pLock = pFile->pLock;
23016
23017   /* If some thread using this PID has a lock via a different unixFile*
23018   ** handle that precludes the requested lock, return BUSY.
23019   */
23020   if( (pFile->locktype!=pLock->locktype && 
23021           (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
23022   ){
23023     rc = SQLITE_BUSY;
23024     goto end_lock;
23025   }
23026
23027   /* If a SHARED lock is requested, and some thread using this PID already
23028   ** has a SHARED or RESERVED lock, then increment reference counts and
23029   ** return SQLITE_OK.
23030   */
23031   if( locktype==SHARED_LOCK && 
23032       (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
23033     assert( locktype==SHARED_LOCK );
23034     assert( pFile->locktype==0 );
23035     assert( pLock->cnt>0 );
23036     pFile->locktype = SHARED_LOCK;
23037     pLock->cnt++;
23038     pFile->pOpen->nLock++;
23039     goto end_lock;
23040   }
23041
23042   lock.l_len = 1L;
23043
23044   lock.l_whence = SEEK_SET;
23045
23046   /* A PENDING lock is needed before acquiring a SHARED lock and before
23047   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
23048   ** be released.
23049   */
23050   if( locktype==SHARED_LOCK 
23051       || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
23052   ){
23053     lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
23054     lock.l_start = PENDING_BYTE;
23055     s = fcntl(pFile->h, F_SETLK, &lock);
23056     if( s==(-1) ){
23057       int tErrno = errno;
23058       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23059       if( IS_LOCK_ERROR(rc) ){
23060         pFile->lastErrno = tErrno;
23061       }
23062       goto end_lock;
23063     }
23064   }
23065
23066
23067   /* If control gets to this point, then actually go ahead and make
23068   ** operating system calls for the specified lock.
23069   */
23070   if( locktype==SHARED_LOCK ){
23071     int tErrno = 0;
23072     assert( pLock->cnt==0 );
23073     assert( pLock->locktype==0 );
23074
23075     /* Now get the read-lock */
23076     lock.l_start = SHARED_FIRST;
23077     lock.l_len = SHARED_SIZE;
23078     if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
23079       tErrno = errno;
23080     }
23081     /* Drop the temporary PENDING lock */
23082     lock.l_start = PENDING_BYTE;
23083     lock.l_len = 1L;
23084     lock.l_type = F_UNLCK;
23085     if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
23086       if( s != -1 ){
23087         /* This could happen with a network mount */
23088         tErrno = errno; 
23089         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); 
23090         if( IS_LOCK_ERROR(rc) ){
23091           pFile->lastErrno = tErrno;
23092         }
23093         goto end_lock;
23094       }
23095     }
23096     if( s==(-1) ){
23097       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23098       if( IS_LOCK_ERROR(rc) ){
23099         pFile->lastErrno = tErrno;
23100       }
23101     }else{
23102       pFile->locktype = SHARED_LOCK;
23103       pFile->pOpen->nLock++;
23104       pLock->cnt = 1;
23105     }
23106   }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
23107     /* We are trying for an exclusive lock but another thread in this
23108     ** same process is still holding a shared lock. */
23109     rc = SQLITE_BUSY;
23110   }else{
23111     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
23112     ** assumed that there is a SHARED or greater lock on the file
23113     ** already.
23114     */
23115     assert( 0!=pFile->locktype );
23116     lock.l_type = F_WRLCK;
23117     switch( locktype ){
23118       case RESERVED_LOCK:
23119         lock.l_start = RESERVED_BYTE;
23120         break;
23121       case EXCLUSIVE_LOCK:
23122         lock.l_start = SHARED_FIRST;
23123         lock.l_len = SHARED_SIZE;
23124         break;
23125       default:
23126         assert(0);
23127     }
23128     s = fcntl(pFile->h, F_SETLK, &lock);
23129     if( s==(-1) ){
23130       int tErrno = errno;
23131       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23132       if( IS_LOCK_ERROR(rc) ){
23133         pFile->lastErrno = tErrno;
23134       }
23135     }
23136   }
23137   
23138   if( rc==SQLITE_OK ){
23139     pFile->locktype = locktype;
23140     pLock->locktype = locktype;
23141   }else if( locktype==EXCLUSIVE_LOCK ){
23142     pFile->locktype = PENDING_LOCK;
23143     pLock->locktype = PENDING_LOCK;
23144   }
23145
23146 end_lock:
23147   leaveMutex();
23148   OSTRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
23149       rc==SQLITE_OK ? "ok" : "failed");
23150   return rc;
23151 }
23152
23153 /*
23154 ** Lower the locking level on file descriptor pFile to locktype.  locktype
23155 ** must be either NO_LOCK or SHARED_LOCK.
23156 **
23157 ** If the locking level of the file descriptor is already at or below
23158 ** the requested locking level, this routine is a no-op.
23159 */
23160 static int unixUnlock(sqlite3_file *id, int locktype){
23161   struct lockInfo *pLock;
23162   struct flock lock;
23163   int rc = SQLITE_OK;
23164   unixFile *pFile = (unixFile*)id;
23165   int h;
23166
23167   assert( pFile );
23168   OSTRACE7("UNLOCK  %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
23169       pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
23170
23171   assert( locktype<=SHARED_LOCK );
23172   if( pFile->locktype<=locktype ){
23173     return SQLITE_OK;
23174   }
23175   if( CHECK_THREADID(pFile) ){
23176     return SQLITE_MISUSE;
23177   }
23178   enterMutex();
23179   h = pFile->h;
23180   pLock = pFile->pLock;
23181   assert( pLock->cnt!=0 );
23182   if( pFile->locktype>SHARED_LOCK ){
23183     assert( pLock->locktype==pFile->locktype );
23184     SimulateIOErrorBenign(1);
23185     SimulateIOError( h=(-1) )
23186     SimulateIOErrorBenign(0);
23187     if( locktype==SHARED_LOCK ){
23188       lock.l_type = F_RDLCK;
23189       lock.l_whence = SEEK_SET;
23190       lock.l_start = SHARED_FIRST;
23191       lock.l_len = SHARED_SIZE;
23192       if( fcntl(h, F_SETLK, &lock)==(-1) ){
23193         int tErrno = errno;
23194         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
23195         if( IS_LOCK_ERROR(rc) ){
23196           pFile->lastErrno = tErrno;
23197         }
23198                                 goto end_unlock;
23199       }
23200     }
23201     lock.l_type = F_UNLCK;
23202     lock.l_whence = SEEK_SET;
23203     lock.l_start = PENDING_BYTE;
23204     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
23205     if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23206       pLock->locktype = SHARED_LOCK;
23207     }else{
23208       int tErrno = errno;
23209       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23210       if( IS_LOCK_ERROR(rc) ){
23211         pFile->lastErrno = tErrno;
23212       }
23213                         goto end_unlock;
23214     }
23215   }
23216   if( locktype==NO_LOCK ){
23217     struct openCnt *pOpen;
23218
23219     /* Decrement the shared lock counter.  Release the lock using an
23220     ** OS call only when all threads in this same process have released
23221     ** the lock.
23222     */
23223     pLock->cnt--;
23224     if( pLock->cnt==0 ){
23225       lock.l_type = F_UNLCK;
23226       lock.l_whence = SEEK_SET;
23227       lock.l_start = lock.l_len = 0L;
23228       SimulateIOErrorBenign(1);
23229       SimulateIOError( h=(-1) )
23230       SimulateIOErrorBenign(0);
23231       if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23232         pLock->locktype = NO_LOCK;
23233       }else{
23234         int tErrno = errno;
23235         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23236         if( IS_LOCK_ERROR(rc) ){
23237           pFile->lastErrno = tErrno;
23238         }
23239         pLock->cnt = 1;
23240                                 goto end_unlock;
23241       }
23242     }
23243
23244     /* Decrement the count of locks against this same file.  When the
23245     ** count reaches zero, close any other file descriptors whose close
23246     ** was deferred because of outstanding locks.
23247     */
23248     if( rc==SQLITE_OK ){
23249       pOpen = pFile->pOpen;
23250       pOpen->nLock--;
23251       assert( pOpen->nLock>=0 );
23252       if( pOpen->nLock==0 && pOpen->nPending>0 ){
23253         int i;
23254         for(i=0; i<pOpen->nPending; i++){
23255           close(pOpen->aPending[i]);
23256         }
23257         sqlite3_free(pOpen->aPending);
23258         pOpen->nPending = 0;
23259         pOpen->aPending = 0;
23260       }
23261     }
23262   }
23263         
23264 end_unlock:
23265   leaveMutex();
23266   if( rc==SQLITE_OK ) pFile->locktype = locktype;
23267   return rc;
23268 }
23269
23270 /*
23271 ** This function performs the parts of the "close file" operation 
23272 ** common to all locking schemes. It closes the directory and file
23273 ** handles, if they are valid, and sets all fields of the unixFile
23274 ** structure to 0.
23275 */
23276 static int closeUnixFile(sqlite3_file *id){
23277   unixFile *pFile = (unixFile*)id;
23278   if( pFile ){
23279     if( pFile->dirfd>=0 ){
23280       close(pFile->dirfd);
23281     }
23282     if( pFile->h>=0 ){
23283       close(pFile->h);
23284     }
23285     OSTRACE2("CLOSE   %-3d\n", pFile->h);
23286     OpenCounter(-1);
23287     memset(pFile, 0, sizeof(unixFile));
23288   }
23289   return SQLITE_OK;
23290 }
23291
23292 /*
23293 ** Close a file.
23294 */
23295 static int unixClose(sqlite3_file *id){
23296   if( id ){
23297     unixFile *pFile = (unixFile *)id;
23298     unixUnlock(id, NO_LOCK);
23299     enterMutex();
23300     if( pFile->pOpen && pFile->pOpen->nLock ){
23301       /* If there are outstanding locks, do not actually close the file just
23302       ** yet because that would clear those locks.  Instead, add the file
23303       ** descriptor to pOpen->aPending.  It will be automatically closed when
23304       ** the last lock is cleared.
23305       */
23306       int *aNew;
23307       struct openCnt *pOpen = pFile->pOpen;
23308       aNew = sqlite3_realloc(pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
23309       if( aNew==0 ){
23310         /* If a malloc fails, just leak the file descriptor */
23311       }else{
23312         pOpen->aPending = aNew;
23313         pOpen->aPending[pOpen->nPending] = pFile->h;
23314         pOpen->nPending++;
23315         pFile->h = -1;
23316       }
23317     }
23318     releaseLockInfo(pFile->pLock);
23319     releaseOpenCnt(pFile->pOpen);
23320     closeUnixFile(id);
23321     leaveMutex();
23322   }
23323   return SQLITE_OK;
23324 }
23325
23326
23327 #ifdef SQLITE_ENABLE_LOCKING_STYLE
23328 #pragma mark AFP Support
23329
23330 /*
23331  ** The afpLockingContext structure contains all afp lock specific state
23332  */
23333 typedef struct afpLockingContext afpLockingContext;
23334 struct afpLockingContext {
23335   unsigned long long sharedLockByte;
23336   const char *filePath;
23337 };
23338
23339 struct ByteRangeLockPB2
23340 {
23341   unsigned long long offset;        /* offset to first byte to lock */
23342   unsigned long long length;        /* nbr of bytes to lock */
23343   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
23344   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
23345   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
23346   int fd;                           /* file desc to assoc this lock with */
23347 };
23348
23349 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
23350
23351 /* 
23352  ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
23353  */
23354 static int _AFPFSSetLock(
23355   const char *path, 
23356   unixFile *pFile, 
23357   unsigned long long offset, 
23358   unsigned long long length, 
23359   int setLockFlag
23360 ){
23361   struct ByteRangeLockPB2       pb;
23362   int                     err;
23363   
23364   pb.unLockFlag = setLockFlag ? 0 : 1;
23365   pb.startEndFlag = 0;
23366   pb.offset = offset;
23367   pb.length = length; 
23368   pb.fd = pFile->h;
23369   OSTRACE5("AFPLOCK setting lock %s for %d in range %llx:%llx\n", 
23370     (setLockFlag?"ON":"OFF"), pFile->h, offset, length);
23371   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
23372   if ( err==-1 ) {
23373     int rc;
23374     int tErrno = errno;
23375     OSTRACE4("AFPLOCK failed to fsctl() '%s' %d %s\n", path, tErrno, strerror(tErrno));
23376     rc = sqliteErrorFromPosixError(tErrno, setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK); /* error */
23377     if( IS_LOCK_ERROR(rc) ){
23378       pFile->lastErrno = tErrno;
23379     }
23380     return rc;
23381   } else {
23382     return SQLITE_OK;
23383   }
23384 }
23385
23386 /* AFP-style reserved lock checking following the behavior of 
23387 ** unixCheckReservedLock, see the unixCheckReservedLock function comments */
23388 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
23389   int rc = SQLITE_OK;
23390   int reserved = 0;
23391   unixFile *pFile = (unixFile*)id;
23392   
23393   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23394   
23395   assert( pFile );
23396   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
23397   
23398   /* Check if a thread in this process holds such a lock */
23399   if( pFile->locktype>SHARED_LOCK ){
23400     reserved = 1;
23401   }
23402   
23403   /* Otherwise see if some other process holds it.
23404    */
23405   if( !reserved ){
23406     /* lock the RESERVED byte */
23407     int lrc = _AFPFSSetLock(context->filePath, pFile, RESERVED_BYTE, 1,1);  
23408     if( SQLITE_OK==lrc ){
23409       /* if we succeeded in taking the reserved lock, unlock it to restore
23410       ** the original state */
23411       lrc = _AFPFSSetLock(context->filePath, pFile, RESERVED_BYTE, 1, 0);
23412     } else {
23413       /* if we failed to get the lock then someone else must have it */
23414       reserved = 1;
23415     }
23416     if( IS_LOCK_ERROR(lrc) ){
23417       rc=lrc;
23418     }
23419   }
23420   
23421   OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
23422   
23423   *pResOut = reserved;
23424   return rc;
23425 }
23426
23427 /* AFP-style locking following the behavior of unixLock, see the unixLock 
23428 ** function comments for details of lock management. */
23429 static int afpLock(sqlite3_file *id, int locktype){
23430   int rc = SQLITE_OK;
23431   unixFile *pFile = (unixFile*)id;
23432   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
23433   
23434   assert( pFile );
23435   OSTRACE5("LOCK    %d %s was %s pid=%d\n", pFile->h,
23436          locktypeName(locktype), locktypeName(pFile->locktype), getpid());
23437
23438   /* If there is already a lock of this type or more restrictive on the
23439   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
23440   ** enterMutex() hasn't been called yet.
23441   */
23442   if( pFile->locktype>=locktype ){
23443     OSTRACE3("LOCK    %d %s ok (already held)\n", pFile->h,
23444            locktypeName(locktype));
23445     return SQLITE_OK;
23446   }
23447
23448   /* Make sure the locking sequence is correct
23449   */
23450   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
23451   assert( locktype!=PENDING_LOCK );
23452   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
23453   
23454   /* This mutex is needed because pFile->pLock is shared across threads
23455   */
23456   enterMutex();
23457
23458   /* Make sure the current thread owns the pFile.
23459   */
23460   rc = transferOwnership(pFile);
23461   if( rc!=SQLITE_OK ){
23462     leaveMutex();
23463     return rc;
23464   }
23465     
23466   /* A PENDING lock is needed before acquiring a SHARED lock and before
23467   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
23468   ** be released.
23469   */
23470   if( locktype==SHARED_LOCK 
23471       || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
23472   ){
23473     int failed;
23474     failed = _AFPFSSetLock(context->filePath, pFile, PENDING_BYTE, 1, 1);
23475     if (failed) {
23476       rc = failed;
23477       goto afp_end_lock;
23478     }
23479   }
23480   
23481   /* If control gets to this point, then actually go ahead and make
23482   ** operating system calls for the specified lock.
23483   */
23484   if( locktype==SHARED_LOCK ){
23485     int lk, lrc1, lrc2, lrc1Errno;
23486     
23487     /* Now get the read-lock SHARED_LOCK */
23488     /* note that the quality of the randomness doesn't matter that much */
23489     lk = random(); 
23490     context->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
23491     lrc1 = _AFPFSSetLock(context->filePath, pFile, 
23492           SHARED_FIRST+context->sharedLockByte, 1, 1);
23493     if( IS_LOCK_ERROR(lrc1) ){
23494       lrc1Errno = pFile->lastErrno;
23495     }
23496     /* Drop the temporary PENDING lock */
23497     lrc2 = _AFPFSSetLock(context->filePath, pFile, PENDING_BYTE, 1, 0);
23498     
23499     if( IS_LOCK_ERROR(lrc1) ) {
23500       pFile->lastErrno = lrc1Errno;
23501       rc = lrc1;
23502       goto afp_end_lock;
23503     } else if( IS_LOCK_ERROR(lrc2) ){
23504       rc = lrc2;
23505       goto afp_end_lock;
23506     } else if( lrc1 != SQLITE_OK ) {
23507       rc = lrc1;
23508     } else {
23509       pFile->locktype = SHARED_LOCK;
23510     }
23511   }else{
23512     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
23513     ** assumed that there is a SHARED or greater lock on the file
23514     ** already.
23515     */
23516     int failed = 0;
23517     assert( 0!=pFile->locktype );
23518     if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
23519         /* Acquire a RESERVED lock */
23520         failed = _AFPFSSetLock(context->filePath, pFile, RESERVED_BYTE, 1,1);
23521     }
23522     if (!failed && locktype == EXCLUSIVE_LOCK) {
23523       /* Acquire an EXCLUSIVE lock */
23524         
23525       /* Remove the shared lock before trying the range.  we'll need to 
23526       ** reestablish the shared lock if we can't get the  afpUnlock
23527       */
23528       if (!(failed = _AFPFSSetLock(context->filePath, pFile, SHARED_FIRST +
23529                          context->sharedLockByte, 1, 0))) {
23530         /* now attemmpt to get the exclusive lock range */
23531         failed = _AFPFSSetLock(context->filePath, pFile, SHARED_FIRST, 
23532                                SHARED_SIZE, 1);
23533         if (failed && (failed = _AFPFSSetLock(context->filePath, pFile, 
23534                        SHARED_FIRST + context->sharedLockByte, 1, 1))) {
23535           rc = failed;
23536         }
23537       } else {
23538         rc = failed; 
23539       }
23540     }
23541     if( failed ){
23542       rc = failed;
23543     }
23544   }
23545   
23546   if( rc==SQLITE_OK ){
23547     pFile->locktype = locktype;
23548   }else if( locktype==EXCLUSIVE_LOCK ){
23549     pFile->locktype = PENDING_LOCK;
23550   }
23551   
23552 afp_end_lock:
23553   leaveMutex();
23554   OSTRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
23555          rc==SQLITE_OK ? "ok" : "failed");
23556   return rc;
23557 }
23558
23559 /*
23560 ** Lower the locking level on file descriptor pFile to locktype.  locktype
23561 ** must be either NO_LOCK or SHARED_LOCK.
23562 **
23563 ** If the locking level of the file descriptor is already at or below
23564 ** the requested locking level, this routine is a no-op.
23565 */
23566 static int afpUnlock(sqlite3_file *id, int locktype) {
23567   int rc = SQLITE_OK;
23568   unixFile *pFile = (unixFile*)id;
23569   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
23570
23571   assert( pFile );
23572   OSTRACE5("UNLOCK  %d %d was %d pid=%d\n", pFile->h, locktype,
23573          pFile->locktype, getpid());
23574
23575   assert( locktype<=SHARED_LOCK );
23576   if( pFile->locktype<=locktype ){
23577     return SQLITE_OK;
23578   }
23579   if( CHECK_THREADID(pFile) ){
23580     return SQLITE_MISUSE;
23581   }
23582   enterMutex();
23583   int failed = SQLITE_OK;
23584   if( pFile->locktype>SHARED_LOCK ){
23585     if( locktype==SHARED_LOCK ){
23586
23587       /* unlock the exclusive range - then re-establish the shared lock */
23588       if (pFile->locktype==EXCLUSIVE_LOCK) {
23589         failed = _AFPFSSetLock(context->filePath, pFile, SHARED_FIRST, 
23590                                  SHARED_SIZE, 0);
23591         if (!failed) {
23592           /* successfully removed the exclusive lock */
23593           if ((failed = _AFPFSSetLock(context->filePath, pFile, SHARED_FIRST+
23594                             context->sharedLockByte, 1, 1))) {
23595             /* failed to re-establish our shared lock */
23596             rc = failed;
23597           }
23598         } else {
23599           rc = failed;
23600         } 
23601       }
23602     }
23603     if (rc == SQLITE_OK && pFile->locktype>=PENDING_LOCK) {
23604       if ((failed = _AFPFSSetLock(context->filePath, pFile, 
23605                                   PENDING_BYTE, 1, 0))){
23606         /* failed to release the pending lock */
23607         rc = failed; 
23608       }
23609     } 
23610     if (rc == SQLITE_OK && pFile->locktype>=RESERVED_LOCK) {
23611       if ((failed = _AFPFSSetLock(context->filePath, pFile, 
23612                                   RESERVED_BYTE, 1, 0))) {
23613         /* failed to release the reserved lock */
23614         rc = failed;  
23615       }
23616     } 
23617   }
23618   if( locktype==NO_LOCK ){
23619     int failed = _AFPFSSetLock(context->filePath, pFile, 
23620                                SHARED_FIRST + context->sharedLockByte, 1, 0);
23621     if (failed) {
23622       rc = failed;  
23623     }
23624   }
23625   if (rc == SQLITE_OK)
23626     pFile->locktype = locktype;
23627   leaveMutex();
23628   return rc;
23629 }
23630
23631 /*
23632 ** Close a file & cleanup AFP specific locking context 
23633 */
23634 static int afpClose(sqlite3_file *id) {
23635   if( id ){
23636     unixFile *pFile = (unixFile*)id;
23637     afpUnlock(id, NO_LOCK);
23638     sqlite3_free(pFile->lockingContext);
23639   }
23640   return closeUnixFile(id);
23641 }
23642
23643
23644 #pragma mark flock() style locking
23645
23646 /*
23647 ** The flockLockingContext is not used
23648 */
23649 typedef void flockLockingContext;
23650
23651 /* flock-style reserved lock checking following the behavior of 
23652  ** unixCheckReservedLock, see the unixCheckReservedLock function comments */
23653 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
23654   int rc = SQLITE_OK;
23655   int reserved = 0;
23656   unixFile *pFile = (unixFile*)id;
23657   
23658   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23659   
23660   assert( pFile );
23661   
23662   /* Check if a thread in this process holds such a lock */
23663   if( pFile->locktype>SHARED_LOCK ){
23664     reserved = 1;
23665   }
23666   
23667   /* Otherwise see if some other process holds it. */
23668   if( !reserved ){
23669     /* attempt to get the lock */
23670     int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
23671     if( !lrc ){
23672       /* got the lock, unlock it */
23673       lrc = flock(pFile->h, LOCK_UN);
23674       if ( lrc ) {
23675         int tErrno = errno;
23676         /* unlock failed with an error */
23677         lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); 
23678         if( IS_LOCK_ERROR(lrc) ){
23679           pFile->lastErrno = tErrno;
23680           rc = lrc;
23681         }
23682       }
23683     } else {
23684       int tErrno = errno;
23685       reserved = 1;
23686       /* someone else might have it reserved */
23687       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 
23688       if( IS_LOCK_ERROR(lrc) ){
23689         pFile->lastErrno = tErrno;
23690         rc = lrc;
23691       }
23692     }
23693   }
23694   OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
23695
23696   *pResOut = reserved;
23697   return rc;
23698 }
23699
23700 static int flockLock(sqlite3_file *id, int locktype) {
23701   int rc = SQLITE_OK;
23702   unixFile *pFile = (unixFile*)id;
23703
23704   assert( pFile );
23705
23706   /* if we already have a lock, it is exclusive.  
23707   ** Just adjust level and punt on outta here. */
23708   if (pFile->locktype > NO_LOCK) {
23709     pFile->locktype = locktype;
23710     return SQLITE_OK;
23711   }
23712   
23713   /* grab an exclusive lock */
23714   
23715   if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
23716     int tErrno = errno;
23717     /* didn't get, must be busy */
23718     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23719     if( IS_LOCK_ERROR(rc) ){
23720       pFile->lastErrno = tErrno;
23721     }
23722   } else {
23723     /* got it, set the type and return ok */
23724     pFile->locktype = locktype;
23725   }
23726   OSTRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
23727            rc==SQLITE_OK ? "ok" : "failed");
23728   return rc;
23729 }
23730
23731 static int flockUnlock(sqlite3_file *id, int locktype) {
23732   unixFile *pFile = (unixFile*)id;
23733   
23734   assert( pFile );
23735   OSTRACE5("UNLOCK  %d %d was %d pid=%d\n", pFile->h, locktype,
23736            pFile->locktype, getpid());
23737   assert( locktype<=SHARED_LOCK );
23738   
23739   /* no-op if possible */
23740   if( pFile->locktype==locktype ){
23741     return SQLITE_OK;
23742   }
23743   
23744   /* shared can just be set because we always have an exclusive */
23745   if (locktype==SHARED_LOCK) {
23746     pFile->locktype = locktype;
23747     return SQLITE_OK;
23748   }
23749   
23750   /* no, really, unlock. */
23751   int rc = flock(pFile->h, LOCK_UN);
23752   if (rc) {
23753     int r, tErrno = errno;
23754     r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23755     if( IS_LOCK_ERROR(r) ){
23756       pFile->lastErrno = tErrno;
23757     }
23758     return r;
23759   } else {
23760     pFile->locktype = NO_LOCK;
23761     return SQLITE_OK;
23762   }
23763 }
23764
23765 /*
23766 ** Close a file.
23767 */
23768 static int flockClose(sqlite3_file *id) {
23769   if( id ){
23770     flockUnlock(id, NO_LOCK);
23771   }
23772   return closeUnixFile(id);
23773 }
23774
23775 #pragma mark Old-School .lock file based locking
23776
23777 /* Dotlock-style reserved lock checking following the behavior of 
23778 ** unixCheckReservedLock, see the unixCheckReservedLock function comments */
23779 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
23780   int rc = SQLITE_OK;
23781   int reserved = 0;
23782   unixFile *pFile = (unixFile*)id;
23783
23784   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23785   
23786   assert( pFile );
23787
23788   /* Check if a thread in this process holds such a lock */
23789   if( pFile->locktype>SHARED_LOCK ){
23790     reserved = 1;
23791   }
23792   
23793   /* Otherwise see if some other process holds it. */
23794   if( !reserved ){
23795     char *zLockFile = (char *)pFile->lockingContext;
23796     struct stat statBuf;
23797     
23798     if( lstat(zLockFile, &statBuf)==0 ){
23799       /* file exists, someone else has the lock */
23800       reserved = 1;
23801     }else{
23802       /* file does not exist, we could have it if we want it */
23803                         int tErrno = errno;
23804       if( ENOENT != tErrno ){
23805         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
23806         pFile->lastErrno = tErrno;
23807       }
23808     }
23809   }
23810   OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
23811
23812   *pResOut = reserved;
23813   return rc;
23814 }
23815
23816 static int dotlockLock(sqlite3_file *id, int locktype) {
23817   unixFile *pFile = (unixFile*)id;
23818   int fd;
23819   char *zLockFile = (char *)pFile->lockingContext;
23820   int rc=SQLITE_OK;
23821
23822   /* if we already have a lock, it is exclusive.  
23823   ** Just adjust level and punt on outta here. */
23824   if (pFile->locktype > NO_LOCK) {
23825     pFile->locktype = locktype;
23826     
23827     /* Always update the timestamp on the old file */
23828     utimes(zLockFile, NULL);
23829     rc = SQLITE_OK;
23830     goto dotlock_end_lock;
23831   }
23832   
23833   /* check to see if lock file already exists */
23834   struct stat statBuf;
23835   if (lstat(zLockFile,&statBuf) == 0){
23836     rc = SQLITE_BUSY; /* it does, busy */
23837     goto dotlock_end_lock;
23838   }
23839   
23840   /* grab an exclusive lock */
23841   fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
23842   if( fd<0 ){
23843     /* failed to open/create the file, someone else may have stolen the lock */
23844     int tErrno = errno;
23845     if( EEXIST == tErrno ){
23846       rc = SQLITE_BUSY;
23847     } else {
23848       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23849       if( IS_LOCK_ERROR(rc) ){
23850         pFile->lastErrno = tErrno;
23851       }
23852     }
23853     goto dotlock_end_lock;
23854   } 
23855   close(fd);
23856   
23857   /* got it, set the type and return ok */
23858   pFile->locktype = locktype;
23859
23860  dotlock_end_lock:
23861   return rc;
23862 }
23863
23864 static int dotlockUnlock(sqlite3_file *id, int locktype) {
23865   unixFile *pFile = (unixFile*)id;
23866   char *zLockFile = (char *)pFile->lockingContext;
23867
23868   assert( pFile );
23869   OSTRACE5("UNLOCK  %d %d was %d pid=%d\n", pFile->h, locktype,
23870            pFile->locktype, getpid());
23871   assert( locktype<=SHARED_LOCK );
23872   
23873   /* no-op if possible */
23874   if( pFile->locktype==locktype ){
23875     return SQLITE_OK;
23876   }
23877   
23878   /* shared can just be set because we always have an exclusive */
23879   if (locktype==SHARED_LOCK) {
23880     pFile->locktype = locktype;
23881     return SQLITE_OK;
23882   }
23883   
23884   /* no, really, unlock. */
23885   if (unlink(zLockFile) ) {
23886     int rc, tErrno = errno;
23887     if( ENOENT != tErrno ){
23888       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23889     }
23890     if( IS_LOCK_ERROR(rc) ){
23891       pFile->lastErrno = tErrno;
23892     }
23893     return rc; 
23894   }
23895   pFile->locktype = NO_LOCK;
23896   return SQLITE_OK;
23897 }
23898
23899 /*
23900  ** Close a file.
23901  */
23902 static int dotlockClose(sqlite3_file *id) {
23903   if( id ){
23904     unixFile *pFile = (unixFile*)id;
23905     dotlockUnlock(id, NO_LOCK);
23906     sqlite3_free(pFile->lockingContext);
23907   }
23908   return closeUnixFile(id);
23909 }
23910
23911
23912 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
23913
23914 /*
23915 ** The nolockLockingContext is void
23916 */
23917 typedef void nolockLockingContext;
23918
23919 static int nolockCheckReservedLock(sqlite3_file *id, int *pResOut) {
23920   *pResOut = 0;
23921   return SQLITE_OK;
23922 }
23923
23924 static int nolockLock(sqlite3_file *id, int locktype) {
23925   return SQLITE_OK;
23926 }
23927
23928 static int nolockUnlock(sqlite3_file *id, int locktype) {
23929   return SQLITE_OK;
23930 }
23931
23932 /*
23933 ** Close a file.
23934 */
23935 static int nolockClose(sqlite3_file *id) {
23936   return closeUnixFile(id);
23937 }
23938
23939
23940 /*
23941 ** Information and control of an open file handle.
23942 */
23943 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
23944   switch( op ){
23945     case SQLITE_FCNTL_LOCKSTATE: {
23946       *(int*)pArg = ((unixFile*)id)->locktype;
23947       return SQLITE_OK;
23948     }
23949   }
23950   return SQLITE_ERROR;
23951 }
23952
23953 /*
23954 ** Return the sector size in bytes of the underlying block device for
23955 ** the specified file. This is almost always 512 bytes, but may be
23956 ** larger for some devices.
23957 **
23958 ** SQLite code assumes this function cannot fail. It also assumes that
23959 ** if two files are created in the same file-system directory (i.e.
23960 ** a database and its journal file) that the sector size will be the
23961 ** same for both.
23962 */
23963 static int unixSectorSize(sqlite3_file *id){
23964   return SQLITE_DEFAULT_SECTOR_SIZE;
23965 }
23966
23967 /*
23968 ** Return the device characteristics for the file. This is always 0.
23969 */
23970 static int unixDeviceCharacteristics(sqlite3_file *id){
23971   return 0;
23972 }
23973
23974 /*
23975 ** Initialize the contents of the unixFile structure pointed to by pId.
23976 **
23977 ** When locking extensions are enabled, the filepath and locking style 
23978 ** are needed to determine the unixFile pMethod to use for locking operations.
23979 ** The locking-style specific lockingContext data structure is created 
23980 ** and assigned here also.
23981 */
23982 static int fillInUnixFile(
23983   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
23984   int h,                  /* Open file descriptor of file being opened */
23985   int dirfd,              /* Directory file descriptor */
23986   sqlite3_file *pId,      /* Write to the unixFile structure here */
23987   const char *zFilename,  /* Name of the file being opened */
23988   int noLock              /* Omit locking if true */
23989 ){
23990   int eLockingStyle;
23991   unixFile *pNew = (unixFile *)pId;
23992   int rc = SQLITE_OK;
23993
23994   /* Macro to define the static contents of an sqlite3_io_methods 
23995   ** structure for a unix backend file. Different locking methods
23996   ** require different functions for the xClose, xLock, xUnlock and
23997   ** xCheckReservedLock methods.
23998   */
23999   #define IOMETHODS(xClose, xLock, xUnlock, xCheckReservedLock) {    \
24000     1,                          /* iVersion */                           \
24001     xClose,                     /* xClose */                             \
24002     unixRead,                   /* xRead */                              \
24003     unixWrite,                  /* xWrite */                             \
24004     unixTruncate,               /* xTruncate */                          \
24005     unixSync,                   /* xSync */                              \
24006     unixFileSize,               /* xFileSize */                          \
24007     xLock,                      /* xLock */                              \
24008     xUnlock,                    /* xUnlock */                            \
24009     xCheckReservedLock,         /* xCheckReservedLock */                 \
24010     unixFileControl,            /* xFileControl */                       \
24011     unixSectorSize,             /* xSectorSize */                        \
24012     unixDeviceCharacteristics   /* xDeviceCapabilities */                \
24013   }
24014   static sqlite3_io_methods aIoMethod[] = {
24015     IOMETHODS(unixClose, unixLock, unixUnlock, unixCheckReservedLock) 
24016    ,IOMETHODS(nolockClose, nolockLock, nolockUnlock, nolockCheckReservedLock)
24017 #ifdef SQLITE_ENABLE_LOCKING_STYLE
24018    ,IOMETHODS(dotlockClose, dotlockLock, dotlockUnlock,dotlockCheckReservedLock)
24019    ,IOMETHODS(flockClose, flockLock, flockUnlock, flockCheckReservedLock)
24020    ,IOMETHODS(afpClose, afpLock, afpUnlock, afpCheckReservedLock)
24021 #endif
24022   };
24023   /* The order of the IOMETHODS macros above is important.  It must be the
24024   ** same order as the LOCKING_STYLE numbers
24025   */
24026   assert(LOCKING_STYLE_POSIX==1);
24027   assert(LOCKING_STYLE_NONE==2);
24028   assert(LOCKING_STYLE_DOTFILE==3);
24029   assert(LOCKING_STYLE_FLOCK==4);
24030   assert(LOCKING_STYLE_AFP==5);
24031
24032   assert( pNew->pLock==NULL );
24033   assert( pNew->pOpen==NULL );
24034
24035   OSTRACE3("OPEN    %-3d %s\n", h, zFilename);    
24036   pNew->h = h;
24037   pNew->dirfd = dirfd;
24038   SET_THREADID(pNew);
24039
24040   if( noLock ){
24041     eLockingStyle = LOCKING_STYLE_NONE;
24042   }else{
24043     eLockingStyle = detectLockingStyle(pVfs, zFilename, h);
24044   }
24045
24046   switch( eLockingStyle ){
24047
24048     case LOCKING_STYLE_POSIX: {
24049       enterMutex();
24050       rc = findLockInfo(h, &pNew->pLock, &pNew->pOpen);
24051       leaveMutex();
24052       break;
24053     }
24054
24055 #ifdef SQLITE_ENABLE_LOCKING_STYLE
24056     case LOCKING_STYLE_AFP: {
24057       /* AFP locking uses the file path so it needs to be included in
24058       ** the afpLockingContext.
24059       */
24060       afpLockingContext *pCtx;
24061       pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
24062       if( pCtx==0 ){
24063         rc = SQLITE_NOMEM;
24064       }else{
24065         /* NB: zFilename exists and remains valid until the file is closed
24066         ** according to requirement F11141.  So we do not need to make a
24067         ** copy of the filename. */
24068         pCtx->filePath = zFilename;
24069         srandomdev();
24070       }
24071       break;
24072     }
24073
24074     case LOCKING_STYLE_DOTFILE: {
24075       /* Dotfile locking uses the file path so it needs to be included in
24076       ** the dotlockLockingContext 
24077       */
24078       char *zLockFile;
24079       int nFilename;
24080       nFilename = strlen(zFilename) + 6;
24081       zLockFile = (char *)sqlite3_malloc(nFilename);
24082       if( zLockFile==0 ){
24083         rc = SQLITE_NOMEM;
24084       }else{
24085         sqlite3_snprintf(nFilename, zLockFile, "%s.lock", zFilename);
24086       }
24087       pNew->lockingContext = zLockFile;
24088       break;
24089     }
24090
24091     case LOCKING_STYLE_FLOCK: 
24092     case LOCKING_STYLE_NONE: 
24093       break;
24094 #endif
24095   }
24096   
24097   pNew->lastErrno = 0;
24098   if( rc!=SQLITE_OK ){
24099     if( dirfd>=0 ) close(dirfd);
24100     close(h);
24101   }else{
24102     pNew->pMethod = &aIoMethod[eLockingStyle-1];
24103     OpenCounter(+1);
24104   }
24105   return rc;
24106 }
24107
24108 /*
24109 ** Open a file descriptor to the directory containing file zFilename.
24110 ** If successful, *pFd is set to the opened file descriptor and
24111 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
24112 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
24113 ** value.
24114 **
24115 ** If SQLITE_OK is returned, the caller is responsible for closing
24116 ** the file descriptor *pFd using close().
24117 */
24118 static int openDirectory(const char *zFilename, int *pFd){
24119   int ii;
24120   int fd = -1;
24121   char zDirname[MAX_PATHNAME+1];
24122
24123   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
24124   for(ii=strlen(zDirname); ii>=0 && zDirname[ii]!='/'; ii--);
24125   if( ii>0 ){
24126     zDirname[ii] = '\0';
24127     fd = open(zDirname, O_RDONLY|O_BINARY, 0);
24128     if( fd>=0 ){
24129 #ifdef FD_CLOEXEC
24130       fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
24131 #endif
24132       OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
24133     }
24134   }
24135   *pFd = fd;
24136   return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
24137 }
24138
24139 /*
24140 ** Create a temporary file name in zBuf.  zBuf must be allocated
24141 ** by the calling process and must be big enough to hold at least
24142 ** pVfs->mxPathname bytes.
24143 */
24144 static int getTempname(int nBuf, char *zBuf){
24145   static const char *azDirs[] = {
24146      0,
24147      "/var/tmp",
24148      "/usr/tmp",
24149      "/tmp",
24150      ".",
24151   };
24152   static const unsigned char zChars[] =
24153     "abcdefghijklmnopqrstuvwxyz"
24154     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
24155     "0123456789";
24156   int i, j;
24157   struct stat buf;
24158   const char *zDir = ".";
24159
24160   /* It's odd to simulate an io-error here, but really this is just
24161   ** using the io-error infrastructure to test that SQLite handles this
24162   ** function failing. 
24163   */
24164   SimulateIOError( return SQLITE_IOERR );
24165
24166   azDirs[0] = sqlite3_temp_directory;
24167   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
24168     if( azDirs[i]==0 ) continue;
24169     if( stat(azDirs[i], &buf) ) continue;
24170     if( !S_ISDIR(buf.st_mode) ) continue;
24171     if( access(azDirs[i], 07) ) continue;
24172     zDir = azDirs[i];
24173     break;
24174   }
24175
24176   /* Check that the output buffer is large enough for the temporary file 
24177   ** name. If it is not, return SQLITE_ERROR.
24178   */
24179   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= nBuf ){
24180     return SQLITE_ERROR;
24181   }
24182
24183   do{
24184     sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
24185     j = strlen(zBuf);
24186     sqlite3_randomness(15, &zBuf[j]);
24187     for(i=0; i<15; i++, j++){
24188       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
24189     }
24190     zBuf[j] = 0;
24191   }while( access(zBuf,0)==0 );
24192   return SQLITE_OK;
24193 }
24194
24195
24196 /*
24197 ** Open the file zPath.
24198 ** 
24199 ** Previously, the SQLite OS layer used three functions in place of this
24200 ** one:
24201 **
24202 **     sqlite3OsOpenReadWrite();
24203 **     sqlite3OsOpenReadOnly();
24204 **     sqlite3OsOpenExclusive();
24205 **
24206 ** These calls correspond to the following combinations of flags:
24207 **
24208 **     ReadWrite() ->     (READWRITE | CREATE)
24209 **     ReadOnly()  ->     (READONLY) 
24210 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
24211 **
24212 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
24213 ** true, the file was configured to be automatically deleted when the
24214 ** file handle closed. To achieve the same effect using this new 
24215 ** interface, add the DELETEONCLOSE flag to those specified above for 
24216 ** OpenExclusive().
24217 */
24218 static int unixOpen(
24219   sqlite3_vfs *pVfs, 
24220   const char *zPath, 
24221   sqlite3_file *pFile,
24222   int flags,
24223   int *pOutFlags
24224 ){
24225   int fd = 0;                    /* File descriptor returned by open() */
24226   int dirfd = -1;                /* Directory file descriptor */
24227   int oflags = 0;                /* Flags to pass to open() */
24228   int eType = flags&0xFFFFFF00;  /* Type of file to open */
24229   int noLock;                    /* True to omit locking primitives */
24230
24231   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
24232   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
24233   int isCreate     = (flags & SQLITE_OPEN_CREATE);
24234   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
24235   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
24236
24237   /* If creating a master or main-file journal, this function will open
24238   ** a file-descriptor on the directory too. The first time unixSync()
24239   ** is called the directory file descriptor will be fsync()ed and close()d.
24240   */
24241   int isOpenDirectory = (isCreate && 
24242       (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
24243   );
24244
24245   /* If argument zPath is a NULL pointer, this function is required to open
24246   ** a temporary file. Use this buffer to store the file name in.
24247   */
24248   char zTmpname[MAX_PATHNAME+1];
24249   const char *zName = zPath;
24250
24251   /* Check the following statements are true: 
24252   **
24253   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
24254   **   (b) if CREATE is set, then READWRITE must also be set, and
24255   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
24256   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
24257   */
24258   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
24259   assert(isCreate==0 || isReadWrite);
24260   assert(isExclusive==0 || isCreate);
24261   assert(isDelete==0 || isCreate);
24262
24263   /* The main DB, main journal, and master journal are never automatically
24264   ** deleted
24265   */
24266   assert( eType!=SQLITE_OPEN_MAIN_DB || !isDelete );
24267   assert( eType!=SQLITE_OPEN_MAIN_JOURNAL || !isDelete );
24268   assert( eType!=SQLITE_OPEN_MASTER_JOURNAL || !isDelete );
24269
24270   /* Assert that the upper layer has set one of the "file-type" flags. */
24271   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
24272        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
24273        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
24274        || eType==SQLITE_OPEN_TRANSIENT_DB
24275   );
24276
24277   memset(pFile, 0, sizeof(unixFile));
24278
24279   if( !zName ){
24280     int rc;
24281     assert(isDelete && !isOpenDirectory);
24282     rc = getTempname(MAX_PATHNAME+1, zTmpname);
24283     if( rc!=SQLITE_OK ){
24284       return rc;
24285     }
24286     zName = zTmpname;
24287   }
24288
24289   if( isReadonly )  oflags |= O_RDONLY;
24290   if( isReadWrite ) oflags |= O_RDWR;
24291   if( isCreate )    oflags |= O_CREAT;
24292   if( isExclusive ) oflags |= (O_EXCL|O_NOFOLLOW);
24293   oflags |= (O_LARGEFILE|O_BINARY);
24294
24295   fd = open(zName, oflags, isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
24296   if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
24297     /* Failed to open the file for read/write access. Try read-only. */
24298     flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
24299     flags |= SQLITE_OPEN_READONLY;
24300     return unixOpen(pVfs, zPath, pFile, flags, pOutFlags);
24301   }
24302   if( fd<0 ){
24303     return SQLITE_CANTOPEN;
24304   }
24305   if( isDelete ){
24306     unlink(zName);
24307   }
24308   if( pOutFlags ){
24309     *pOutFlags = flags;
24310   }
24311
24312   assert(fd!=0);
24313   if( isOpenDirectory ){
24314     int rc = openDirectory(zPath, &dirfd);
24315     if( rc!=SQLITE_OK ){
24316       close(fd);
24317       return rc;
24318     }
24319   }
24320
24321 #ifdef FD_CLOEXEC
24322   fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
24323 #endif
24324
24325   noLock = eType!=SQLITE_OPEN_MAIN_DB;
24326   return fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock);
24327 }
24328
24329 /*
24330 ** Delete the file at zPath. If the dirSync argument is true, fsync()
24331 ** the directory after deleting the file.
24332 */
24333 static int unixDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
24334   int rc = SQLITE_OK;
24335   SimulateIOError(return SQLITE_IOERR_DELETE);
24336   unlink(zPath);
24337   if( dirSync ){
24338     int fd;
24339     rc = openDirectory(zPath, &fd);
24340     if( rc==SQLITE_OK ){
24341       if( fsync(fd) ){
24342         rc = SQLITE_IOERR_DIR_FSYNC;
24343       }
24344       close(fd);
24345     }
24346   }
24347   return rc;
24348 }
24349
24350 /*
24351 ** Test the existance of or access permissions of file zPath. The
24352 ** test performed depends on the value of flags:
24353 **
24354 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
24355 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
24356 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
24357 **
24358 ** Otherwise return 0.
24359 */
24360 static int unixAccess(
24361   sqlite3_vfs *pVfs, 
24362   const char *zPath, 
24363   int flags, 
24364   int *pResOut
24365 ){
24366   int amode = 0;
24367   SimulateIOError( return SQLITE_IOERR_ACCESS; );
24368   switch( flags ){
24369     case SQLITE_ACCESS_EXISTS:
24370       amode = F_OK;
24371       break;
24372     case SQLITE_ACCESS_READWRITE:
24373       amode = W_OK|R_OK;
24374       break;
24375     case SQLITE_ACCESS_READ:
24376       amode = R_OK;
24377       break;
24378
24379     default:
24380       assert(!"Invalid flags argument");
24381   }
24382   *pResOut = (access(zPath, amode)==0);
24383   return SQLITE_OK;
24384 }
24385
24386
24387 /*
24388 ** Turn a relative pathname into a full pathname. The relative path
24389 ** is stored as a nul-terminated string in the buffer pointed to by
24390 ** zPath. 
24391 **
24392 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
24393 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
24394 ** this buffer before returning.
24395 */
24396 static int unixFullPathname(
24397   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
24398   const char *zPath,            /* Possibly relative input path */
24399   int nOut,                     /* Size of output buffer in bytes */
24400   char *zOut                    /* Output buffer */
24401 ){
24402
24403   /* It's odd to simulate an io-error here, but really this is just
24404   ** using the io-error infrastructure to test that SQLite handles this
24405   ** function failing. This function could fail if, for example, the
24406   ** current working directly has been unlinked.
24407   */
24408   SimulateIOError( return SQLITE_ERROR );
24409
24410   assert( pVfs->mxPathname==MAX_PATHNAME );
24411   zOut[nOut-1] = '\0';
24412   if( zPath[0]=='/' ){
24413     sqlite3_snprintf(nOut, zOut, "%s", zPath);
24414   }else{
24415     int nCwd;
24416     if( getcwd(zOut, nOut-1)==0 ){
24417       return SQLITE_CANTOPEN;
24418     }
24419     nCwd = strlen(zOut);
24420     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
24421   }
24422   return SQLITE_OK;
24423
24424 #if 0
24425   /*
24426   ** Remove "/./" path elements and convert "/A/./" path elements
24427   ** to just "/".
24428   */
24429   if( zFull ){
24430     int i, j;
24431     for(i=j=0; zFull[i]; i++){
24432       if( zFull[i]=='/' ){
24433         if( zFull[i+1]=='/' ) continue;
24434         if( zFull[i+1]=='.' && zFull[i+2]=='/' ){
24435           i += 1;
24436           continue;
24437         }
24438         if( zFull[i+1]=='.' && zFull[i+2]=='.' && zFull[i+3]=='/' ){
24439           while( j>0 && zFull[j-1]!='/' ){ j--; }
24440           i += 3;
24441           continue;
24442         }
24443       }
24444       zFull[j++] = zFull[i];
24445     }
24446     zFull[j] = 0;
24447   }
24448 #endif
24449 }
24450
24451
24452 #ifndef SQLITE_OMIT_LOAD_EXTENSION
24453 /*
24454 ** Interfaces for opening a shared library, finding entry points
24455 ** within the shared library, and closing the shared library.
24456 */
24457 #include <dlfcn.h>
24458 static void *unixDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
24459   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
24460 }
24461
24462 /*
24463 ** SQLite calls this function immediately after a call to unixDlSym() or
24464 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
24465 ** message is available, it is written to zBufOut. If no error message
24466 ** is available, zBufOut is left unmodified and SQLite uses a default
24467 ** error message.
24468 */
24469 static void unixDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
24470   char *zErr;
24471   enterMutex();
24472   zErr = dlerror();
24473   if( zErr ){
24474     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
24475   }
24476   leaveMutex();
24477 }
24478 static void *unixDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
24479   return dlsym(pHandle, zSymbol);
24480 }
24481 static void unixDlClose(sqlite3_vfs *pVfs, void *pHandle){
24482   dlclose(pHandle);
24483 }
24484 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
24485   #define unixDlOpen  0
24486   #define unixDlError 0
24487   #define unixDlSym   0
24488   #define unixDlClose 0
24489 #endif
24490
24491 /*
24492 ** Write nBuf bytes of random data to the supplied buffer zBuf.
24493 */
24494 static int unixRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
24495
24496   assert(nBuf>=(sizeof(time_t)+sizeof(int)));
24497
24498   /* We have to initialize zBuf to prevent valgrind from reporting
24499   ** errors.  The reports issued by valgrind are incorrect - we would
24500   ** prefer that the randomness be increased by making use of the
24501   ** uninitialized space in zBuf - but valgrind errors tend to worry
24502   ** some users.  Rather than argue, it seems easier just to initialize
24503   ** the whole array and silence valgrind, even if that means less randomness
24504   ** in the random seed.
24505   **
24506   ** When testing, initializing zBuf[] to zero is all we do.  That means
24507   ** that we always use the same random number sequence.  This makes the
24508   ** tests repeatable.
24509   */
24510   memset(zBuf, 0, nBuf);
24511 #if !defined(SQLITE_TEST)
24512   {
24513     int pid, fd;
24514     fd = open("/dev/urandom", O_RDONLY);
24515     if( fd<0 ){
24516       time_t t;
24517       time(&t);
24518       memcpy(zBuf, &t, sizeof(t));
24519       pid = getpid();
24520       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
24521     }else{
24522       read(fd, zBuf, nBuf);
24523       close(fd);
24524     }
24525   }
24526 #endif
24527   return SQLITE_OK;
24528 }
24529
24530
24531 /*
24532 ** Sleep for a little while.  Return the amount of time slept.
24533 ** The argument is the number of microseconds we want to sleep.
24534 ** The return value is the number of microseconds of sleep actually
24535 ** requested from the underlying operating system, a number which
24536 ** might be greater than or equal to the argument, but not less
24537 ** than the argument.
24538 */
24539 static int unixSleep(sqlite3_vfs *pVfs, int microseconds){
24540 #if defined(HAVE_USLEEP) && HAVE_USLEEP
24541   usleep(microseconds);
24542   return microseconds;
24543 #else
24544   int seconds = (microseconds+999999)/1000000;
24545   sleep(seconds);
24546   return seconds*1000000;
24547 #endif
24548 }
24549
24550 /*
24551 ** The following variable, if set to a non-zero value, becomes the result
24552 ** returned from sqlite3OsCurrentTime().  This is used for testing.
24553 */
24554 #ifdef SQLITE_TEST
24555 SQLITE_API int sqlite3_current_time = 0;
24556 #endif
24557
24558 /*
24559 ** Find the current time (in Universal Coordinated Time).  Write the
24560 ** current time and date as a Julian Day number into *prNow and
24561 ** return 0.  Return 1 if the time and date cannot be found.
24562 */
24563 static int unixCurrentTime(sqlite3_vfs *pVfs, double *prNow){
24564 #ifdef NO_GETTOD
24565   time_t t;
24566   time(&t);
24567   *prNow = t/86400.0 + 2440587.5;
24568 #else
24569   struct timeval sNow;
24570   gettimeofday(&sNow, 0);
24571   *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
24572 #endif
24573 #ifdef SQLITE_TEST
24574   if( sqlite3_current_time ){
24575     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
24576   }
24577 #endif
24578   return 0;
24579 }
24580
24581 static int unixGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
24582   return 0;
24583 }
24584
24585 /*
24586 ** Initialize the operating system interface.
24587 */
24588 SQLITE_API int sqlite3_os_init(void){ 
24589   /* Macro to define the static contents of an sqlite3_vfs structure for
24590   ** the unix backend. The two parameters are the values to use for
24591   ** the sqlite3_vfs.zName and sqlite3_vfs.pAppData fields, respectively.
24592   ** 
24593   */
24594   #define UNIXVFS(zVfsName, pVfsAppData) {                  \
24595     1,                    /* iVersion */                    \
24596     sizeof(unixFile),     /* szOsFile */                    \
24597     MAX_PATHNAME,         /* mxPathname */                  \
24598     0,                    /* pNext */                       \
24599     zVfsName,             /* zName */                       \
24600     (void *)pVfsAppData,  /* pAppData */                    \
24601     unixOpen,             /* xOpen */                       \
24602     unixDelete,           /* xDelete */                     \
24603     unixAccess,           /* xAccess */                     \
24604     unixFullPathname,     /* xFullPathname */               \
24605     unixDlOpen,           /* xDlOpen */                     \
24606     unixDlError,          /* xDlError */                    \
24607     unixDlSym,            /* xDlSym */                      \
24608     unixDlClose,          /* xDlClose */                    \
24609     unixRandomness,       /* xRandomness */                 \
24610     unixSleep,            /* xSleep */                      \
24611     unixCurrentTime,      /* xCurrentTime */                \
24612     unixGetLastError      /* xGetLastError */               \
24613   }
24614
24615   static sqlite3_vfs unixVfs = UNIXVFS("unix", 0);
24616 #ifdef SQLITE_ENABLE_LOCKING_STYLE
24617   int i;
24618   static sqlite3_vfs aVfs[] = {
24619     UNIXVFS("unix-posix",   LOCKING_STYLE_POSIX), 
24620     UNIXVFS("unix-afp",     LOCKING_STYLE_AFP), 
24621     UNIXVFS("unix-flock",   LOCKING_STYLE_FLOCK), 
24622     UNIXVFS("unix-dotfile", LOCKING_STYLE_DOTFILE), 
24623     UNIXVFS("unix-none",    LOCKING_STYLE_NONE)
24624   };
24625   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
24626     sqlite3_vfs_register(&aVfs[i], 0);
24627   }
24628 #endif
24629   sqlite3_vfs_register(&unixVfs, 1);
24630   return SQLITE_OK; 
24631 }
24632
24633 /*
24634 ** Shutdown the operating system interface. This is a no-op for unix.
24635 */
24636 SQLITE_API int sqlite3_os_end(void){ 
24637   return SQLITE_OK; 
24638 }
24639  
24640 #endif /* SQLITE_OS_UNIX */
24641
24642 /************** End of os_unix.c *********************************************/
24643 /************** Begin file os_win.c ******************************************/
24644 /*
24645 ** 2004 May 22
24646 **
24647 ** The author disclaims copyright to this source code.  In place of
24648 ** a legal notice, here is a blessing:
24649 **
24650 **    May you do good and not evil.
24651 **    May you find forgiveness for yourself and forgive others.
24652 **    May you share freely, never taking more than you give.
24653 **
24654 ******************************************************************************
24655 **
24656 ** This file contains code that is specific to windows.
24657 **
24658 ** $Id: os_win.c,v 1.133 2008/09/01 22:15:19 shane Exp $
24659 */
24660 #if SQLITE_OS_WIN               /* This file is used for windows only */
24661
24662
24663 /*
24664 ** A Note About Memory Allocation:
24665 **
24666 ** This driver uses malloc()/free() directly rather than going through
24667 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
24668 ** are designed for use on embedded systems where memory is scarce and
24669 ** malloc failures happen frequently.  Win32 does not typically run on
24670 ** embedded systems, and when it does the developers normally have bigger
24671 ** problems to worry about than running out of memory.  So there is not
24672 ** a compelling need to use the wrappers.
24673 **
24674 ** But there is a good reason to not use the wrappers.  If we use the
24675 ** wrappers then we will get simulated malloc() failures within this
24676 ** driver.  And that causes all kinds of problems for our tests.  We
24677 ** could enhance SQLite to deal with simulated malloc failures within
24678 ** the OS driver, but the code to deal with those failure would not
24679 ** be exercised on Linux (which does not need to malloc() in the driver)
24680 ** and so we would have difficulty writing coverage tests for that
24681 ** code.  Better to leave the code out, we think.
24682 **
24683 ** The point of this discussion is as follows:  When creating a new
24684 ** OS layer for an embedded system, if you use this file as an example,
24685 ** avoid the use of malloc()/free().  Those routines work ok on windows
24686 ** desktops but not so well in embedded systems.
24687 */
24688
24689 #include <winbase.h>
24690
24691 #ifdef __CYGWIN__
24692 # include <sys/cygwin.h>
24693 #endif
24694
24695 /*
24696 ** Macros used to determine whether or not to use threads.
24697 */
24698 #if defined(THREADSAFE) && THREADSAFE
24699 # define SQLITE_W32_THREADS 1
24700 #endif
24701
24702 /*
24703 ** Include code that is common to all os_*.c files
24704 */
24705 /************** Include os_common.h in the middle of os_win.c ****************/
24706 /************** Begin file os_common.h ***************************************/
24707 /*
24708 ** 2004 May 22
24709 **
24710 ** The author disclaims copyright to this source code.  In place of
24711 ** a legal notice, here is a blessing:
24712 **
24713 **    May you do good and not evil.
24714 **    May you find forgiveness for yourself and forgive others.
24715 **    May you share freely, never taking more than you give.
24716 **
24717 ******************************************************************************
24718 **
24719 ** This file contains macros and a little bit of code that is common to
24720 ** all of the platform-specific files (os_*.c) and is #included into those
24721 ** files.
24722 **
24723 ** This file should be #included by the os_*.c files only.  It is not a
24724 ** general purpose header file.
24725 **
24726 ** $Id: os_common.h,v 1.37 2008/05/29 20:22:37 shane Exp $
24727 */
24728 #ifndef _OS_COMMON_H_
24729 #define _OS_COMMON_H_
24730
24731 /*
24732 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
24733 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
24734 ** switch.  The following code should catch this problem at compile-time.
24735 */
24736 #ifdef MEMORY_DEBUG
24737 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
24738 #endif
24739
24740
24741 /*
24742  * When testing, this global variable stores the location of the
24743  * pending-byte in the database file.
24744  */
24745 #ifdef SQLITE_TEST
24746 SQLITE_API unsigned int sqlite3_pending_byte = 0x40000000;
24747 #endif
24748
24749 #ifdef SQLITE_DEBUG
24750 SQLITE_PRIVATE int sqlite3OSTrace = 0;
24751 #define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
24752 #define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
24753 #define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
24754 #define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
24755 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
24756 #define OSTRACE6(X,Y,Z,A,B,C) \
24757     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
24758 #define OSTRACE7(X,Y,Z,A,B,C,D) \
24759     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
24760 #else
24761 #define OSTRACE1(X)
24762 #define OSTRACE2(X,Y)
24763 #define OSTRACE3(X,Y,Z)
24764 #define OSTRACE4(X,Y,Z,A)
24765 #define OSTRACE5(X,Y,Z,A,B)
24766 #define OSTRACE6(X,Y,Z,A,B,C)
24767 #define OSTRACE7(X,Y,Z,A,B,C,D)
24768 #endif
24769
24770 /*
24771 ** Macros for performance tracing.  Normally turned off.  Only works
24772 ** on i486 hardware.
24773 */
24774 #ifdef SQLITE_PERFORMANCE_TRACE
24775
24776 /* 
24777 ** hwtime.h contains inline assembler code for implementing 
24778 ** high-performance timing routines.
24779 */
24780 /************** Include hwtime.h in the middle of os_common.h ****************/
24781 /************** Begin file hwtime.h ******************************************/
24782 /*
24783 ** 2008 May 27
24784 **
24785 ** The author disclaims copyright to this source code.  In place of
24786 ** a legal notice, here is a blessing:
24787 **
24788 **    May you do good and not evil.
24789 **    May you find forgiveness for yourself and forgive others.
24790 **    May you share freely, never taking more than you give.
24791 **
24792 ******************************************************************************
24793 **
24794 ** This file contains inline asm code for retrieving "high-performance"
24795 ** counters for x86 class CPUs.
24796 **
24797 ** $Id: hwtime.h,v 1.3 2008/08/01 14:33:15 shane Exp $
24798 */
24799 #ifndef _HWTIME_H_
24800 #define _HWTIME_H_
24801
24802 /*
24803 ** The following routine only works on pentium-class (or newer) processors.
24804 ** It uses the RDTSC opcode to read the cycle count value out of the
24805 ** processor and returns that value.  This can be used for high-res
24806 ** profiling.
24807 */
24808 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
24809       (defined(i386) || defined(__i386__) || defined(_M_IX86))
24810
24811   #if defined(__GNUC__)
24812
24813   __inline__ sqlite_uint64 sqlite3Hwtime(void){
24814      unsigned int lo, hi;
24815      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
24816      return (sqlite_uint64)hi << 32 | lo;
24817   }
24818
24819   #elif defined(_MSC_VER)
24820
24821   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
24822      __asm {
24823         rdtsc
24824         ret       ; return value at EDX:EAX
24825      }
24826   }
24827
24828   #endif
24829
24830 #elif (defined(__GNUC__) && defined(__x86_64__))
24831
24832   __inline__ sqlite_uint64 sqlite3Hwtime(void){
24833       unsigned long val;
24834       __asm__ __volatile__ ("rdtsc" : "=A" (val));
24835       return val;
24836   }
24837  
24838 #elif (defined(__GNUC__) && defined(__ppc__))
24839
24840   __inline__ sqlite_uint64 sqlite3Hwtime(void){
24841       unsigned long long retval;
24842       unsigned long junk;
24843       __asm__ __volatile__ ("\n\
24844           1:      mftbu   %1\n\
24845                   mftb    %L0\n\
24846                   mftbu   %0\n\
24847                   cmpw    %0,%1\n\
24848                   bne     1b"
24849                   : "=r" (retval), "=r" (junk));
24850       return retval;
24851   }
24852
24853 #else
24854
24855   #error Need implementation of sqlite3Hwtime() for your platform.
24856
24857   /*
24858   ** To compile without implementing sqlite3Hwtime() for your platform,
24859   ** you can remove the above #error and use the following
24860   ** stub function.  You will lose timing support for many
24861   ** of the debugging and testing utilities, but it should at
24862   ** least compile and run.
24863   */
24864 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
24865
24866 #endif
24867
24868 #endif /* !defined(_HWTIME_H_) */
24869
24870 /************** End of hwtime.h **********************************************/
24871 /************** Continuing where we left off in os_common.h ******************/
24872
24873 static sqlite_uint64 g_start;
24874 static sqlite_uint64 g_elapsed;
24875 #define TIMER_START       g_start=sqlite3Hwtime()
24876 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
24877 #define TIMER_ELAPSED     g_elapsed
24878 #else
24879 #define TIMER_START
24880 #define TIMER_END
24881 #define TIMER_ELAPSED     ((sqlite_uint64)0)
24882 #endif
24883
24884 /*
24885 ** If we compile with the SQLITE_TEST macro set, then the following block
24886 ** of code will give us the ability to simulate a disk I/O error.  This
24887 ** is used for testing the I/O recovery logic.
24888 */
24889 #ifdef SQLITE_TEST
24890 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
24891 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
24892 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
24893 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
24894 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
24895 SQLITE_API int sqlite3_diskfull_pending = 0;
24896 SQLITE_API int sqlite3_diskfull = 0;
24897 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
24898 #define SimulateIOError(CODE)  \
24899   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
24900        || sqlite3_io_error_pending-- == 1 )  \
24901               { local_ioerr(); CODE; }
24902 static void local_ioerr(){
24903   IOTRACE(("IOERR\n"));
24904   sqlite3_io_error_hit++;
24905   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
24906 }
24907 #define SimulateDiskfullError(CODE) \
24908    if( sqlite3_diskfull_pending ){ \
24909      if( sqlite3_diskfull_pending == 1 ){ \
24910        local_ioerr(); \
24911        sqlite3_diskfull = 1; \
24912        sqlite3_io_error_hit = 1; \
24913        CODE; \
24914      }else{ \
24915        sqlite3_diskfull_pending--; \
24916      } \
24917    }
24918 #else
24919 #define SimulateIOErrorBenign(X)
24920 #define SimulateIOError(A)
24921 #define SimulateDiskfullError(A)
24922 #endif
24923
24924 /*
24925 ** When testing, keep a count of the number of open files.
24926 */
24927 #ifdef SQLITE_TEST
24928 SQLITE_API int sqlite3_open_file_count = 0;
24929 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
24930 #else
24931 #define OpenCounter(X)
24932 #endif
24933
24934 #endif /* !defined(_OS_COMMON_H_) */
24935
24936 /************** End of os_common.h *******************************************/
24937 /************** Continuing where we left off in os_win.c *********************/
24938
24939 /*
24940 ** Some microsoft compilers lack this definition.
24941 */
24942 #ifndef INVALID_FILE_ATTRIBUTES
24943 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) 
24944 #endif
24945
24946 /*
24947 ** Determine if we are dealing with WindowsCE - which has a much
24948 ** reduced API.
24949 */
24950 #if defined(SQLITE_OS_WINCE)
24951 # define AreFileApisANSI() 1
24952 #endif
24953
24954 /*
24955 ** WinCE lacks native support for file locking so we have to fake it
24956 ** with some code of our own.
24957 */
24958 #if SQLITE_OS_WINCE
24959 typedef struct winceLock {
24960   int nReaders;       /* Number of reader locks obtained */
24961   BOOL bPending;      /* Indicates a pending lock has been obtained */
24962   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
24963   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
24964 } winceLock;
24965 #endif
24966
24967 /*
24968 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
24969 ** portability layer.
24970 */
24971 typedef struct winFile winFile;
24972 struct winFile {
24973   const sqlite3_io_methods *pMethod;/* Must be first */
24974   HANDLE h;               /* Handle for accessing the file */
24975   unsigned char locktype; /* Type of lock currently held on this file */
24976   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
24977 #if SQLITE_OS_WINCE
24978   WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
24979   HANDLE hMutex;          /* Mutex used to control access to shared lock */  
24980   HANDLE hShared;         /* Shared memory segment used for locking */
24981   winceLock local;        /* Locks obtained by this instance of winFile */
24982   winceLock *shared;      /* Global shared lock memory for the file  */
24983 #endif
24984 };
24985
24986
24987 /*
24988 ** The following variable is (normally) set once and never changes
24989 ** thereafter.  It records whether the operating system is Win95
24990 ** or WinNT.
24991 **
24992 ** 0:   Operating system unknown.
24993 ** 1:   Operating system is Win95.
24994 ** 2:   Operating system is WinNT.
24995 **
24996 ** In order to facilitate testing on a WinNT system, the test fixture
24997 ** can manually set this value to 1 to emulate Win98 behavior.
24998 */
24999 #ifdef SQLITE_TEST
25000 SQLITE_API int sqlite3_os_type = 0;
25001 #else
25002 static int sqlite3_os_type = 0;
25003 #endif
25004
25005 /*
25006 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
25007 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
25008 **
25009 ** Here is an interesting observation:  Win95, Win98, and WinME lack
25010 ** the LockFileEx() API.  But we can still statically link against that
25011 ** API as long as we don't call it win running Win95/98/ME.  A call to
25012 ** this routine is used to determine if the host is Win95/98/ME or
25013 ** WinNT/2K/XP so that we will know whether or not we can safely call
25014 ** the LockFileEx() API.
25015 */
25016 #if SQLITE_OS_WINCE
25017 # define isNT()  (1)
25018 #else
25019   static int isNT(void){
25020     if( sqlite3_os_type==0 ){
25021       OSVERSIONINFO sInfo;
25022       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
25023       GetVersionEx(&sInfo);
25024       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
25025     }
25026     return sqlite3_os_type==2;
25027   }
25028 #endif /* SQLITE_OS_WINCE */
25029
25030 /*
25031 ** Convert a UTF-8 string to microsoft unicode (UTF-16?). 
25032 **
25033 ** Space to hold the returned string is obtained from malloc.
25034 */
25035 static WCHAR *utf8ToUnicode(const char *zFilename){
25036   int nChar;
25037   WCHAR *zWideFilename;
25038
25039   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
25040   zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
25041   if( zWideFilename==0 ){
25042     return 0;
25043   }
25044   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
25045   if( nChar==0 ){
25046     free(zWideFilename);
25047     zWideFilename = 0;
25048   }
25049   return zWideFilename;
25050 }
25051
25052 /*
25053 ** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
25054 ** obtained from malloc().
25055 */
25056 static char *unicodeToUtf8(const WCHAR *zWideFilename){
25057   int nByte;
25058   char *zFilename;
25059
25060   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
25061   zFilename = malloc( nByte );
25062   if( zFilename==0 ){
25063     return 0;
25064   }
25065   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
25066                               0, 0);
25067   if( nByte == 0 ){
25068     free(zFilename);
25069     zFilename = 0;
25070   }
25071   return zFilename;
25072 }
25073
25074 /*
25075 ** Convert an ansi string to microsoft unicode, based on the
25076 ** current codepage settings for file apis.
25077 ** 
25078 ** Space to hold the returned string is obtained
25079 ** from malloc.
25080 */
25081 static WCHAR *mbcsToUnicode(const char *zFilename){
25082   int nByte;
25083   WCHAR *zMbcsFilename;
25084   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
25085
25086   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
25087   zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
25088   if( zMbcsFilename==0 ){
25089     return 0;
25090   }
25091   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
25092   if( nByte==0 ){
25093     free(zMbcsFilename);
25094     zMbcsFilename = 0;
25095   }
25096   return zMbcsFilename;
25097 }
25098
25099 /*
25100 ** Convert microsoft unicode to multibyte character string, based on the
25101 ** user's Ansi codepage.
25102 **
25103 ** Space to hold the returned string is obtained from
25104 ** malloc().
25105 */
25106 static char *unicodeToMbcs(const WCHAR *zWideFilename){
25107   int nByte;
25108   char *zFilename;
25109   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
25110
25111   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
25112   zFilename = malloc( nByte );
25113   if( zFilename==0 ){
25114     return 0;
25115   }
25116   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
25117                               0, 0);
25118   if( nByte == 0 ){
25119     free(zFilename);
25120     zFilename = 0;
25121   }
25122   return zFilename;
25123 }
25124
25125 /*
25126 ** Convert multibyte character string to UTF-8.  Space to hold the
25127 ** returned string is obtained from malloc().
25128 */
25129 static char *mbcsToUtf8(const char *zFilename){
25130   char *zFilenameUtf8;
25131   WCHAR *zTmpWide;
25132
25133   zTmpWide = mbcsToUnicode(zFilename);
25134   if( zTmpWide==0 ){
25135     return 0;
25136   }
25137   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
25138   free(zTmpWide);
25139   return zFilenameUtf8;
25140 }
25141
25142 /*
25143 ** Convert UTF-8 to multibyte character string.  Space to hold the 
25144 ** returned string is obtained from malloc().
25145 */
25146 static char *utf8ToMbcs(const char *zFilename){
25147   char *zFilenameMbcs;
25148   WCHAR *zTmpWide;
25149
25150   zTmpWide = utf8ToUnicode(zFilename);
25151   if( zTmpWide==0 ){
25152     return 0;
25153   }
25154   zFilenameMbcs = unicodeToMbcs(zTmpWide);
25155   free(zTmpWide);
25156   return zFilenameMbcs;
25157 }
25158
25159 #if SQLITE_OS_WINCE
25160 /*************************************************************************
25161 ** This section contains code for WinCE only.
25162 */
25163 /*
25164 ** WindowsCE does not have a localtime() function.  So create a
25165 ** substitute.
25166 */
25167 struct tm *__cdecl localtime(const time_t *t)
25168 {
25169   static struct tm y;
25170   FILETIME uTm, lTm;
25171   SYSTEMTIME pTm;
25172   sqlite3_int64 t64;
25173   t64 = *t;
25174   t64 = (t64 + 11644473600)*10000000;
25175   uTm.dwLowDateTime = t64 & 0xFFFFFFFF;
25176   uTm.dwHighDateTime= t64 >> 32;
25177   FileTimeToLocalFileTime(&uTm,&lTm);
25178   FileTimeToSystemTime(&lTm,&pTm);
25179   y.tm_year = pTm.wYear - 1900;
25180   y.tm_mon = pTm.wMonth - 1;
25181   y.tm_wday = pTm.wDayOfWeek;
25182   y.tm_mday = pTm.wDay;
25183   y.tm_hour = pTm.wHour;
25184   y.tm_min = pTm.wMinute;
25185   y.tm_sec = pTm.wSecond;
25186   return &y;
25187 }
25188
25189 /* This will never be called, but defined to make the code compile */
25190 #define GetTempPathA(a,b)
25191
25192 #define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
25193 #define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
25194 #define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
25195
25196 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-offsetof(winFile,h)]
25197
25198 /*
25199 ** Acquire a lock on the handle h
25200 */
25201 static void winceMutexAcquire(HANDLE h){
25202    DWORD dwErr;
25203    do {
25204      dwErr = WaitForSingleObject(h, INFINITE);
25205    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
25206 }
25207 /*
25208 ** Release a lock acquired by winceMutexAcquire()
25209 */
25210 #define winceMutexRelease(h) ReleaseMutex(h)
25211
25212 /*
25213 ** Create the mutex and shared memory used for locking in the file
25214 ** descriptor pFile
25215 */
25216 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
25217   WCHAR *zTok;
25218   WCHAR *zName = utf8ToUnicode(zFilename);
25219   BOOL bInit = TRUE;
25220
25221   /* Initialize the local lockdata */
25222   ZeroMemory(&pFile->local, sizeof(pFile->local));
25223
25224   /* Replace the backslashes from the filename and lowercase it
25225   ** to derive a mutex name. */
25226   zTok = CharLowerW(zName);
25227   for (;*zTok;zTok++){
25228     if (*zTok == '\\') *zTok = '_';
25229   }
25230
25231   /* Create/open the named mutex */
25232   pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
25233   if (!pFile->hMutex){
25234     free(zName);
25235     return FALSE;
25236   }
25237
25238   /* Acquire the mutex before continuing */
25239   winceMutexAcquire(pFile->hMutex);
25240   
25241   /* Since the names of named mutexes, semaphores, file mappings etc are 
25242   ** case-sensitive, take advantage of that by uppercasing the mutex name
25243   ** and using that as the shared filemapping name.
25244   */
25245   CharUpperW(zName);
25246   pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
25247                                        PAGE_READWRITE, 0, sizeof(winceLock),
25248                                        zName);  
25249
25250   /* Set a flag that indicates we're the first to create the memory so it 
25251   ** must be zero-initialized */
25252   if (GetLastError() == ERROR_ALREADY_EXISTS){
25253     bInit = FALSE;
25254   }
25255
25256   free(zName);
25257
25258   /* If we succeeded in making the shared memory handle, map it. */
25259   if (pFile->hShared){
25260     pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared, 
25261              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
25262     /* If mapping failed, close the shared memory handle and erase it */
25263     if (!pFile->shared){
25264       CloseHandle(pFile->hShared);
25265       pFile->hShared = NULL;
25266     }
25267   }
25268
25269   /* If shared memory could not be created, then close the mutex and fail */
25270   if (pFile->hShared == NULL){
25271     winceMutexRelease(pFile->hMutex);
25272     CloseHandle(pFile->hMutex);
25273     pFile->hMutex = NULL;
25274     return FALSE;
25275   }
25276   
25277   /* Initialize the shared memory if we're supposed to */
25278   if (bInit) {
25279     ZeroMemory(pFile->shared, sizeof(winceLock));
25280   }
25281
25282   winceMutexRelease(pFile->hMutex);
25283   return TRUE;
25284 }
25285
25286 /*
25287 ** Destroy the part of winFile that deals with wince locks
25288 */
25289 static void winceDestroyLock(winFile *pFile){
25290   if (pFile->hMutex){
25291     /* Acquire the mutex */
25292     winceMutexAcquire(pFile->hMutex);
25293
25294     /* The following blocks should probably assert in debug mode, but they
25295        are to cleanup in case any locks remained open */
25296     if (pFile->local.nReaders){
25297       pFile->shared->nReaders --;
25298     }
25299     if (pFile->local.bReserved){
25300       pFile->shared->bReserved = FALSE;
25301     }
25302     if (pFile->local.bPending){
25303       pFile->shared->bPending = FALSE;
25304     }
25305     if (pFile->local.bExclusive){
25306       pFile->shared->bExclusive = FALSE;
25307     }
25308
25309     /* De-reference and close our copy of the shared memory handle */
25310     UnmapViewOfFile(pFile->shared);
25311     CloseHandle(pFile->hShared);
25312
25313     /* Done with the mutex */
25314     winceMutexRelease(pFile->hMutex);    
25315     CloseHandle(pFile->hMutex);
25316     pFile->hMutex = NULL;
25317   }
25318 }
25319
25320 /* 
25321 ** An implementation of the LockFile() API of windows for wince
25322 */
25323 static BOOL winceLockFile(
25324   HANDLE *phFile,
25325   DWORD dwFileOffsetLow,
25326   DWORD dwFileOffsetHigh,
25327   DWORD nNumberOfBytesToLockLow,
25328   DWORD nNumberOfBytesToLockHigh
25329 ){
25330   winFile *pFile = HANDLE_TO_WINFILE(phFile);
25331   BOOL bReturn = FALSE;
25332
25333   if (!pFile->hMutex) return TRUE;
25334   winceMutexAcquire(pFile->hMutex);
25335
25336   /* Wanting an exclusive lock? */
25337   if (dwFileOffsetLow == SHARED_FIRST
25338        && nNumberOfBytesToLockLow == SHARED_SIZE){
25339     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
25340        pFile->shared->bExclusive = TRUE;
25341        pFile->local.bExclusive = TRUE;
25342        bReturn = TRUE;
25343     }
25344   }
25345
25346   /* Want a read-only lock? */
25347   else if ((dwFileOffsetLow >= SHARED_FIRST &&
25348             dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE) &&
25349             nNumberOfBytesToLockLow == 1){
25350     if (pFile->shared->bExclusive == 0){
25351       pFile->local.nReaders ++;
25352       if (pFile->local.nReaders == 1){
25353         pFile->shared->nReaders ++;
25354       }
25355       bReturn = TRUE;
25356     }
25357   }
25358
25359   /* Want a pending lock? */
25360   else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToLockLow == 1){
25361     /* If no pending lock has been acquired, then acquire it */
25362     if (pFile->shared->bPending == 0) {
25363       pFile->shared->bPending = TRUE;
25364       pFile->local.bPending = TRUE;
25365       bReturn = TRUE;
25366     }
25367   }
25368   /* Want a reserved lock? */
25369   else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
25370     if (pFile->shared->bReserved == 0) {
25371       pFile->shared->bReserved = TRUE;
25372       pFile->local.bReserved = TRUE;
25373       bReturn = TRUE;
25374     }
25375   }
25376
25377   winceMutexRelease(pFile->hMutex);
25378   return bReturn;
25379 }
25380
25381 /*
25382 ** An implementation of the UnlockFile API of windows for wince
25383 */
25384 static BOOL winceUnlockFile(
25385   HANDLE *phFile,
25386   DWORD dwFileOffsetLow,
25387   DWORD dwFileOffsetHigh,
25388   DWORD nNumberOfBytesToUnlockLow,
25389   DWORD nNumberOfBytesToUnlockHigh
25390 ){
25391   winFile *pFile = HANDLE_TO_WINFILE(phFile);
25392   BOOL bReturn = FALSE;
25393
25394   if (!pFile->hMutex) return TRUE;
25395   winceMutexAcquire(pFile->hMutex);
25396
25397   /* Releasing a reader lock or an exclusive lock */
25398   if (dwFileOffsetLow >= SHARED_FIRST &&
25399        dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE){
25400     /* Did we have an exclusive lock? */
25401     if (pFile->local.bExclusive){
25402       pFile->local.bExclusive = FALSE;
25403       pFile->shared->bExclusive = FALSE;
25404       bReturn = TRUE;
25405     }
25406
25407     /* Did we just have a reader lock? */
25408     else if (pFile->local.nReaders){
25409       pFile->local.nReaders --;
25410       if (pFile->local.nReaders == 0)
25411       {
25412         pFile->shared->nReaders --;
25413       }
25414       bReturn = TRUE;
25415     }
25416   }
25417
25418   /* Releasing a pending lock */
25419   else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
25420     if (pFile->local.bPending){
25421       pFile->local.bPending = FALSE;
25422       pFile->shared->bPending = FALSE;
25423       bReturn = TRUE;
25424     }
25425   }
25426   /* Releasing a reserved lock */
25427   else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
25428     if (pFile->local.bReserved) {
25429       pFile->local.bReserved = FALSE;
25430       pFile->shared->bReserved = FALSE;
25431       bReturn = TRUE;
25432     }
25433   }
25434
25435   winceMutexRelease(pFile->hMutex);
25436   return bReturn;
25437 }
25438
25439 /*
25440 ** An implementation of the LockFileEx() API of windows for wince
25441 */
25442 static BOOL winceLockFileEx(
25443   HANDLE *phFile,
25444   DWORD dwFlags,
25445   DWORD dwReserved,
25446   DWORD nNumberOfBytesToLockLow,
25447   DWORD nNumberOfBytesToLockHigh,
25448   LPOVERLAPPED lpOverlapped
25449 ){
25450   /* If the caller wants a shared read lock, forward this call
25451   ** to winceLockFile */
25452   if (lpOverlapped->Offset == SHARED_FIRST &&
25453       dwFlags == 1 &&
25454       nNumberOfBytesToLockLow == SHARED_SIZE){
25455     return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
25456   }
25457   return FALSE;
25458 }
25459 /*
25460 ** End of the special code for wince
25461 *****************************************************************************/
25462 #endif /* SQLITE_OS_WINCE */
25463
25464 /*****************************************************************************
25465 ** The next group of routines implement the I/O methods specified
25466 ** by the sqlite3_io_methods object.
25467 ******************************************************************************/
25468
25469 /*
25470 ** Close a file.
25471 **
25472 ** It is reported that an attempt to close a handle might sometimes
25473 ** fail.  This is a very unreasonable result, but windows is notorious
25474 ** for being unreasonable so I do not doubt that it might happen.  If
25475 ** the close fails, we pause for 100 milliseconds and try again.  As
25476 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
25477 ** giving up and returning an error.
25478 */
25479 #define MX_CLOSE_ATTEMPT 3
25480 static int winClose(sqlite3_file *id){
25481   int rc, cnt = 0;
25482   winFile *pFile = (winFile*)id;
25483   OSTRACE2("CLOSE %d\n", pFile->h);
25484   do{
25485     rc = CloseHandle(pFile->h);
25486   }while( rc==0 && cnt++ < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
25487 #if SQLITE_OS_WINCE
25488 #define WINCE_DELETION_ATTEMPTS 3
25489   winceDestroyLock(pFile);
25490   if( pFile->zDeleteOnClose ){
25491     int cnt = 0;
25492     while(
25493            DeleteFileW(pFile->zDeleteOnClose)==0
25494         && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
25495         && cnt++ < WINCE_DELETION_ATTEMPTS
25496     ){
25497        Sleep(100);  /* Wait a little before trying again */
25498     }
25499     free(pFile->zDeleteOnClose);
25500   }
25501 #endif
25502   OpenCounter(-1);
25503   return rc ? SQLITE_OK : SQLITE_IOERR;
25504 }
25505
25506 /*
25507 ** Some microsoft compilers lack this definition.
25508 */
25509 #ifndef INVALID_SET_FILE_POINTER
25510 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
25511 #endif
25512
25513 /*
25514 ** Read data from a file into a buffer.  Return SQLITE_OK if all
25515 ** bytes were read successfully and SQLITE_IOERR if anything goes
25516 ** wrong.
25517 */
25518 static int winRead(
25519   sqlite3_file *id,          /* File to read from */
25520   void *pBuf,                /* Write content into this buffer */
25521   int amt,                   /* Number of bytes to read */
25522   sqlite3_int64 offset       /* Begin reading at this offset */
25523 ){
25524   LONG upperBits = (offset>>32) & 0x7fffffff;
25525   LONG lowerBits = offset & 0xffffffff;
25526   DWORD rc;
25527   DWORD got;
25528   winFile *pFile = (winFile*)id;
25529   assert( id!=0 );
25530   SimulateIOError(return SQLITE_IOERR_READ);
25531   OSTRACE3("READ %d lock=%d\n", pFile->h, pFile->locktype);
25532   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
25533   if( rc==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR ){
25534     return SQLITE_FULL;
25535   }
25536   if( !ReadFile(pFile->h, pBuf, amt, &got, 0) ){
25537     return SQLITE_IOERR_READ;
25538   }
25539   if( got==(DWORD)amt ){
25540     return SQLITE_OK;
25541   }else{
25542     memset(&((char*)pBuf)[got], 0, amt-got);
25543     return SQLITE_IOERR_SHORT_READ;
25544   }
25545 }
25546
25547 /*
25548 ** Write data from a buffer into a file.  Return SQLITE_OK on success
25549 ** or some other error code on failure.
25550 */
25551 static int winWrite(
25552   sqlite3_file *id,         /* File to write into */
25553   const void *pBuf,         /* The bytes to be written */
25554   int amt,                  /* Number of bytes to write */
25555   sqlite3_int64 offset      /* Offset into the file to begin writing at */
25556 ){
25557   LONG upperBits = (offset>>32) & 0x7fffffff;
25558   LONG lowerBits = offset & 0xffffffff;
25559   DWORD rc;
25560   DWORD wrote;
25561   winFile *pFile = (winFile*)id;
25562   assert( id!=0 );
25563   SimulateIOError(return SQLITE_IOERR_WRITE);
25564   SimulateDiskfullError(return SQLITE_FULL);
25565   OSTRACE3("WRITE %d lock=%d\n", pFile->h, pFile->locktype);
25566   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
25567   if( rc==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR ){
25568     return SQLITE_FULL;
25569   }
25570   assert( amt>0 );
25571   while(
25572      amt>0
25573      && (rc = WriteFile(pFile->h, pBuf, amt, &wrote, 0))!=0
25574      && wrote>0
25575   ){
25576     amt -= wrote;
25577     pBuf = &((char*)pBuf)[wrote];
25578   }
25579   if( !rc || amt>(int)wrote ){
25580     return SQLITE_FULL;
25581   }
25582   return SQLITE_OK;
25583 }
25584
25585 /*
25586 ** Truncate an open file to a specified size
25587 */
25588 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
25589   LONG upperBits = (nByte>>32) & 0x7fffffff;
25590   LONG lowerBits = nByte & 0xffffffff;
25591   winFile *pFile = (winFile*)id;
25592   OSTRACE3("TRUNCATE %d %lld\n", pFile->h, nByte);
25593   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
25594   SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
25595   SetEndOfFile(pFile->h);
25596   return SQLITE_OK;
25597 }
25598
25599 #ifdef SQLITE_TEST
25600 /*
25601 ** Count the number of fullsyncs and normal syncs.  This is used to test
25602 ** that syncs and fullsyncs are occuring at the right times.
25603 */
25604 SQLITE_API int sqlite3_sync_count = 0;
25605 SQLITE_API int sqlite3_fullsync_count = 0;
25606 #endif
25607
25608 /*
25609 ** Make sure all writes to a particular file are committed to disk.
25610 */
25611 static int winSync(sqlite3_file *id, int flags){
25612   winFile *pFile = (winFile*)id;
25613   OSTRACE3("SYNC %d lock=%d\n", pFile->h, pFile->locktype);
25614 #ifdef SQLITE_TEST
25615   if( flags & SQLITE_SYNC_FULL ){
25616     sqlite3_fullsync_count++;
25617   }
25618   sqlite3_sync_count++;
25619 #endif
25620   if( FlushFileBuffers(pFile->h) ){
25621     return SQLITE_OK;
25622   }else{
25623     return SQLITE_IOERR;
25624   }
25625 }
25626
25627 /*
25628 ** Determine the current size of a file in bytes
25629 */
25630 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
25631   winFile *pFile = (winFile*)id;
25632   DWORD upperBits, lowerBits;
25633   SimulateIOError(return SQLITE_IOERR_FSTAT);
25634   lowerBits = GetFileSize(pFile->h, &upperBits);
25635   *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
25636   return SQLITE_OK;
25637 }
25638
25639 /*
25640 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
25641 */
25642 #ifndef LOCKFILE_FAIL_IMMEDIATELY
25643 # define LOCKFILE_FAIL_IMMEDIATELY 1
25644 #endif
25645
25646 /*
25647 ** Acquire a reader lock.
25648 ** Different API routines are called depending on whether or not this
25649 ** is Win95 or WinNT.
25650 */
25651 static int getReadLock(winFile *pFile){
25652   int res;
25653   if( isNT() ){
25654     OVERLAPPED ovlp;
25655     ovlp.Offset = SHARED_FIRST;
25656     ovlp.OffsetHigh = 0;
25657     ovlp.hEvent = 0;
25658     res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
25659                      0, SHARED_SIZE, 0, &ovlp);
25660   }else{
25661     int lk;
25662     sqlite3_randomness(sizeof(lk), &lk);
25663     pFile->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
25664     res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
25665   }
25666   return res;
25667 }
25668
25669 /*
25670 ** Undo a readlock
25671 */
25672 static int unlockReadLock(winFile *pFile){
25673   int res;
25674   if( isNT() ){
25675     res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
25676   }else{
25677     res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
25678   }
25679   return res;
25680 }
25681
25682 /*
25683 ** Lock the file with the lock specified by parameter locktype - one
25684 ** of the following:
25685 **
25686 **     (1) SHARED_LOCK
25687 **     (2) RESERVED_LOCK
25688 **     (3) PENDING_LOCK
25689 **     (4) EXCLUSIVE_LOCK
25690 **
25691 ** Sometimes when requesting one lock state, additional lock states
25692 ** are inserted in between.  The locking might fail on one of the later
25693 ** transitions leaving the lock state different from what it started but
25694 ** still short of its goal.  The following chart shows the allowed
25695 ** transitions and the inserted intermediate states:
25696 **
25697 **    UNLOCKED -> SHARED
25698 **    SHARED -> RESERVED
25699 **    SHARED -> (PENDING) -> EXCLUSIVE
25700 **    RESERVED -> (PENDING) -> EXCLUSIVE
25701 **    PENDING -> EXCLUSIVE
25702 **
25703 ** This routine will only increase a lock.  The winUnlock() routine
25704 ** erases all locks at once and returns us immediately to locking level 0.
25705 ** It is not possible to lower the locking level one step at a time.  You
25706 ** must go straight to locking level 0.
25707 */
25708 static int winLock(sqlite3_file *id, int locktype){
25709   int rc = SQLITE_OK;    /* Return code from subroutines */
25710   int res = 1;           /* Result of a windows lock call */
25711   int newLocktype;       /* Set pFile->locktype to this value before exiting */
25712   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
25713   winFile *pFile = (winFile*)id;
25714
25715   assert( pFile!=0 );
25716   OSTRACE5("LOCK %d %d was %d(%d)\n",
25717           pFile->h, locktype, pFile->locktype, pFile->sharedLockByte);
25718
25719   /* If there is already a lock of this type or more restrictive on the
25720   ** OsFile, do nothing. Don't use the end_lock: exit path, as
25721   ** sqlite3OsEnterMutex() hasn't been called yet.
25722   */
25723   if( pFile->locktype>=locktype ){
25724     return SQLITE_OK;
25725   }
25726
25727   /* Make sure the locking sequence is correct
25728   */
25729   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
25730   assert( locktype!=PENDING_LOCK );
25731   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
25732
25733   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
25734   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
25735   ** the PENDING_LOCK byte is temporary.
25736   */
25737   newLocktype = pFile->locktype;
25738   if( pFile->locktype==NO_LOCK
25739    || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
25740   ){
25741     int cnt = 3;
25742     while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
25743       /* Try 3 times to get the pending lock.  The pending lock might be
25744       ** held by another reader process who will release it momentarily.
25745       */
25746       OSTRACE2("could not get a PENDING lock. cnt=%d\n", cnt);
25747       Sleep(1);
25748     }
25749     gotPendingLock = res;
25750   }
25751
25752   /* Acquire a shared lock
25753   */
25754   if( locktype==SHARED_LOCK && res ){
25755     assert( pFile->locktype==NO_LOCK );
25756     res = getReadLock(pFile);
25757     if( res ){
25758       newLocktype = SHARED_LOCK;
25759     }
25760   }
25761
25762   /* Acquire a RESERVED lock
25763   */
25764   if( locktype==RESERVED_LOCK && res ){
25765     assert( pFile->locktype==SHARED_LOCK );
25766     res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
25767     if( res ){
25768       newLocktype = RESERVED_LOCK;
25769     }
25770   }
25771
25772   /* Acquire a PENDING lock
25773   */
25774   if( locktype==EXCLUSIVE_LOCK && res ){
25775     newLocktype = PENDING_LOCK;
25776     gotPendingLock = 0;
25777   }
25778
25779   /* Acquire an EXCLUSIVE lock
25780   */
25781   if( locktype==EXCLUSIVE_LOCK && res ){
25782     assert( pFile->locktype>=SHARED_LOCK );
25783     res = unlockReadLock(pFile);
25784     OSTRACE2("unreadlock = %d\n", res);
25785     res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
25786     if( res ){
25787       newLocktype = EXCLUSIVE_LOCK;
25788     }else{
25789       OSTRACE2("error-code = %d\n", GetLastError());
25790       getReadLock(pFile);
25791     }
25792   }
25793
25794   /* If we are holding a PENDING lock that ought to be released, then
25795   ** release it now.
25796   */
25797   if( gotPendingLock && locktype==SHARED_LOCK ){
25798     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
25799   }
25800
25801   /* Update the state of the lock has held in the file descriptor then
25802   ** return the appropriate result code.
25803   */
25804   if( res ){
25805     rc = SQLITE_OK;
25806   }else{
25807     OSTRACE4("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
25808            locktype, newLocktype);
25809     rc = SQLITE_BUSY;
25810   }
25811   pFile->locktype = newLocktype;
25812   return rc;
25813 }
25814
25815 /*
25816 ** This routine checks if there is a RESERVED lock held on the specified
25817 ** file by this or any other process. If such a lock is held, return
25818 ** non-zero, otherwise zero.
25819 */
25820 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
25821   int rc;
25822   winFile *pFile = (winFile*)id;
25823   assert( pFile!=0 );
25824   if( pFile->locktype>=RESERVED_LOCK ){
25825     rc = 1;
25826     OSTRACE3("TEST WR-LOCK %d %d (local)\n", pFile->h, rc);
25827   }else{
25828     rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
25829     if( rc ){
25830       UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
25831     }
25832     rc = !rc;
25833     OSTRACE3("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc);
25834   }
25835   *pResOut = rc;
25836   return SQLITE_OK;
25837 }
25838
25839 /*
25840 ** Lower the locking level on file descriptor id to locktype.  locktype
25841 ** must be either NO_LOCK or SHARED_LOCK.
25842 **
25843 ** If the locking level of the file descriptor is already at or below
25844 ** the requested locking level, this routine is a no-op.
25845 **
25846 ** It is not possible for this routine to fail if the second argument
25847 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
25848 ** might return SQLITE_IOERR;
25849 */
25850 static int winUnlock(sqlite3_file *id, int locktype){
25851   int type;
25852   winFile *pFile = (winFile*)id;
25853   int rc = SQLITE_OK;
25854   assert( pFile!=0 );
25855   assert( locktype<=SHARED_LOCK );
25856   OSTRACE5("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
25857           pFile->locktype, pFile->sharedLockByte);
25858   type = pFile->locktype;
25859   if( type>=EXCLUSIVE_LOCK ){
25860     UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
25861     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
25862       /* This should never happen.  We should always be able to
25863       ** reacquire the read lock */
25864       rc = SQLITE_IOERR_UNLOCK;
25865     }
25866   }
25867   if( type>=RESERVED_LOCK ){
25868     UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
25869   }
25870   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
25871     unlockReadLock(pFile);
25872   }
25873   if( type>=PENDING_LOCK ){
25874     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
25875   }
25876   pFile->locktype = locktype;
25877   return rc;
25878 }
25879
25880 /*
25881 ** Control and query of the open file handle.
25882 */
25883 static int winFileControl(sqlite3_file *id, int op, void *pArg){
25884   switch( op ){
25885     case SQLITE_FCNTL_LOCKSTATE: {
25886       *(int*)pArg = ((winFile*)id)->locktype;
25887       return SQLITE_OK;
25888     }
25889   }
25890   return SQLITE_ERROR;
25891 }
25892
25893 /*
25894 ** Return the sector size in bytes of the underlying block device for
25895 ** the specified file. This is almost always 512 bytes, but may be
25896 ** larger for some devices.
25897 **
25898 ** SQLite code assumes this function cannot fail. It also assumes that
25899 ** if two files are created in the same file-system directory (i.e.
25900 ** a database and its journal file) that the sector size will be the
25901 ** same for both.
25902 */
25903 static int winSectorSize(sqlite3_file *id){
25904   return SQLITE_DEFAULT_SECTOR_SIZE;
25905 }
25906
25907 /*
25908 ** Return a vector of device characteristics.
25909 */
25910 static int winDeviceCharacteristics(sqlite3_file *id){
25911   return 0;
25912 }
25913
25914 /*
25915 ** This vector defines all the methods that can operate on an
25916 ** sqlite3_file for win32.
25917 */
25918 static const sqlite3_io_methods winIoMethod = {
25919   1,                        /* iVersion */
25920   winClose,
25921   winRead,
25922   winWrite,
25923   winTruncate,
25924   winSync,
25925   winFileSize,
25926   winLock,
25927   winUnlock,
25928   winCheckReservedLock,
25929   winFileControl,
25930   winSectorSize,
25931   winDeviceCharacteristics
25932 };
25933
25934 /***************************************************************************
25935 ** Here ends the I/O methods that form the sqlite3_io_methods object.
25936 **
25937 ** The next block of code implements the VFS methods.
25938 ****************************************************************************/
25939
25940 /*
25941 ** Convert a UTF-8 filename into whatever form the underlying
25942 ** operating system wants filenames in.  Space to hold the result
25943 ** is obtained from malloc and must be freed by the calling
25944 ** function.
25945 */
25946 static void *convertUtf8Filename(const char *zFilename){
25947   void *zConverted = 0;
25948   if( isNT() ){
25949     zConverted = utf8ToUnicode(zFilename);
25950   }else{
25951     zConverted = utf8ToMbcs(zFilename);
25952   }
25953   /* caller will handle out of memory */
25954   return zConverted;
25955 }
25956
25957 /*
25958 ** Create a temporary file name in zBuf.  zBuf must be big enough to
25959 ** hold at pVfs->mxPathname characters.
25960 */
25961 static int getTempname(int nBuf, char *zBuf){
25962   static char zChars[] =
25963     "abcdefghijklmnopqrstuvwxyz"
25964     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
25965     "0123456789";
25966   size_t i, j;
25967   char zTempPath[MAX_PATH+1];
25968   if( sqlite3_temp_directory ){
25969     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
25970   }else if( isNT() ){
25971     char *zMulti;
25972     WCHAR zWidePath[MAX_PATH];
25973     GetTempPathW(MAX_PATH-30, zWidePath);
25974     zMulti = unicodeToUtf8(zWidePath);
25975     if( zMulti ){
25976       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
25977       free(zMulti);
25978     }else{
25979       return SQLITE_NOMEM;
25980     }
25981   }else{
25982     char *zUtf8;
25983     char zMbcsPath[MAX_PATH];
25984     GetTempPathA(MAX_PATH-30, zMbcsPath);
25985     zUtf8 = mbcsToUtf8(zMbcsPath);
25986     if( zUtf8 ){
25987       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
25988       free(zUtf8);
25989     }else{
25990       return SQLITE_NOMEM;
25991     }
25992   }
25993   for(i=strlen(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
25994   zTempPath[i] = 0;
25995   sqlite3_snprintf(nBuf-30, zBuf,
25996                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
25997   j = strlen(zBuf);
25998   sqlite3_randomness(20, &zBuf[j]);
25999   for(i=0; i<20; i++, j++){
26000     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
26001   }
26002   zBuf[j] = 0;
26003   OSTRACE2("TEMP FILENAME: %s\n", zBuf);
26004   return SQLITE_OK; 
26005 }
26006
26007 /*
26008 ** The return value of getLastErrorMsg
26009 ** is zero if the error message fits in the buffer, or non-zero
26010 ** otherwise (if the message was truncated).
26011 */
26012 static int getLastErrorMsg(int nBuf, char *zBuf){
26013   DWORD error = GetLastError();
26014
26015 #if SQLITE_OS_WINCE
26016   sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
26017 #else
26018   /* FormatMessage returns 0 on failure.  Otherwise it
26019   ** returns the number of TCHARs written to the output
26020   ** buffer, excluding the terminating null char.
26021   */
26022   if (!FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
26023                       NULL,
26024                       error,
26025                       0,
26026                       zBuf,
26027                       nBuf-1,
26028                       0))
26029   {
26030     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
26031   }
26032 #endif
26033
26034   return 0;
26035 }
26036
26037
26038 /*
26039 ** Open a file.
26040 */
26041 static int winOpen(
26042   sqlite3_vfs *pVfs,        /* Not used */
26043   const char *zName,        /* Name of the file (UTF-8) */
26044   sqlite3_file *id,         /* Write the SQLite file handle here */
26045   int flags,                /* Open mode flags */
26046   int *pOutFlags            /* Status return flags */
26047 ){
26048   HANDLE h;
26049   DWORD dwDesiredAccess;
26050   DWORD dwShareMode;
26051   DWORD dwCreationDisposition;
26052   DWORD dwFlagsAndAttributes = 0;
26053   int isTemp;
26054   winFile *pFile = (winFile*)id;
26055   void *zConverted;                 /* Filename in OS encoding */
26056   const char *zUtf8Name = zName;    /* Filename in UTF-8 encoding */
26057   char zTmpname[MAX_PATH+1];        /* Buffer used to create temp filename */
26058
26059   /* If the second argument to this function is NULL, generate a 
26060   ** temporary file name to use 
26061   */
26062   if( !zUtf8Name ){
26063     int rc = getTempname(MAX_PATH+1, zTmpname);
26064     if( rc!=SQLITE_OK ){
26065       return rc;
26066     }
26067     zUtf8Name = zTmpname;
26068   }
26069
26070   /* Convert the filename to the system encoding. */
26071   zConverted = convertUtf8Filename(zUtf8Name);
26072   if( zConverted==0 ){
26073     return SQLITE_NOMEM;
26074   }
26075
26076   if( flags & SQLITE_OPEN_READWRITE ){
26077     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
26078   }else{
26079     dwDesiredAccess = GENERIC_READ;
26080   }
26081   if( flags & SQLITE_OPEN_CREATE ){
26082     dwCreationDisposition = OPEN_ALWAYS;
26083   }else{
26084     dwCreationDisposition = OPEN_EXISTING;
26085   }
26086   if( flags & SQLITE_OPEN_MAIN_DB ){
26087     dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
26088   }else{
26089     dwShareMode = 0;
26090   }
26091   if( flags & SQLITE_OPEN_DELETEONCLOSE ){
26092 #if SQLITE_OS_WINCE
26093     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
26094 #else
26095     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
26096                                | FILE_ATTRIBUTE_HIDDEN
26097                                | FILE_FLAG_DELETE_ON_CLOSE;
26098 #endif
26099     isTemp = 1;
26100   }else{
26101     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
26102     isTemp = 0;
26103   }
26104   /* Reports from the internet are that performance is always
26105   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
26106   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
26107   if( isNT() ){
26108     h = CreateFileW((WCHAR*)zConverted,
26109        dwDesiredAccess,
26110        dwShareMode,
26111        NULL,
26112        dwCreationDisposition,
26113        dwFlagsAndAttributes,
26114        NULL
26115     );
26116   }else{
26117     h = CreateFileA((char*)zConverted,
26118        dwDesiredAccess,
26119        dwShareMode,
26120        NULL,
26121        dwCreationDisposition,
26122        dwFlagsAndAttributes,
26123        NULL
26124     );
26125   }
26126   if( h==INVALID_HANDLE_VALUE ){
26127     free(zConverted);
26128     if( flags & SQLITE_OPEN_READWRITE ){
26129       return winOpen(0, zName, id, 
26130              ((flags|SQLITE_OPEN_READONLY)&~SQLITE_OPEN_READWRITE), pOutFlags);
26131     }else{
26132       return SQLITE_CANTOPEN;
26133     }
26134   }
26135   if( pOutFlags ){
26136     if( flags & SQLITE_OPEN_READWRITE ){
26137       *pOutFlags = SQLITE_OPEN_READWRITE;
26138     }else{
26139       *pOutFlags = SQLITE_OPEN_READONLY;
26140     }
26141   }
26142   memset(pFile, 0, sizeof(*pFile));
26143   pFile->pMethod = &winIoMethod;
26144   pFile->h = h;
26145 #if SQLITE_OS_WINCE
26146   if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
26147                (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)
26148        && !winceCreateLock(zName, pFile)
26149   ){
26150     CloseHandle(h);
26151     free(zConverted);
26152     return SQLITE_CANTOPEN;
26153   }
26154   if( isTemp ){
26155     pFile->zDeleteOnClose = zConverted;
26156   }else
26157 #endif
26158   {
26159     free(zConverted);
26160   }
26161   OpenCounter(+1);
26162   return SQLITE_OK;
26163 }
26164
26165 /*
26166 ** Delete the named file.
26167 **
26168 ** Note that windows does not allow a file to be deleted if some other
26169 ** process has it open.  Sometimes a virus scanner or indexing program
26170 ** will open a journal file shortly after it is created in order to do
26171 ** whatever it does.  While this other process is holding the
26172 ** file open, we will be unable to delete it.  To work around this
26173 ** problem, we delay 100 milliseconds and try to delete again.  Up
26174 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
26175 ** up and returning an error.
26176 */
26177 #define MX_DELETION_ATTEMPTS 5
26178 static int winDelete(
26179   sqlite3_vfs *pVfs,          /* Not used on win32 */
26180   const char *zFilename,      /* Name of file to delete */
26181   int syncDir                 /* Not used on win32 */
26182 ){
26183   int cnt = 0;
26184   int rc;
26185   DWORD error;
26186   void *zConverted = convertUtf8Filename(zFilename);
26187   if( zConverted==0 ){
26188     return SQLITE_NOMEM;
26189   }
26190   SimulateIOError(return SQLITE_IOERR_DELETE);
26191   if( isNT() ){
26192     do{
26193       DeleteFileW(zConverted);
26194     }while(   (   ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
26195                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
26196            && (cnt++ < MX_DELETION_ATTEMPTS)
26197            && (Sleep(100), 1) );
26198   }else{
26199     do{
26200       DeleteFileA(zConverted);
26201     }while(   (   ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
26202                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
26203            && (cnt++ < MX_DELETION_ATTEMPTS)
26204            && (Sleep(100), 1) );
26205   }
26206   free(zConverted);
26207   OSTRACE2("DELETE \"%s\"\n", zFilename);
26208   return (   (rc==INVALID_FILE_ATTRIBUTES) 
26209           && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
26210 }
26211
26212 /*
26213 ** Check the existance and status of a file.
26214 */
26215 static int winAccess(
26216   sqlite3_vfs *pVfs,         /* Not used on win32 */
26217   const char *zFilename,     /* Name of file to check */
26218   int flags,                 /* Type of test to make on this file */
26219   int *pResOut               /* OUT: Result */
26220 ){
26221   DWORD attr;
26222   int rc;
26223   void *zConverted = convertUtf8Filename(zFilename);
26224   if( zConverted==0 ){
26225     return SQLITE_NOMEM;
26226   }
26227   if( isNT() ){
26228     attr = GetFileAttributesW((WCHAR*)zConverted);
26229   }else{
26230     attr = GetFileAttributesA((char*)zConverted);
26231   }
26232   free(zConverted);
26233   switch( flags ){
26234     case SQLITE_ACCESS_READ:
26235     case SQLITE_ACCESS_EXISTS:
26236       rc = attr!=INVALID_FILE_ATTRIBUTES;
26237       break;
26238     case SQLITE_ACCESS_READWRITE:
26239       rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
26240       break;
26241     default:
26242       assert(!"Invalid flags argument");
26243   }
26244   *pResOut = rc;
26245   return SQLITE_OK;
26246 }
26247
26248
26249 /*
26250 ** Turn a relative pathname into a full pathname.  Write the full
26251 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
26252 ** bytes in size.
26253 */
26254 static int winFullPathname(
26255   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
26256   const char *zRelative,        /* Possibly relative input path */
26257   int nFull,                    /* Size of output buffer in bytes */
26258   char *zFull                   /* Output buffer */
26259 ){
26260
26261 #if defined(__CYGWIN__)
26262   cygwin_conv_to_full_win32_path(zRelative, zFull);
26263   return SQLITE_OK;
26264 #endif
26265
26266 #if SQLITE_OS_WINCE
26267   /* WinCE has no concept of a relative pathname, or so I am told. */
26268   sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
26269   return SQLITE_OK;
26270 #endif
26271
26272 #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
26273   int nByte;
26274   void *zConverted;
26275   char *zOut;
26276   zConverted = convertUtf8Filename(zRelative);
26277   if( isNT() ){
26278     WCHAR *zTemp;
26279     nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
26280     zTemp = malloc( nByte*sizeof(zTemp[0]) );
26281     if( zTemp==0 ){
26282       free(zConverted);
26283       return SQLITE_NOMEM;
26284     }
26285     GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
26286     free(zConverted);
26287     zOut = unicodeToUtf8(zTemp);
26288     free(zTemp);
26289   }else{
26290     char *zTemp;
26291     nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
26292     zTemp = malloc( nByte*sizeof(zTemp[0]) );
26293     if( zTemp==0 ){
26294       free(zConverted);
26295       return SQLITE_NOMEM;
26296     }
26297     GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
26298     free(zConverted);
26299     zOut = mbcsToUtf8(zTemp);
26300     free(zTemp);
26301   }
26302   if( zOut ){
26303     sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
26304     free(zOut);
26305     return SQLITE_OK;
26306   }else{
26307     return SQLITE_NOMEM;
26308   }
26309 #endif
26310 }
26311
26312 #ifndef SQLITE_OMIT_LOAD_EXTENSION
26313 /*
26314 ** Interfaces for opening a shared library, finding entry points
26315 ** within the shared library, and closing the shared library.
26316 */
26317 /*
26318 ** Interfaces for opening a shared library, finding entry points
26319 ** within the shared library, and closing the shared library.
26320 */
26321 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
26322   HANDLE h;
26323   void *zConverted = convertUtf8Filename(zFilename);
26324   if( zConverted==0 ){
26325     return 0;
26326   }
26327   if( isNT() ){
26328     h = LoadLibraryW((WCHAR*)zConverted);
26329   }else{
26330     h = LoadLibraryA((char*)zConverted);
26331   }
26332   free(zConverted);
26333   return (void*)h;
26334 }
26335 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
26336   getLastErrorMsg(nBuf, zBufOut);
26337 }
26338 void *winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
26339 #if SQLITE_OS_WINCE
26340   /* The GetProcAddressA() routine is only available on wince. */
26341   return GetProcAddressA((HANDLE)pHandle, zSymbol);
26342 #else
26343   /* All other windows platforms expect GetProcAddress() to take
26344   ** an Ansi string regardless of the _UNICODE setting */
26345   return GetProcAddress((HANDLE)pHandle, zSymbol);
26346 #endif
26347 }
26348 void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
26349   FreeLibrary((HANDLE)pHandle);
26350 }
26351 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
26352   #define winDlOpen  0
26353   #define winDlError 0
26354   #define winDlSym   0
26355   #define winDlClose 0
26356 #endif
26357
26358
26359 /*
26360 ** Write up to nBuf bytes of randomness into zBuf.
26361 */
26362 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
26363   int n = 0;
26364   if( sizeof(SYSTEMTIME)<=nBuf-n ){
26365     SYSTEMTIME x;
26366     GetSystemTime(&x);
26367     memcpy(&zBuf[n], &x, sizeof(x));
26368     n += sizeof(x);
26369   }
26370   if( sizeof(DWORD)<=nBuf-n ){
26371     DWORD pid = GetCurrentProcessId();
26372     memcpy(&zBuf[n], &pid, sizeof(pid));
26373     n += sizeof(pid);
26374   }
26375   if( sizeof(DWORD)<=nBuf-n ){
26376     DWORD cnt = GetTickCount();
26377     memcpy(&zBuf[n], &cnt, sizeof(cnt));
26378     n += sizeof(cnt);
26379   }
26380   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
26381     LARGE_INTEGER i;
26382     QueryPerformanceCounter(&i);
26383     memcpy(&zBuf[n], &i, sizeof(i));
26384     n += sizeof(i);
26385   }
26386   return n;
26387 }
26388
26389
26390 /*
26391 ** Sleep for a little while.  Return the amount of time slept.
26392 */
26393 static int winSleep(sqlite3_vfs *pVfs, int microsec){
26394   Sleep((microsec+999)/1000);
26395   return ((microsec+999)/1000)*1000;
26396 }
26397
26398 /*
26399 ** The following variable, if set to a non-zero value, becomes the result
26400 ** returned from sqlite3OsCurrentTime().  This is used for testing.
26401 */
26402 #ifdef SQLITE_TEST
26403 SQLITE_API int sqlite3_current_time = 0;
26404 #endif
26405
26406 /*
26407 ** Find the current time (in Universal Coordinated Time).  Write the
26408 ** current time and date as a Julian Day number into *prNow and
26409 ** return 0.  Return 1 if the time and date cannot be found.
26410 */
26411 int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
26412   FILETIME ft;
26413   /* FILETIME structure is a 64-bit value representing the number of 
26414      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
26415   */
26416   double now;
26417 #if SQLITE_OS_WINCE
26418   SYSTEMTIME time;
26419   GetSystemTime(&time);
26420   /* if SystemTimeToFileTime() fails, it returns zero. */
26421   if (!SystemTimeToFileTime(&time,&ft)){
26422     return 1;
26423   }
26424 #else
26425   GetSystemTimeAsFileTime( &ft );
26426 #endif
26427   now = ((double)ft.dwHighDateTime) * 4294967296.0; 
26428   *prNow = (now + ft.dwLowDateTime)/864000000000.0 + 2305813.5;
26429 #ifdef SQLITE_TEST
26430   if( sqlite3_current_time ){
26431     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
26432   }
26433 #endif
26434   return 0;
26435 }
26436
26437 /*
26438 ** The idea is that this function works like a combination of
26439 ** GetLastError() and FormatMessage() on windows (or errno and
26440 ** strerror_r() on unix). After an error is returned by an OS
26441 ** function, SQLite calls this function with zBuf pointing to
26442 ** a buffer of nBuf bytes. The OS layer should populate the
26443 ** buffer with a nul-terminated UTF-8 encoded error message
26444 ** describing the last IO error to have occured within the calling
26445 ** thread.
26446 **
26447 ** If the error message is too large for the supplied buffer,
26448 ** it should be truncated. The return value of xGetLastError
26449 ** is zero if the error message fits in the buffer, or non-zero
26450 ** otherwise (if the message was truncated). If non-zero is returned,
26451 ** then it is not necessary to include the nul-terminator character
26452 ** in the output buffer.
26453 **
26454 ** Not supplying an error message will have no adverse effect
26455 ** on SQLite. It is fine to have an implementation that never
26456 ** returns an error message:
26457 **
26458 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
26459 **     assert(zBuf[0]=='\0');
26460 **     return 0;
26461 **   }
26462 **
26463 ** However if an error message is supplied, it will be incorporated
26464 ** by sqlite into the error message available to the user using
26465 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
26466 */
26467 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
26468   return getLastErrorMsg(nBuf, zBuf);
26469 }
26470
26471 /*
26472 ** Initialize and deinitialize the operating system interface.
26473 */
26474 SQLITE_API int sqlite3_os_init(void){
26475   static sqlite3_vfs winVfs = {
26476     1,                 /* iVersion */
26477     sizeof(winFile),   /* szOsFile */
26478     MAX_PATH,          /* mxPathname */
26479     0,                 /* pNext */
26480     "win32",           /* zName */
26481     0,                 /* pAppData */
26482  
26483     winOpen,           /* xOpen */
26484     winDelete,         /* xDelete */
26485     winAccess,         /* xAccess */
26486     winFullPathname,   /* xFullPathname */
26487     winDlOpen,         /* xDlOpen */
26488     winDlError,        /* xDlError */
26489     winDlSym,          /* xDlSym */
26490     winDlClose,        /* xDlClose */
26491     winRandomness,     /* xRandomness */
26492     winSleep,          /* xSleep */
26493     winCurrentTime,    /* xCurrentTime */
26494     winGetLastError    /* xGetLastError */
26495   };
26496   sqlite3_vfs_register(&winVfs, 1);
26497   return SQLITE_OK; 
26498 }
26499 SQLITE_API int sqlite3_os_end(void){ 
26500   return SQLITE_OK;
26501 }
26502
26503 #endif /* SQLITE_OS_WIN */
26504
26505 /************** End of os_win.c **********************************************/
26506 /************** Begin file bitvec.c ******************************************/
26507 /*
26508 ** 2008 February 16
26509 **
26510 ** The author disclaims copyright to this source code.  In place of
26511 ** a legal notice, here is a blessing:
26512 **
26513 **    May you do good and not evil.
26514 **    May you find forgiveness for yourself and forgive others.
26515 **    May you share freely, never taking more than you give.
26516 **
26517 *************************************************************************
26518 ** This file implements an object that represents a fixed-length
26519 ** bitmap.  Bits are numbered starting with 1.
26520 **
26521 ** A bitmap is used to record what pages a database file have been
26522 ** journalled during a transaction.  Usually only a few pages are
26523 ** journalled.  So the bitmap is usually sparse and has low cardinality.
26524 ** But sometimes (for example when during a DROP of a large table) most
26525 ** or all of the pages get journalled.  In those cases, the bitmap becomes
26526 ** dense.  The algorithm needs to handle both cases well.
26527 **
26528 ** The size of the bitmap is fixed when the object is created.
26529 **
26530 ** All bits are clear when the bitmap is created.  Individual bits
26531 ** may be set or cleared one at a time.
26532 **
26533 ** Test operations are about 100 times more common that set operations.
26534 ** Clear operations are exceedingly rare.  There are usually between
26535 ** 5 and 500 set operations per Bitvec object, though the number of sets can
26536 ** sometimes grow into tens of thousands or larger.  The size of the
26537 ** Bitvec object is the number of pages in the database file at the
26538 ** start of a transaction, and is thus usually less than a few thousand,
26539 ** but can be as large as 2 billion for a really big database.
26540 **
26541 ** @(#) $Id: bitvec.c,v 1.6 2008/06/20 14:59:51 danielk1977 Exp $
26542 */
26543
26544 #define BITVEC_SZ        512
26545 /* Round the union size down to the nearest pointer boundary, since that's how 
26546 ** it will be aligned within the Bitvec struct. */
26547 #define BITVEC_USIZE     (((BITVEC_SZ-12)/sizeof(Bitvec*))*sizeof(Bitvec*))
26548 #define BITVEC_NCHAR     BITVEC_USIZE
26549 #define BITVEC_NBIT      (BITVEC_NCHAR*8)
26550 #define BITVEC_NINT      (BITVEC_USIZE/4)
26551 #define BITVEC_MXHASH    (BITVEC_NINT/2)
26552 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
26553
26554 #define BITVEC_HASH(X)   (((X)*37)%BITVEC_NINT)
26555
26556 /*
26557 ** A bitmap is an instance of the following structure.
26558 **
26559 ** This bitmap records the existance of zero or more bits
26560 ** with values between 1 and iSize, inclusive.
26561 **
26562 ** There are three possible representations of the bitmap.
26563 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
26564 ** bitmap.  The least significant bit is bit 1.
26565 **
26566 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
26567 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
26568 **
26569 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
26570 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
26571 ** handles up to iDivisor separate values of i.  apSub[0] holds
26572 ** values between 1 and iDivisor.  apSub[1] holds values between
26573 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
26574 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
26575 ** to hold deal with values between 1 and iDivisor.
26576 */
26577 struct Bitvec {
26578   u32 iSize;      /* Maximum bit index */
26579   u32 nSet;       /* Number of bits that are set */
26580   u32 iDivisor;   /* Number of bits handled by each apSub[] entry */
26581   union {
26582     u8 aBitmap[BITVEC_NCHAR];    /* Bitmap representation */
26583     u32 aHash[BITVEC_NINT];      /* Hash table representation */
26584     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
26585   } u;
26586 };
26587
26588 /*
26589 ** Create a new bitmap object able to handle bits between 0 and iSize,
26590 ** inclusive.  Return a pointer to the new object.  Return NULL if 
26591 ** malloc fails.
26592 */
26593 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
26594   Bitvec *p;
26595   assert( sizeof(*p)==BITVEC_SZ );
26596   p = sqlite3MallocZero( sizeof(*p) );
26597   if( p ){
26598     p->iSize = iSize;
26599   }
26600   return p;
26601 }
26602
26603 /*
26604 ** Check to see if the i-th bit is set.  Return true or false.
26605 ** If p is NULL (if the bitmap has not been created) or if
26606 ** i is out of range, then return false.
26607 */
26608 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
26609   if( p==0 ) return 0;
26610   if( i>p->iSize || i==0 ) return 0;
26611   if( p->iSize<=BITVEC_NBIT ){
26612     i--;
26613     return (p->u.aBitmap[i/8] & (1<<(i&7)))!=0;
26614   }
26615   if( p->iDivisor>0 ){
26616     u32 bin = (i-1)/p->iDivisor;
26617     i = (i-1)%p->iDivisor + 1;
26618     return sqlite3BitvecTest(p->u.apSub[bin], i);
26619   }else{
26620     u32 h = BITVEC_HASH(i);
26621     while( p->u.aHash[h] ){
26622       if( p->u.aHash[h]==i ) return 1;
26623       h++;
26624       if( h>=BITVEC_NINT ) h = 0;
26625     }
26626     return 0;
26627   }
26628 }
26629
26630 /*
26631 ** Set the i-th bit.  Return 0 on success and an error code if
26632 ** anything goes wrong.
26633 */
26634 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
26635   u32 h;
26636   assert( p!=0 );
26637   assert( i>0 );
26638   assert( i<=p->iSize );
26639   if( p->iSize<=BITVEC_NBIT ){
26640     i--;
26641     p->u.aBitmap[i/8] |= 1 << (i&7);
26642     return SQLITE_OK;
26643   }
26644   if( p->iDivisor ){
26645     u32 bin = (i-1)/p->iDivisor;
26646     i = (i-1)%p->iDivisor + 1;
26647     if( p->u.apSub[bin]==0 ){
26648       sqlite3BeginBenignMalloc();
26649       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
26650       sqlite3EndBenignMalloc();
26651       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
26652     }
26653     return sqlite3BitvecSet(p->u.apSub[bin], i);
26654   }
26655   h = BITVEC_HASH(i);
26656   while( p->u.aHash[h] ){
26657     if( p->u.aHash[h]==i ) return SQLITE_OK;
26658     h++;
26659     if( h==BITVEC_NINT ) h = 0;
26660   }
26661   p->nSet++;
26662   if( p->nSet>=BITVEC_MXHASH ){
26663     int j, rc;
26664     u32 aiValues[BITVEC_NINT];
26665     memcpy(aiValues, p->u.aHash, sizeof(aiValues));
26666     memset(p->u.apSub, 0, sizeof(p->u.apSub[0])*BITVEC_NPTR);
26667     p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
26668     rc = sqlite3BitvecSet(p, i);
26669     for(j=0; j<BITVEC_NINT; j++){
26670       if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
26671     }
26672     return rc;
26673   }
26674   p->u.aHash[h] = i;
26675   return SQLITE_OK;
26676 }
26677
26678 /*
26679 ** Clear the i-th bit.  Return 0 on success and an error code if
26680 ** anything goes wrong.
26681 */
26682 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i){
26683   assert( p!=0 );
26684   assert( i>0 );
26685   if( p->iSize<=BITVEC_NBIT ){
26686     i--;
26687     p->u.aBitmap[i/8] &= ~(1 << (i&7));
26688   }else if( p->iDivisor ){
26689     u32 bin = (i-1)/p->iDivisor;
26690     i = (i-1)%p->iDivisor + 1;
26691     if( p->u.apSub[bin] ){
26692       sqlite3BitvecClear(p->u.apSub[bin], i);
26693     }
26694   }else{
26695     int j;
26696     u32 aiValues[BITVEC_NINT];
26697     memcpy(aiValues, p->u.aHash, sizeof(aiValues));
26698     memset(p->u.aHash, 0, sizeof(p->u.aHash[0])*BITVEC_NINT);
26699     p->nSet = 0;
26700     for(j=0; j<BITVEC_NINT; j++){
26701       if( aiValues[j] && aiValues[j]!=i ){
26702         sqlite3BitvecSet(p, aiValues[j]);
26703       }
26704     }
26705   }
26706 }
26707
26708 /*
26709 ** Destroy a bitmap object.  Reclaim all memory used.
26710 */
26711 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
26712   if( p==0 ) return;
26713   if( p->iDivisor ){
26714     int i;
26715     for(i=0; i<BITVEC_NPTR; i++){
26716       sqlite3BitvecDestroy(p->u.apSub[i]);
26717     }
26718   }
26719   sqlite3_free(p);
26720 }
26721
26722 #ifndef SQLITE_OMIT_BUILTIN_TEST
26723 /*
26724 ** Let V[] be an array of unsigned characters sufficient to hold
26725 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
26726 ** Then the following macros can be used to set, clear, or test
26727 ** individual bits within V.
26728 */
26729 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
26730 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
26731 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
26732
26733 /*
26734 ** This routine runs an extensive test of the Bitvec code.
26735 **
26736 ** The input is an array of integers that acts as a program
26737 ** to test the Bitvec.  The integers are opcodes followed
26738 ** by 0, 1, or 3 operands, depending on the opcode.  Another
26739 ** opcode follows immediately after the last operand.
26740 **
26741 ** There are 6 opcodes numbered from 0 through 5.  0 is the
26742 ** "halt" opcode and causes the test to end.
26743 **
26744 **    0          Halt and return the number of errors
26745 **    1 N S X    Set N bits beginning with S and incrementing by X
26746 **    2 N S X    Clear N bits beginning with S and incrementing by X
26747 **    3 N        Set N randomly chosen bits
26748 **    4 N        Clear N randomly chosen bits
26749 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
26750 **
26751 ** The opcodes 1 through 4 perform set and clear operations are performed
26752 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
26753 ** Opcode 5 works on the linear array only, not on the Bitvec.
26754 ** Opcode 5 is used to deliberately induce a fault in order to
26755 ** confirm that error detection works.
26756 **
26757 ** At the conclusion of the test the linear array is compared
26758 ** against the Bitvec object.  If there are any differences,
26759 ** an error is returned.  If they are the same, zero is returned.
26760 **
26761 ** If a memory allocation error occurs, return -1.
26762 */
26763 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
26764   Bitvec *pBitvec = 0;
26765   unsigned char *pV = 0;
26766   int rc = -1;
26767   int i, nx, pc, op;
26768
26769   /* Allocate the Bitvec to be tested and a linear array of
26770   ** bits to act as the reference */
26771   pBitvec = sqlite3BitvecCreate( sz );
26772   pV = sqlite3_malloc( (sz+7)/8 + 1 );
26773   if( pBitvec==0 || pV==0 ) goto bitvec_end;
26774   memset(pV, 0, (sz+7)/8 + 1);
26775
26776   /* Run the program */
26777   pc = 0;
26778   while( (op = aOp[pc])!=0 ){
26779     switch( op ){
26780       case 1:
26781       case 2:
26782       case 5: {
26783         nx = 4;
26784         i = aOp[pc+2] - 1;
26785         aOp[pc+2] += aOp[pc+3];
26786         break;
26787       }
26788       case 3:
26789       case 4: 
26790       default: {
26791         nx = 2;
26792         sqlite3_randomness(sizeof(i), &i);
26793         break;
26794       }
26795     }
26796     if( (--aOp[pc+1]) > 0 ) nx = 0;
26797     pc += nx;
26798     i = (i & 0x7fffffff)%sz;
26799     if( (op & 1)!=0 ){
26800       SETBIT(pV, (i+1));
26801       if( op!=5 ){
26802         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
26803       }
26804     }else{
26805       CLEARBIT(pV, (i+1));
26806       sqlite3BitvecClear(pBitvec, i+1);
26807     }
26808   }
26809
26810   /* Test to make sure the linear array exactly matches the
26811   ** Bitvec object.  Start with the assumption that they do
26812   ** match (rc==0).  Change rc to non-zero if a discrepancy
26813   ** is found.
26814   */
26815   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
26816           + sqlite3BitvecTest(pBitvec, 0);
26817   for(i=1; i<=sz; i++){
26818     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
26819       rc = i;
26820       break;
26821     }
26822   }
26823
26824   /* Free allocated structure */
26825 bitvec_end:
26826   sqlite3_free(pV);
26827   sqlite3BitvecDestroy(pBitvec);
26828   return rc;
26829 }
26830 #endif /* SQLITE_OMIT_BUILTIN_TEST */
26831
26832 /************** End of bitvec.c **********************************************/
26833 /************** Begin file pcache.c ******************************************/
26834 /*
26835 ** 2008 August 05
26836 **
26837 ** The author disclaims copyright to this source code.  In place of
26838 ** a legal notice, here is a blessing:
26839 **
26840 **    May you do good and not evil.
26841 **    May you find forgiveness for yourself and forgive others.
26842 **    May you share freely, never taking more than you give.
26843 **
26844 *************************************************************************
26845 ** This file implements that page cache.
26846 **
26847 ** @(#) $Id: pcache.c,v 1.31 2008/09/21 15:14:04 drh Exp $
26848 */
26849
26850 /*
26851 ** A complete page cache is an instance of this structure.
26852 **
26853 ** A cache may only be deleted by its owner and while holding the
26854 ** SQLITE_MUTEX_STATUS_LRU mutex.
26855 */
26856 struct PCache {
26857   /*********************************************************************
26858   ** The first group of elements may be read or written at any time by
26859   ** the cache owner without holding the mutex.  No thread other than the
26860   ** cache owner is permitted to access these elements at any time.
26861   */
26862   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
26863   PgHdr *pSynced;                     /* Last synced page in dirty page list */
26864   int nRef;                           /* Number of pinned pages */
26865   int nPinned;                        /* Number of pinned and/or dirty pages */
26866   int nMax;                           /* Configured cache size */
26867   int nMin;                           /* Configured minimum cache size */
26868   /**********************************************************************
26869   ** The next group of elements are fixed when the cache is created and
26870   ** may not be changed afterwards.  These elements can read at any time by
26871   ** the cache owner or by any thread holding the the mutex.  Non-owner
26872   ** threads must hold the mutex when reading these elements to prevent
26873   ** the entire PCache object from being deleted during the read.
26874   */
26875   int szPage;                         /* Size of every page in this cache */
26876   int szExtra;                        /* Size of extra space for each page */
26877   int bPurgeable;                     /* True if pages are on backing store */
26878   void (*xDestroy)(PgHdr*);           /* Called when refcnt goes 1->0 */
26879   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
26880   void *pStress;                      /* Argument to xStress */
26881   /**********************************************************************
26882   ** The final group of elements can only be accessed while holding the
26883   ** mutex.  Both the cache owner and any other thread must hold the mutex
26884   ** to read or write any of these elements.
26885   */
26886   int nPage;                          /* Total number of pages in apHash */
26887   int nHash;                          /* Number of slots in apHash[] */
26888   PgHdr **apHash;                     /* Hash table for fast lookup by pgno */
26889   PgHdr *pClean;                      /* List of clean pages in use */
26890 };
26891
26892 /*
26893 ** Free slots in the page block allocator
26894 */
26895 typedef struct PgFreeslot PgFreeslot;
26896 struct PgFreeslot {
26897   PgFreeslot *pNext;  /* Next free slot */
26898 };
26899
26900 /*
26901 ** Global data for the page cache.
26902 */
26903 static SQLITE_WSD struct PCacheGlobal {
26904   int isInit;                         /* True when initialized */
26905   sqlite3_mutex *mutex;               /* static mutex MUTEX_STATIC_LRU */
26906
26907   int nMaxPage;                       /* Sum of nMaxPage for purgeable caches */
26908   int nMinPage;                       /* Sum of nMinPage for purgeable caches */
26909   int nCurrentPage;                   /* Number of purgeable pages allocated */
26910   PgHdr *pLruHead, *pLruTail;         /* LRU list of unused clean pgs */
26911
26912   /* Variables related to SQLITE_CONFIG_PAGECACHE settings. */
26913   int szSlot;                         /* Size of each free slot */
26914   void *pStart, *pEnd;                /* Bounds of pagecache malloc range */
26915   PgFreeslot *pFree;                  /* Free page blocks */
26916 } pcache = {0};
26917
26918 /*
26919 ** All code in this file should access the global pcache structure via the
26920 ** alias "pcache_g". This ensures that the WSD emulation is used when
26921 ** compiling for systems that do not support real WSD.
26922 */
26923 #define pcache_g (GLOBAL(struct PCacheGlobal, pcache))
26924
26925 /*
26926 ** All global variables used by this module (all of which are grouped 
26927 ** together in global structure "pcache" above) are protected by the static 
26928 ** SQLITE_MUTEX_STATIC_LRU mutex. A pointer to this mutex is stored in
26929 ** variable "pcache.mutex".
26930 **
26931 ** Some elements of the PCache and PgHdr structures are protected by the 
26932 ** SQLITE_MUTEX_STATUS_LRU mutex and other are not.  The protected
26933 ** elements are grouped at the end of the structures and are clearly
26934 ** marked.
26935 **
26936 ** Use the following macros must surround all access (read or write)
26937 ** of protected elements.  The mutex is not recursive and may not be
26938 ** entered more than once.  The pcacheMutexHeld() macro should only be
26939 ** used within an assert() to verify that the mutex is being held.
26940 */
26941 #define pcacheEnterMutex() sqlite3_mutex_enter(pcache_g.mutex)
26942 #define pcacheExitMutex()  sqlite3_mutex_leave(pcache_g.mutex)
26943 #define pcacheMutexHeld()  sqlite3_mutex_held(pcache_g.mutex)
26944
26945 /*
26946 ** Some of the assert() macros in this code are too expensive to run
26947 ** even during normal debugging.  Use them only rarely on long-running
26948 ** tests.  Enable the expensive asserts using the
26949 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
26950 */
26951 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
26952 # define expensive_assert(X)  assert(X)
26953 #else
26954 # define expensive_assert(X)
26955 #endif
26956
26957 /********************************** Linked List Management ********************/
26958
26959 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
26960 /*
26961 ** This routine verifies that the number of entries in the hash table
26962 ** is pCache->nPage.  This routine is used within assert() statements
26963 ** only and is therefore disabled during production builds.
26964 */
26965 static int pcacheCheckHashCount(PCache *pCache){
26966   int i;
26967   int nPage = 0;
26968   for(i=0; i<pCache->nHash; i++){
26969     PgHdr *p;
26970     for(p=pCache->apHash[i]; p; p=p->pNextHash){
26971       nPage++;
26972     }
26973   }
26974   assert( nPage==pCache->nPage );
26975   return 1;
26976 }
26977 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
26978
26979
26980 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
26981 /*
26982 ** Based on the current value of PCache.nRef and the contents of the
26983 ** PCache.pDirty list, return the expected value of the PCache.nPinned
26984 ** counter. This is only used in debugging builds, as follows:
26985 **
26986 **   expensive_assert( pCache->nPinned==pcachePinnedCount(pCache) );
26987 */
26988 static int pcachePinnedCount(PCache *pCache){
26989   PgHdr *p;
26990   int nPinned = pCache->nRef;
26991   for(p=pCache->pDirty; p; p=p->pNext){
26992     if( p->nRef==0 ){
26993       nPinned++;
26994     }
26995   }
26996   return nPinned;
26997 }
26998 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
26999
27000
27001 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
27002 /*
27003 ** Check that the pCache->pSynced variable is set correctly. If it
27004 ** is not, either fail an assert or return zero. Otherwise, return
27005 ** non-zero. This is only used in debugging builds, as follows:
27006 **
27007 **   expensive_assert( pcacheCheckSynced(pCache) );
27008 */
27009 static int pcacheCheckSynced(PCache *pCache){
27010   PgHdr *p = pCache->pDirtyTail;
27011   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pPrev){
27012     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
27013   }
27014   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
27015 }
27016 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
27017
27018
27019
27020 /*
27021 ** Remove a page from its hash table (PCache.apHash[]).
27022 */
27023 static void pcacheRemoveFromHash(PgHdr *pPage){
27024   assert( pcacheMutexHeld() );
27025   if( pPage->pPrevHash ){
27026     pPage->pPrevHash->pNextHash = pPage->pNextHash;
27027   }else{
27028     PCache *pCache = pPage->pCache;
27029     u32 h = pPage->pgno % pCache->nHash;
27030     assert( pCache->apHash[h]==pPage );
27031     pCache->apHash[h] = pPage->pNextHash;
27032   }
27033   if( pPage->pNextHash ){
27034     pPage->pNextHash->pPrevHash = pPage->pPrevHash;
27035   }
27036   pPage->pCache->nPage--;
27037   expensive_assert( pcacheCheckHashCount(pPage->pCache) );
27038 }
27039
27040 /*
27041 ** Insert a page into the hash table
27042 **
27043 ** The mutex must be held by the caller.
27044 */
27045 static void pcacheAddToHash(PgHdr *pPage){
27046   PCache *pCache = pPage->pCache;
27047   u32 h = pPage->pgno % pCache->nHash;
27048   assert( pcacheMutexHeld() );
27049   pPage->pNextHash = pCache->apHash[h];
27050   pPage->pPrevHash = 0;
27051   if( pCache->apHash[h] ){
27052     pCache->apHash[h]->pPrevHash = pPage;
27053   }
27054   pCache->apHash[h] = pPage;
27055   pCache->nPage++;
27056   expensive_assert( pcacheCheckHashCount(pCache) );
27057 }
27058
27059 /*
27060 ** Attempt to increase the size the hash table to contain
27061 ** at least nHash buckets.
27062 */
27063 static int pcacheResizeHash(PCache *pCache, int nHash){
27064   PgHdr *p;
27065   PgHdr **pNew;
27066   assert( pcacheMutexHeld() );
27067 #ifdef SQLITE_MALLOC_SOFT_LIMIT
27068   if( nHash*sizeof(PgHdr*)>SQLITE_MALLOC_SOFT_LIMIT ){
27069     nHash = SQLITE_MALLOC_SOFT_LIMIT/sizeof(PgHdr *);
27070   }
27071 #endif
27072   pcacheExitMutex();
27073   pNew = (PgHdr **)sqlite3Malloc(sizeof(PgHdr*)*nHash);
27074   pcacheEnterMutex();
27075   if( !pNew ){
27076     return SQLITE_NOMEM;
27077   }
27078   memset(pNew, 0, sizeof(PgHdr *)*nHash);
27079   sqlite3_free(pCache->apHash);
27080   pCache->apHash = pNew;
27081   pCache->nHash = nHash;
27082   pCache->nPage = 0;
27083  
27084   for(p=pCache->pClean; p; p=p->pNext){
27085     pcacheAddToHash(p);
27086   }
27087   for(p=pCache->pDirty; p; p=p->pNext){
27088     pcacheAddToHash(p);
27089   }
27090   return SQLITE_OK;
27091 }
27092
27093 /*
27094 ** Remove a page from a linked list that is headed by *ppHead.
27095 ** *ppHead is either PCache.pClean or PCache.pDirty.
27096 */
27097 static void pcacheRemoveFromList(PgHdr **ppHead, PgHdr *pPage){
27098   int isDirtyList = (ppHead==&pPage->pCache->pDirty);
27099   assert( ppHead==&pPage->pCache->pClean || ppHead==&pPage->pCache->pDirty );
27100   assert( pcacheMutexHeld() || ppHead!=&pPage->pCache->pClean );
27101
27102   if( pPage->pPrev ){
27103     pPage->pPrev->pNext = pPage->pNext;
27104   }else{
27105     assert( *ppHead==pPage );
27106     *ppHead = pPage->pNext;
27107   }
27108   if( pPage->pNext ){
27109     pPage->pNext->pPrev = pPage->pPrev;
27110   }
27111
27112   if( isDirtyList ){
27113     PCache *pCache = pPage->pCache;
27114     assert( pPage->pNext || pCache->pDirtyTail==pPage );
27115     if( !pPage->pNext ){
27116       pCache->pDirtyTail = pPage->pPrev;
27117     }
27118     if( pCache->pSynced==pPage ){
27119       PgHdr *pSynced = pPage->pPrev;
27120       while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
27121         pSynced = pSynced->pPrev;
27122       }
27123       pCache->pSynced = pSynced;
27124     }
27125   }
27126 }
27127
27128 /*
27129 ** Add a page from a linked list that is headed by *ppHead.
27130 ** *ppHead is either PCache.pClean or PCache.pDirty.
27131 */
27132 static void pcacheAddToList(PgHdr **ppHead, PgHdr *pPage){
27133   int isDirtyList = (ppHead==&pPage->pCache->pDirty);
27134   assert( ppHead==&pPage->pCache->pClean || ppHead==&pPage->pCache->pDirty );
27135
27136   if( (*ppHead) ){
27137     (*ppHead)->pPrev = pPage;
27138   }
27139   pPage->pNext = *ppHead;
27140   pPage->pPrev = 0;
27141   *ppHead = pPage;
27142
27143   if( isDirtyList ){
27144     PCache *pCache = pPage->pCache;
27145     if( !pCache->pDirtyTail ){
27146       assert( pPage->pNext==0 );
27147       pCache->pDirtyTail = pPage;
27148     }
27149     if( !pCache->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
27150       pCache->pSynced = pPage;
27151     }
27152   }
27153 }
27154
27155 /*
27156 ** Remove a page from the global LRU list
27157 */
27158 static void pcacheRemoveFromLruList(PgHdr *pPage){
27159   assert( sqlite3_mutex_held(pcache_g.mutex) );
27160   assert( (pPage->flags&PGHDR_DIRTY)==0 );
27161   if( pPage->pCache->bPurgeable==0 ) return;
27162   if( pPage->pNextLru ){
27163     assert( pcache_g.pLruTail!=pPage );
27164     pPage->pNextLru->pPrevLru = pPage->pPrevLru;
27165   }else{
27166     assert( pcache_g.pLruTail==pPage );
27167     pcache_g.pLruTail = pPage->pPrevLru;
27168   }
27169   if( pPage->pPrevLru ){
27170     assert( pcache_g.pLruHead!=pPage );
27171     pPage->pPrevLru->pNextLru = pPage->pNextLru;
27172   }else{
27173     assert( pcache_g.pLruHead==pPage );
27174     pcache_g.pLruHead = pPage->pNextLru;
27175   }
27176 }
27177
27178 /*
27179 ** Add a page to the global LRU list.  The page is normally added
27180 ** to the front of the list so that it will be the last page recycled.
27181 ** However, if the PGHDR_REUSE_UNLIKELY bit is set, the page is added
27182 ** to the end of the LRU list so that it will be the next to be recycled.
27183 */
27184 static void pcacheAddToLruList(PgHdr *pPage){
27185   assert( sqlite3_mutex_held(pcache_g.mutex) );
27186   assert( (pPage->flags&PGHDR_DIRTY)==0 );
27187   if( pPage->pCache->bPurgeable==0 ) return;
27188   if( pcache_g.pLruTail && (pPage->flags & PGHDR_REUSE_UNLIKELY)!=0 ){
27189     /* If reuse is unlikely.  Put the page at the end of the LRU list
27190     ** where it will be recycled sooner rather than later. 
27191     */
27192     assert( pcache_g.pLruHead );
27193     pPage->pNextLru = 0;
27194     pPage->pPrevLru = pcache_g.pLruTail;
27195     pcache_g.pLruTail->pNextLru = pPage;
27196     pcache_g.pLruTail = pPage;
27197     pPage->flags &= ~PGHDR_REUSE_UNLIKELY;
27198   }else{
27199     /* If reuse is possible. the page goes at the beginning of the LRU
27200     ** list so that it will be the last to be recycled.
27201     */
27202     if( pcache_g.pLruHead ){
27203       pcache_g.pLruHead->pPrevLru = pPage;
27204     }
27205     pPage->pNextLru = pcache_g.pLruHead;
27206     pcache_g.pLruHead = pPage;
27207     pPage->pPrevLru = 0;
27208     if( pcache_g.pLruTail==0 ){
27209       pcache_g.pLruTail = pPage;
27210     }
27211   }
27212 }
27213
27214 /*********************************************** Memory Allocation ***********
27215 **
27216 ** Initialize the page cache memory pool.
27217 **
27218 ** This must be called at start-time when no page cache lines are
27219 ** checked out. This function is not threadsafe.
27220 */
27221 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
27222   PgFreeslot *p;
27223   sz &= ~7;
27224   pcache_g.szSlot = sz;
27225   pcache_g.pStart = pBuf;
27226   pcache_g.pFree = 0;
27227   while( n-- ){
27228     p = (PgFreeslot*)pBuf;
27229     p->pNext = pcache_g.pFree;
27230     pcache_g.pFree = p;
27231     pBuf = (void*)&((char*)pBuf)[sz];
27232   }
27233   pcache_g.pEnd = pBuf;
27234 }
27235
27236 /*
27237 ** Allocate a page cache line.  Look in the page cache memory pool first
27238 ** and use an element from it first if available.  If nothing is available
27239 ** in the page cache memory pool, go to the general purpose memory allocator.
27240 */
27241 static void *pcacheMalloc(int sz, PCache *pCache){
27242   assert( sqlite3_mutex_held(pcache_g.mutex) );
27243   if( sz<=pcache_g.szSlot && pcache_g.pFree ){
27244     PgFreeslot *p = pcache_g.pFree;
27245     pcache_g.pFree = p->pNext;
27246     sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, sz);
27247     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
27248     return (void*)p;
27249   }else{
27250     void *p;
27251
27252     /* Allocate a new buffer using sqlite3Malloc. Before doing so, exit the
27253     ** global pcache mutex and unlock the pager-cache object pCache. This is 
27254     ** so that if the attempt to allocate a new buffer causes the the 
27255     ** configured soft-heap-limit to be breached, it will be possible to
27256     ** reclaim memory from this pager-cache.
27257     */
27258     pcacheExitMutex();
27259     p = sqlite3Malloc(sz);
27260     pcacheEnterMutex();
27261
27262     if( p ){
27263       sz = sqlite3MallocSize(p);
27264       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
27265     }
27266     return p;
27267   }
27268 }
27269 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
27270   void *p;
27271   pcacheEnterMutex();
27272   p = pcacheMalloc(sz, 0);
27273   pcacheExitMutex();
27274   return p;
27275 }
27276
27277 /*
27278 ** Release a pager memory allocation
27279 */
27280 static void pcacheFree(void *p){
27281   assert( sqlite3_mutex_held(pcache_g.mutex) );
27282   if( p==0 ) return;
27283   if( p>=pcache_g.pStart && p<pcache_g.pEnd ){
27284     PgFreeslot *pSlot;
27285     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
27286     pSlot = (PgFreeslot*)p;
27287     pSlot->pNext = pcache_g.pFree;
27288     pcache_g.pFree = pSlot;
27289   }else{
27290     int iSize = sqlite3MallocSize(p);
27291     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
27292     sqlite3_free(p);
27293   }
27294 }
27295 SQLITE_PRIVATE void sqlite3PageFree(void *p){
27296   pcacheEnterMutex();
27297   pcacheFree(p);
27298   pcacheExitMutex();
27299 }
27300
27301 /*
27302 ** Allocate a new page.
27303 */
27304 static PgHdr *pcachePageAlloc(PCache *pCache){
27305   PgHdr *p;
27306   int sz = sizeof(*p) + pCache->szPage + pCache->szExtra;
27307   assert( sqlite3_mutex_held(pcache_g.mutex) );
27308   p = pcacheMalloc(sz, pCache);
27309   if( p==0 ) return 0;
27310   memset(p, 0, sizeof(PgHdr));
27311   p->pData = (void*)&p[1];
27312   p->pExtra = (void*)&((char*)p->pData)[pCache->szPage];
27313   if( pCache->bPurgeable ){
27314     pcache_g.nCurrentPage++;
27315   }
27316   return p;
27317 }
27318
27319 /*
27320 ** Deallocate a page
27321 */
27322 static void pcachePageFree(PgHdr *p){
27323   assert( sqlite3_mutex_held(pcache_g.mutex) );
27324   if( p->pCache->bPurgeable ){
27325     pcache_g.nCurrentPage--;
27326   }
27327   pcacheFree(p->apSave[0]);
27328   pcacheFree(p->apSave[1]);
27329   pcacheFree(p);
27330 }
27331
27332 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
27333 /*
27334 ** Return the number of bytes that will be returned to the heap when
27335 ** the argument is passed to pcachePageFree().
27336 */
27337 static int pcachePageSize(PgHdr *p){
27338   assert( sqlite3_mutex_held(pcache_g.mutex) );
27339   assert( !pcache_g.pStart );
27340   assert( p->apSave[0]==0 );
27341   assert( p->apSave[1]==0 );
27342   assert( p && p->pCache );
27343   return sqlite3MallocSize(p);
27344 }
27345 #endif
27346
27347 /*
27348 ** Attempt to 'recycle' a page from the global LRU list. Only clean,
27349 ** unreferenced pages from purgeable caches are eligible for recycling.
27350 **
27351 ** This function removes page pcache.pLruTail from the global LRU list,
27352 ** and from the hash-table and PCache.pClean list of the owner pcache.
27353 ** There should be no other references to the page.
27354 **
27355 ** A pointer to the recycled page is returned, or NULL if no page is
27356 ** eligible for recycling.
27357 */
27358 static PgHdr *pcacheRecyclePage(){
27359   PgHdr *p = 0;
27360   assert( sqlite3_mutex_held(pcache_g.mutex) );
27361
27362   if( (p=pcache_g.pLruTail) ){
27363     assert( (p->flags&PGHDR_DIRTY)==0 );
27364     pcacheRemoveFromLruList(p);
27365     pcacheRemoveFromHash(p);
27366     pcacheRemoveFromList(&p->pCache->pClean, p);
27367   }
27368
27369   return p;
27370 }
27371
27372 /*
27373 ** Obtain space for a page. Try to recycle an old page if the limit on the 
27374 ** number of pages has been reached. If the limit has not been reached or
27375 ** there are no pages eligible for recycling, allocate a new page.
27376 **
27377 ** Return a pointer to the new page, or NULL if an OOM condition occurs.
27378 */
27379 static int pcacheRecycleOrAlloc(PCache *pCache, PgHdr **ppPage){
27380   PgHdr *p = 0;
27381
27382   int szPage = pCache->szPage;
27383   int szExtra = pCache->szExtra;
27384
27385   assert( pcache_g.isInit );
27386   assert( sqlite3_mutex_held(pcache_g.mutex) );
27387
27388   *ppPage = 0;
27389
27390   /* If we have reached either the global or the local limit for 
27391   ** pinned+dirty pages, and there is at least one dirty page,
27392   ** invoke the xStress callback to cause a page to become clean.
27393   */
27394   expensive_assert( pCache->nPinned==pcachePinnedCount(pCache) );
27395   expensive_assert( pcacheCheckSynced(pCache) );
27396   if( pCache->xStress
27397    && pCache->pDirty
27398    && (pCache->nPinned>=(pcache_g.nMaxPage+pCache->nMin-pcache_g.nMinPage)
27399            || pCache->nPinned>=pCache->nMax)
27400   ){
27401     PgHdr *pPg;
27402     assert(pCache->pDirtyTail);
27403
27404     for(pPg=pCache->pSynced; 
27405         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 
27406         pPg=pPg->pPrev
27407     );
27408     if( !pPg ){
27409       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pPrev);
27410     }
27411     if( pPg ){
27412       int rc;
27413       pcacheExitMutex();
27414       rc = pCache->xStress(pCache->pStress, pPg);
27415       pcacheEnterMutex();
27416       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
27417         return rc;
27418       }
27419     }
27420   }
27421
27422   /* If either the local or the global page limit has been reached, 
27423   ** try to recycle a page. 
27424   */
27425   if( pCache->bPurgeable && (pCache->nPage>=pCache->nMax-1 ||
27426                              pcache_g.nCurrentPage>=pcache_g.nMaxPage) ){
27427     p = pcacheRecyclePage();
27428   }
27429
27430   /* If a page has been recycled but it is the wrong size, free it. */
27431   if( p && (p->pCache->szPage!=szPage || p->pCache->szPage!=szExtra) ){
27432     pcachePageFree(p);
27433     p = 0;
27434   }
27435
27436   if( !p ){
27437     p = pcachePageAlloc(pCache);
27438   }
27439
27440   *ppPage = p;
27441   return (p?SQLITE_OK:SQLITE_NOMEM);
27442 }
27443
27444 /*************************************************** General Interfaces ******
27445 **
27446 ** Initialize and shutdown the page cache subsystem. Neither of these 
27447 ** functions are threadsafe.
27448 */
27449 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
27450   assert( pcache_g.isInit==0 );
27451   memset(&pcache_g, 0, sizeof(pcache));
27452   if( sqlite3GlobalConfig.bCoreMutex ){
27453     /* No need to check the return value of sqlite3_mutex_alloc(). 
27454     ** Allocating a static mutex cannot fail.
27455     */
27456     pcache_g.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
27457   }
27458   pcache_g.isInit = 1;
27459   return SQLITE_OK;
27460 }
27461 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
27462   memset(&pcache_g, 0, sizeof(pcache));
27463 }
27464
27465 /*
27466 ** Return the size in bytes of a PCache object.
27467 */
27468 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
27469
27470 /*
27471 ** Create a new PCache object.  Storage space to hold the object
27472 ** has already been allocated and is passed in as the p pointer.
27473 */
27474 SQLITE_PRIVATE void sqlite3PcacheOpen(
27475   int szPage,                  /* Size of every page */
27476   int szExtra,                 /* Extra space associated with each page */
27477   int bPurgeable,              /* True if pages are on backing store */
27478   void (*xDestroy)(PgHdr*),    /* Called to destroy a page */
27479   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
27480   void *pStress,               /* Argument to xStress */
27481   PCache *p                    /* Preallocated space for the PCache */
27482 ){
27483   assert( pcache_g.isInit );
27484   memset(p, 0, sizeof(PCache));
27485   p->szPage = szPage;
27486   p->szExtra = szExtra;
27487   p->bPurgeable = bPurgeable;
27488   p->xDestroy = xDestroy;
27489   p->xStress = xStress;
27490   p->pStress = pStress;
27491   p->nMax = 100;
27492   p->nMin = 10;
27493
27494   pcacheEnterMutex();
27495   if( bPurgeable ){
27496     pcache_g.nMaxPage += p->nMax;
27497     pcache_g.nMinPage += p->nMin;
27498   }
27499
27500   pcacheExitMutex();
27501 }
27502
27503 /*
27504 ** Change the page size for PCache object.  This can only happen
27505 ** when the cache is empty.
27506 */
27507 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
27508   assert(pCache->nPage==0);
27509   pCache->szPage = szPage;
27510 }
27511
27512 /*
27513 ** Try to obtain a page from the cache.
27514 */
27515 SQLITE_PRIVATE int sqlite3PcacheFetch(
27516   PCache *pCache,       /* Obtain the page from this cache */
27517   Pgno pgno,            /* Page number to obtain */
27518   int createFlag,       /* If true, create page if it does not exist already */
27519   PgHdr **ppPage        /* Write the page here */
27520 ){
27521   int rc = SQLITE_OK;
27522   PgHdr *pPage = 0;
27523
27524   assert( pcache_g.isInit );
27525   assert( pCache!=0 );
27526   assert( pgno>0 );
27527   expensive_assert( pCache->nPinned==pcachePinnedCount(pCache) );
27528
27529   pcacheEnterMutex();
27530
27531   /* Search the hash table for the requested page. Exit early if it is found. */
27532   if( pCache->apHash ){
27533     u32 h = pgno % pCache->nHash;
27534     for(pPage=pCache->apHash[h]; pPage; pPage=pPage->pNextHash){
27535       if( pPage->pgno==pgno ){
27536         if( pPage->nRef==0 ){
27537           if( 0==(pPage->flags&PGHDR_DIRTY) ){
27538             pcacheRemoveFromLruList(pPage);
27539             pCache->nPinned++;
27540           }
27541           pCache->nRef++;
27542         }
27543         pPage->nRef++;
27544         break;
27545       }
27546     }
27547   }
27548
27549   if( !pPage && createFlag ){
27550     if( pCache->nHash<=pCache->nPage ){
27551       rc = pcacheResizeHash(pCache, pCache->nHash<256 ? 256 : pCache->nHash*2);
27552     }
27553     if( rc==SQLITE_OK ){
27554       rc = pcacheRecycleOrAlloc(pCache, &pPage);
27555     }
27556     if( rc==SQLITE_OK ){
27557       pPage->pPager = 0;
27558       pPage->flags = 0;
27559       pPage->pDirty = 0;
27560       pPage->pgno = pgno;
27561       pPage->pCache = pCache;
27562       pPage->nRef = 1;
27563       pCache->nRef++;
27564       pCache->nPinned++;
27565       pcacheAddToList(&pCache->pClean, pPage);
27566       pcacheAddToHash(pPage);
27567     }
27568   }
27569
27570   pcacheExitMutex();
27571
27572   *ppPage = pPage;
27573   expensive_assert( pCache->nPinned==pcachePinnedCount(pCache) );
27574   assert( pPage || !createFlag || rc!=SQLITE_OK );
27575   return rc;
27576 }
27577
27578 /*
27579 ** Dereference a page.  When the reference count reaches zero,
27580 ** move the page to the LRU list if it is clean.
27581 */
27582 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
27583   assert( p->nRef>0 );
27584   p->nRef--;
27585   if( p->nRef==0 ){
27586     PCache *pCache = p->pCache;
27587     if( p->pCache->xDestroy ){
27588       p->pCache->xDestroy(p);
27589     }
27590     pCache->nRef--;
27591     if( (p->flags&PGHDR_DIRTY)==0 ){
27592       pCache->nPinned--;
27593       pcacheEnterMutex();
27594       if( pcache_g.nCurrentPage>pcache_g.nMaxPage ){
27595         pcacheRemoveFromList(&pCache->pClean, p);
27596         pcacheRemoveFromHash(p);
27597         pcachePageFree(p);
27598       }else{
27599         pcacheAddToLruList(p);
27600       }
27601       pcacheExitMutex();
27602     }else{
27603       /* Move the page to the head of the caches dirty list. */
27604       pcacheRemoveFromList(&pCache->pDirty, p);
27605       pcacheAddToList(&pCache->pDirty, p);
27606     }
27607   }
27608 }
27609
27610 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
27611   assert(p->nRef>0);
27612   p->nRef++;
27613 }
27614
27615 /*
27616 ** Drop a page from the cache. There must be exactly one reference to the
27617 ** page. This function deletes that reference, so after it returns the
27618 ** page pointed to by p is invalid.
27619 */
27620 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
27621   PCache *pCache;
27622   assert( p->nRef==1 );
27623   assert( 0==(p->flags&PGHDR_DIRTY) );
27624   pCache = p->pCache;
27625   pCache->nRef--;
27626   pCache->nPinned--;
27627   pcacheEnterMutex();
27628   pcacheRemoveFromList(&pCache->pClean, p);
27629   pcacheRemoveFromHash(p);
27630   pcachePageFree(p);
27631   pcacheExitMutex();
27632 }
27633
27634 /*
27635 ** Make sure the page is marked as dirty.  If it isn't dirty already,
27636 ** make it so.
27637 */
27638 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
27639   PCache *pCache;
27640   p->flags &= ~PGHDR_DONT_WRITE;
27641   if( p->flags & PGHDR_DIRTY ) return;
27642   assert( (p->flags & PGHDR_DIRTY)==0 );
27643   assert( p->nRef>0 );
27644   pCache = p->pCache;
27645   pcacheEnterMutex();
27646   pcacheRemoveFromList(&pCache->pClean, p);
27647   pcacheAddToList(&pCache->pDirty, p);
27648   pcacheExitMutex();
27649   p->flags |= PGHDR_DIRTY;
27650 }
27651
27652 static void pcacheMakeClean(PgHdr *p){
27653   PCache *pCache = p->pCache;
27654   assert( p->apSave[0]==0 && p->apSave[1]==0 );
27655   assert( p->flags & PGHDR_DIRTY );
27656   pcacheRemoveFromList(&pCache->pDirty, p);
27657   pcacheAddToList(&pCache->pClean, p);
27658   p->flags &= ~PGHDR_DIRTY;
27659   if( p->nRef==0 ){
27660     pcacheAddToLruList(p);
27661     pCache->nPinned--;
27662   }
27663   expensive_assert( pCache->nPinned==pcachePinnedCount(pCache) );
27664 }
27665
27666 /*
27667 ** Make sure the page is marked as clean.  If it isn't clean already,
27668 ** make it so.
27669 */
27670 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
27671   if( (p->flags & PGHDR_DIRTY) ){
27672     pcacheEnterMutex();
27673     pcacheMakeClean(p);
27674     pcacheExitMutex();
27675   }
27676 }
27677
27678 /*
27679 ** Make every page in the cache clean.
27680 */
27681 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
27682   PgHdr *p;
27683   pcacheEnterMutex();
27684   while( (p = pCache->pDirty)!=0 ){
27685     assert( p->apSave[0]==0 && p->apSave[1]==0 );
27686     pcacheRemoveFromList(&pCache->pDirty, p);
27687     p->flags &= ~PGHDR_DIRTY;
27688     pcacheAddToList(&pCache->pClean, p);
27689     if( p->nRef==0 ){
27690       pcacheAddToLruList(p);
27691       pCache->nPinned--;
27692     }
27693   }
27694   sqlite3PcacheAssertFlags(pCache, 0, PGHDR_DIRTY);
27695   expensive_assert( pCache->nPinned==pcachePinnedCount(pCache) );
27696   pcacheExitMutex();
27697 }
27698
27699 /*
27700 ** Change the page number of page p to newPgno. If newPgno is 0, then the
27701 ** page object is added to the clean-list and the PGHDR_REUSE_UNLIKELY 
27702 ** flag set.
27703 */
27704 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
27705   assert( p->nRef>0 );
27706   pcacheEnterMutex();
27707   pcacheRemoveFromHash(p);
27708   p->pgno = newPgno;
27709   if( newPgno==0 ){
27710     pcacheFree(p->apSave[0]);
27711     pcacheFree(p->apSave[1]);
27712     p->apSave[0] = 0;
27713     p->apSave[1] = 0;
27714     if( (p->flags & PGHDR_DIRTY) ){
27715       pcacheMakeClean(p);
27716     }
27717     p->flags = PGHDR_REUSE_UNLIKELY;
27718   }
27719   pcacheAddToHash(p);
27720   pcacheExitMutex();
27721 }
27722
27723 /*
27724 ** Remove all content from a page cache
27725 */
27726 static void pcacheClear(PCache *pCache){
27727   PgHdr *p, *pNext;
27728   assert( sqlite3_mutex_held(pcache_g.mutex) );
27729   for(p=pCache->pClean; p; p=pNext){
27730     pNext = p->pNext;
27731     pcacheRemoveFromLruList(p);
27732     pcachePageFree(p);
27733   }
27734   for(p=pCache->pDirty; p; p=pNext){
27735     pNext = p->pNext;
27736     pcachePageFree(p);
27737   }
27738   pCache->pClean = 0;
27739   pCache->pDirty = 0;
27740   pCache->pDirtyTail = 0;
27741   pCache->nPage = 0;
27742   pCache->nPinned = 0;
27743   memset(pCache->apHash, 0, pCache->nHash*sizeof(pCache->apHash[0]));
27744 }
27745
27746
27747 /*
27748 ** Drop every cache entry whose page number is greater than "pgno".
27749 */
27750 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
27751   PgHdr *p, *pNext;
27752   PgHdr *pDirty = pCache->pDirty;
27753   pcacheEnterMutex();
27754   for(p=pCache->pClean; p||pDirty; p=pNext){
27755     if( !p ){
27756       p = pDirty;
27757       pDirty = 0;
27758     }
27759     pNext = p->pNext;
27760     if( p->pgno>pgno ){
27761       if( p->nRef==0 ){
27762         pcacheRemoveFromHash(p);
27763         if( p->flags&PGHDR_DIRTY ){
27764           pcacheRemoveFromList(&pCache->pDirty, p);
27765           pCache->nPinned--;
27766         }else{
27767           pcacheRemoveFromList(&pCache->pClean, p);
27768           pcacheRemoveFromLruList(p);
27769         }
27770         pcachePageFree(p);
27771       }else{
27772         /* If there are references to the page, it cannot be freed. In this
27773         ** case, zero the page content instead.
27774         */
27775         memset(p->pData, 0, pCache->szPage);
27776       }
27777     }
27778   }
27779   pcacheExitMutex();
27780 }
27781
27782 /*
27783 ** If there are currently more than pcache.nMaxPage pages allocated, try
27784 ** to recycle pages to reduce the number allocated to pcache.nMaxPage.
27785 */
27786 static void pcacheEnforceMaxPage(){
27787   PgHdr *p;
27788   assert( sqlite3_mutex_held(pcache_g.mutex) );
27789   while( pcache_g.nCurrentPage>pcache_g.nMaxPage && (p = pcacheRecyclePage()) ){
27790     pcachePageFree(p);
27791   }
27792 }
27793
27794 /*
27795 ** Close a cache.
27796 */
27797 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
27798   pcacheEnterMutex();
27799
27800   /* Free all the pages used by this pager and remove them from the LRU list. */
27801   pcacheClear(pCache);
27802   if( pCache->bPurgeable ){
27803     pcache_g.nMaxPage -= pCache->nMax;
27804     pcache_g.nMinPage -= pCache->nMin;
27805     pcacheEnforceMaxPage();
27806   }
27807   sqlite3_free(pCache->apHash);
27808   pcacheExitMutex();
27809 }
27810
27811 /*
27812 ** Preserve the content of the page.  It is assumed that the content
27813 ** has not been preserved already.
27814 **
27815 ** If idJournal==0 then this is for the overall transaction.
27816 ** If idJournal==1 then this is for the statement journal.
27817 **
27818 ** This routine is used for in-memory databases only.
27819 **
27820 ** Return SQLITE_OK or SQLITE_NOMEM if a memory allocation fails.
27821 */
27822 SQLITE_PRIVATE int sqlite3PcachePreserve(PgHdr *p, int idJournal){
27823   void *x;
27824   int sz;
27825   assert( p->pCache->bPurgeable==0 );
27826   assert( p->apSave[idJournal]==0 );
27827   sz = p->pCache->szPage;
27828   p->apSave[idJournal] = x = sqlite3PageMalloc( sz );
27829   if( x==0 ) return SQLITE_NOMEM;
27830   memcpy(x, p->pData, sz);
27831   return SQLITE_OK;
27832 }
27833
27834 /*
27835 ** Commit a change previously preserved.
27836 */
27837 SQLITE_PRIVATE void sqlite3PcacheCommit(PCache *pCache, int idJournal){
27838   PgHdr *p;
27839   int mask = idJournal==0 ? ~PGHDR_IN_JOURNAL : 0xffffff;
27840   pcacheEnterMutex();     /* Mutex is required to call pcacheFree() */
27841   for(p=pCache->pDirty; p; p=p->pNext){
27842     if( p->apSave[idJournal] ){
27843       pcacheFree(p->apSave[idJournal]);
27844       p->apSave[idJournal] = 0;
27845     }
27846     p->flags &= mask;
27847   }
27848   pcacheExitMutex();
27849 }
27850
27851 /*
27852 ** Rollback a change previously preserved.
27853 */
27854 SQLITE_PRIVATE void sqlite3PcacheRollback(
27855   PCache *pCache,                  /* Pager cache */
27856   int idJournal,                   /* Which copy to rollback to */
27857   void (*xReiniter)(PgHdr*)        /* Called on each rolled back page */
27858 ){
27859   PgHdr *p;
27860   int sz;
27861   int mask = idJournal==0 ? ~PGHDR_IN_JOURNAL : 0xffffff;
27862   pcacheEnterMutex();     /* Mutex is required to call pcacheFree() */
27863   sz = pCache->szPage;
27864   for(p=pCache->pDirty; p; p=p->pNext){
27865     if( p->apSave[idJournal] ){
27866       memcpy(p->pData, p->apSave[idJournal], sz);
27867       pcacheFree(p->apSave[idJournal]);
27868       p->apSave[idJournal] = 0;
27869       if( xReiniter ){
27870         xReiniter(p);
27871       }
27872     }
27873     p->flags &= mask;
27874   }
27875   pcacheExitMutex();
27876 }
27877
27878 #ifndef NDEBUG
27879 /* 
27880 ** Assert flags settings on all pages.  Debugging only.
27881 */
27882 SQLITE_PRIVATE void sqlite3PcacheAssertFlags(PCache *pCache, int trueMask, int falseMask){
27883   PgHdr *p;
27884   for(p=pCache->pDirty; p; p=p->pNext){
27885     assert( (p->flags&trueMask)==trueMask );
27886     assert( (p->flags&falseMask)==0 );
27887   }
27888   for(p=pCache->pClean; p; p=p->pNext){
27889     assert( (p->flags&trueMask)==trueMask );
27890     assert( (p->flags&falseMask)==0 );
27891   }
27892 }
27893 #endif
27894
27895 /* 
27896 ** Discard the contents of the cache.
27897 */
27898 SQLITE_PRIVATE int sqlite3PcacheClear(PCache *pCache){
27899   assert(pCache->nRef==0);
27900   pcacheEnterMutex();
27901   pcacheClear(pCache);
27902   pcacheExitMutex();
27903   return SQLITE_OK;
27904 }
27905
27906 /*
27907 ** Merge two lists of pages connected by pDirty and in pgno order.
27908 ** Do not both fixing the pPrevDirty pointers.
27909 */
27910 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
27911   PgHdr result, *pTail;
27912   pTail = &result;
27913   while( pA && pB ){
27914     if( pA->pgno<pB->pgno ){
27915       pTail->pDirty = pA;
27916       pTail = pA;
27917       pA = pA->pDirty;
27918     }else{
27919       pTail->pDirty = pB;
27920       pTail = pB;
27921       pB = pB->pDirty;
27922     }
27923   }
27924   if( pA ){
27925     pTail->pDirty = pA;
27926   }else if( pB ){
27927     pTail->pDirty = pB;
27928   }else{
27929     pTail->pDirty = 0;
27930   }
27931   return result.pDirty;
27932 }
27933
27934 /*
27935 ** Sort the list of pages in accending order by pgno.  Pages are
27936 ** connected by pDirty pointers.  The pPrevDirty pointers are
27937 ** corrupted by this sort.
27938 */
27939 #define N_SORT_BUCKET_ALLOC 25
27940 #define N_SORT_BUCKET       25
27941 #ifdef SQLITE_TEST
27942   int sqlite3_pager_n_sort_bucket = 0;
27943   #undef N_SORT_BUCKET
27944   #define N_SORT_BUCKET \
27945    (sqlite3_pager_n_sort_bucket?sqlite3_pager_n_sort_bucket:N_SORT_BUCKET_ALLOC)
27946 #endif
27947 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
27948   PgHdr *a[N_SORT_BUCKET_ALLOC], *p;
27949   int i;
27950   memset(a, 0, sizeof(a));
27951   while( pIn ){
27952     p = pIn;
27953     pIn = p->pDirty;
27954     p->pDirty = 0;
27955     for(i=0; i<N_SORT_BUCKET-1; i++){
27956       if( a[i]==0 ){
27957         a[i] = p;
27958         break;
27959       }else{
27960         p = pcacheMergeDirtyList(a[i], p);
27961         a[i] = 0;
27962       }
27963     }
27964     if( i==N_SORT_BUCKET-1 ){
27965       /* Coverage: To get here, there need to be 2^(N_SORT_BUCKET) 
27966       ** elements in the input list. This is possible, but impractical.
27967       ** Testing this line is the point of global variable
27968       ** sqlite3_pager_n_sort_bucket.
27969       */
27970       a[i] = pcacheMergeDirtyList(a[i], p);
27971     }
27972   }
27973   p = a[0];
27974   for(i=1; i<N_SORT_BUCKET; i++){
27975     p = pcacheMergeDirtyList(p, a[i]);
27976   }
27977   return p;
27978 }
27979
27980 /*
27981 ** Return a list of all dirty pages in the cache, sorted by page number.
27982 */
27983 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
27984   PgHdr *p;
27985   for(p=pCache->pDirty; p; p=p->pNext){
27986     p->pDirty = p->pNext;
27987   }
27988   return pcacheSortDirtyList(pCache->pDirty);
27989 }
27990
27991 /* 
27992 ** Return the total number of outstanding page references.
27993 */
27994 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
27995   return pCache->nRef;
27996 }
27997
27998 /* 
27999 ** Return the total number of pages in the cache.
28000 */
28001 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
28002   assert( pCache->nPage>=0 );
28003   return pCache->nPage;
28004 }
28005
28006 #ifdef SQLITE_CHECK_PAGES
28007 /*
28008 ** This function is used by the pager.c module to iterate through all 
28009 ** pages in the cache. At present, this is only required if the
28010 ** SQLITE_CHECK_PAGES macro (used for debugging) is specified.
28011 */
28012 SQLITE_PRIVATE void sqlite3PcacheIterate(PCache *pCache, void (*xIter)(PgHdr *)){
28013   PgHdr *p;
28014   for(p=pCache->pClean; p; p=p->pNext){
28015     xIter(p);
28016   }
28017   for(p=pCache->pDirty; p; p=p->pNext){
28018     xIter(p);
28019   }
28020 }
28021 #endif
28022
28023 /* 
28024 ** Set flags on all pages in the page cache 
28025 */
28026 SQLITE_PRIVATE void sqlite3PcacheClearFlags(PCache *pCache, int mask){
28027   PgHdr *p;
28028
28029   /* Obtain the global mutex before modifying any PgHdr.flags variables 
28030   ** or traversing the LRU list.
28031   */ 
28032   pcacheEnterMutex();
28033
28034   mask = ~mask;
28035   for(p=pCache->pDirty; p; p=p->pNext){
28036     p->flags &= mask;
28037   }
28038   for(p=pCache->pClean; p; p=p->pNext){
28039     p->flags &= mask;
28040   }
28041
28042   if( 0==(mask&PGHDR_NEED_SYNC) ){
28043     pCache->pSynced = pCache->pDirtyTail;
28044     assert( !pCache->pSynced || (pCache->pSynced->flags&PGHDR_NEED_SYNC)==0 );
28045   }
28046
28047   pcacheExitMutex();
28048 }
28049
28050 /*
28051 ** Set the suggested cache-size value.
28052 */
28053 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
28054   return pCache->nMax;
28055 }
28056
28057 /*
28058 ** Set the suggested cache-size value.
28059 */
28060 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
28061   if( mxPage<10 ){
28062     mxPage = 10;
28063   }
28064   if( pCache->bPurgeable ){
28065     pcacheEnterMutex();
28066     pcache_g.nMaxPage -= pCache->nMax;
28067     pcache_g.nMaxPage += mxPage;
28068     pcacheEnforceMaxPage();
28069     pcacheExitMutex();
28070   }
28071   pCache->nMax = mxPage;
28072 }
28073
28074 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
28075 /*
28076 ** This function is called to free superfluous dynamically allocated memory
28077 ** held by the pager system. Memory in use by any SQLite pager allocated
28078 ** by the current thread may be sqlite3_free()ed.
28079 **
28080 ** nReq is the number of bytes of memory required. Once this much has
28081 ** been released, the function returns. The return value is the total number 
28082 ** of bytes of memory released.
28083 */
28084 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
28085   int nFree = 0;
28086   if( pcache_g.pStart==0 ){
28087     PgHdr *p;
28088     pcacheEnterMutex();
28089     while( (nReq<0 || nFree<nReq) && (p=pcacheRecyclePage()) ){
28090       nFree += pcachePageSize(p);
28091       pcachePageFree(p);
28092     }
28093     pcacheExitMutex();
28094   }
28095   return nFree;
28096 }
28097 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
28098
28099 #ifdef SQLITE_TEST
28100 SQLITE_PRIVATE void sqlite3PcacheStats(
28101   int *pnCurrent,
28102   int *pnMax,
28103   int *pnMin,
28104   int *pnRecyclable
28105 ){
28106   PgHdr *p;
28107   int nRecyclable = 0;
28108   for(p=pcache_g.pLruHead; p; p=p->pNextLru){
28109     nRecyclable++;
28110   }
28111
28112   *pnCurrent = pcache_g.nCurrentPage;
28113   *pnMax = pcache_g.nMaxPage;
28114   *pnMin = pcache_g.nMinPage;
28115   *pnRecyclable = nRecyclable;
28116 }
28117 #endif
28118
28119 /************** End of pcache.c **********************************************/
28120 /************** Begin file pager.c *******************************************/
28121 /*
28122 ** 2001 September 15
28123 **
28124 ** The author disclaims copyright to this source code.  In place of
28125 ** a legal notice, here is a blessing:
28126 **
28127 **    May you do good and not evil.
28128 **    May you find forgiveness for yourself and forgive others.
28129 **    May you share freely, never taking more than you give.
28130 **
28131 *************************************************************************
28132 ** This is the implementation of the page cache subsystem or "pager".
28133 ** 
28134 ** The pager is used to access a database disk file.  It implements
28135 ** atomic commit and rollback through the use of a journal file that
28136 ** is separate from the database file.  The pager also implements file
28137 ** locking to prevent two processes from writing the same database
28138 ** file simultaneously, or one process from reading the database while
28139 ** another is writing.
28140 **
28141 ** @(#) $Id: pager.c,v 1.493 2008/09/19 09:14:44 danielk1977 Exp $
28142 */
28143 #ifndef SQLITE_OMIT_DISKIO
28144
28145 /*
28146 ** Macros for troubleshooting.  Normally turned off
28147 */
28148 #if 0
28149 #define sqlite3DebugPrintf printf
28150 #define PAGERTRACE1(X)       sqlite3DebugPrintf(X)
28151 #define PAGERTRACE2(X,Y)     sqlite3DebugPrintf(X,Y)
28152 #define PAGERTRACE3(X,Y,Z)   sqlite3DebugPrintf(X,Y,Z)
28153 #define PAGERTRACE4(X,Y,Z,W) sqlite3DebugPrintf(X,Y,Z,W)
28154 #define PAGERTRACE5(X,Y,Z,W,V) sqlite3DebugPrintf(X,Y,Z,W,V)
28155 #else
28156 #define PAGERTRACE1(X)
28157 #define PAGERTRACE2(X,Y)
28158 #define PAGERTRACE3(X,Y,Z)
28159 #define PAGERTRACE4(X,Y,Z,W)
28160 #define PAGERTRACE5(X,Y,Z,W,V)
28161 #endif
28162
28163 /*
28164 ** The following two macros are used within the PAGERTRACEX() macros above
28165 ** to print out file-descriptors. 
28166 **
28167 ** PAGERID() takes a pointer to a Pager struct as its argument. The
28168 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
28169 ** struct as its argument.
28170 */
28171 #define PAGERID(p) ((int)(p->fd))
28172 #define FILEHANDLEID(fd) ((int)fd)
28173
28174 /*
28175 ** The page cache as a whole is always in one of the following
28176 ** states:
28177 **
28178 **   PAGER_UNLOCK        The page cache is not currently reading or 
28179 **                       writing the database file.  There is no
28180 **                       data held in memory.  This is the initial
28181 **                       state.
28182 **
28183 **   PAGER_SHARED        The page cache is reading the database.
28184 **                       Writing is not permitted.  There can be
28185 **                       multiple readers accessing the same database
28186 **                       file at the same time.
28187 **
28188 **   PAGER_RESERVED      This process has reserved the database for writing
28189 **                       but has not yet made any changes.  Only one process
28190 **                       at a time can reserve the database.  The original
28191 **                       database file has not been modified so other
28192 **                       processes may still be reading the on-disk
28193 **                       database file.
28194 **
28195 **   PAGER_EXCLUSIVE     The page cache is writing the database.
28196 **                       Access is exclusive.  No other processes or
28197 **                       threads can be reading or writing while one
28198 **                       process is writing.
28199 **
28200 **   PAGER_SYNCED        The pager moves to this state from PAGER_EXCLUSIVE
28201 **                       after all dirty pages have been written to the
28202 **                       database file and the file has been synced to
28203 **                       disk. All that remains to do is to remove or
28204 **                       truncate the journal file and the transaction 
28205 **                       will be committed.
28206 **
28207 ** The page cache comes up in PAGER_UNLOCK.  The first time a
28208 ** sqlite3PagerGet() occurs, the state transitions to PAGER_SHARED.
28209 ** After all pages have been released using sqlite_page_unref(),
28210 ** the state transitions back to PAGER_UNLOCK.  The first time
28211 ** that sqlite3PagerWrite() is called, the state transitions to
28212 ** PAGER_RESERVED.  (Note that sqlite3PagerWrite() can only be
28213 ** called on an outstanding page which means that the pager must
28214 ** be in PAGER_SHARED before it transitions to PAGER_RESERVED.)
28215 ** PAGER_RESERVED means that there is an open rollback journal.
28216 ** The transition to PAGER_EXCLUSIVE occurs before any changes
28217 ** are made to the database file, though writes to the rollback
28218 ** journal occurs with just PAGER_RESERVED.  After an sqlite3PagerRollback()
28219 ** or sqlite3PagerCommitPhaseTwo(), the state can go back to PAGER_SHARED,
28220 ** or it can stay at PAGER_EXCLUSIVE if we are in exclusive access mode.
28221 */
28222 #define PAGER_UNLOCK      0
28223 #define PAGER_SHARED      1   /* same as SHARED_LOCK */
28224 #define PAGER_RESERVED    2   /* same as RESERVED_LOCK */
28225 #define PAGER_EXCLUSIVE   4   /* same as EXCLUSIVE_LOCK */
28226 #define PAGER_SYNCED      5
28227
28228 /*
28229 ** If the SQLITE_BUSY_RESERVED_LOCK macro is set to true at compile-time,
28230 ** then failed attempts to get a reserved lock will invoke the busy callback.
28231 ** This is off by default.  To see why, consider the following scenario:
28232 ** 
28233 ** Suppose thread A already has a shared lock and wants a reserved lock.
28234 ** Thread B already has a reserved lock and wants an exclusive lock.  If
28235 ** both threads are using their busy callbacks, it might be a long time
28236 ** be for one of the threads give up and allows the other to proceed.
28237 ** But if the thread trying to get the reserved lock gives up quickly
28238 ** (if it never invokes its busy callback) then the contention will be
28239 ** resolved quickly.
28240 */
28241 #ifndef SQLITE_BUSY_RESERVED_LOCK
28242 # define SQLITE_BUSY_RESERVED_LOCK 0
28243 #endif
28244
28245 /*
28246 ** This macro rounds values up so that if the value is an address it
28247 ** is guaranteed to be an address that is aligned to an 8-byte boundary.
28248 */
28249 #define FORCE_ALIGNMENT(X)   (((X)+7)&~7)
28250
28251 /*
28252 ** A macro used for invoking the codec if there is one
28253 */
28254 #ifdef SQLITE_HAS_CODEC
28255 # define CODEC1(P,D,N,X) if( P->xCodec!=0 ){ P->xCodec(P->pCodecArg,D,N,X); }
28256 # define CODEC2(P,D,N,X) ((char*)(P->xCodec!=0?P->xCodec(P->pCodecArg,D,N,X):D))
28257 #else
28258 # define CODEC1(P,D,N,X) /* NO-OP */
28259 # define CODEC2(P,D,N,X) ((char*)D)
28260 #endif
28261
28262 /*
28263 ** A open page cache is an instance of the following structure.
28264 **
28265 ** Pager.errCode may be set to SQLITE_IOERR, SQLITE_CORRUPT, or
28266 ** or SQLITE_FULL. Once one of the first three errors occurs, it persists
28267 ** and is returned as the result of every major pager API call.  The
28268 ** SQLITE_FULL return code is slightly different. It persists only until the
28269 ** next successful rollback is performed on the pager cache. Also,
28270 ** SQLITE_FULL does not affect the sqlite3PagerGet() and sqlite3PagerLookup()
28271 ** APIs, they may still be used successfully.
28272 */
28273 struct Pager {
28274   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
28275   u8 journalOpen;             /* True if journal file descriptors is valid */
28276   u8 journalStarted;          /* True if header of journal is synced */
28277   u8 useJournal;              /* Use a rollback journal on this file */
28278   u8 noReadlock;              /* Do not bother to obtain readlocks */
28279   u8 stmtOpen;                /* True if the statement subjournal is open */
28280   u8 stmtInUse;               /* True we are in a statement subtransaction */
28281   u8 stmtAutoopen;            /* Open stmt journal when main journal is opened*/
28282   u8 noSync;                  /* Do not sync the journal if true */
28283   u8 fullSync;                /* Do extra syncs of the journal for robustness */
28284   u8 sync_flags;              /* One of SYNC_NORMAL or SYNC_FULL */
28285   u8 state;                   /* PAGER_UNLOCK, _SHARED, _RESERVED, etc. */
28286   u8 tempFile;                /* zFilename is a temporary file */
28287   u8 readOnly;                /* True for a read-only database */
28288   u8 needSync;                /* True if an fsync() is needed on the journal */
28289   u8 dirtyCache;              /* True if cached pages have changed */
28290   u8 alwaysRollback;          /* Disable DontRollback() for all pages */
28291   u8 memDb;                   /* True to inhibit all file I/O */
28292   u8 setMaster;               /* True if a m-j name has been written to jrnl */
28293   u8 doNotSync;               /* Boolean. While true, do not spill the cache */
28294   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
28295   u8 journalMode;             /* On of the PAGER_JOURNALMODE_* values */
28296   u8 dbModified;              /* True if there are any changes to the Db */
28297   u8 changeCountDone;         /* Set after incrementing the change-counter */
28298   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
28299   int errCode;                /* One of several kinds of errors */
28300   int dbSize;                 /* Number of pages in the file */
28301   int origDbSize;             /* dbSize before the current change */
28302   int stmtSize;               /* Size of database (in pages) at stmt_begin() */
28303   int nRec;                   /* Number of pages written to the journal */
28304   u32 cksumInit;              /* Quasi-random value added to every checksum */
28305   int stmtNRec;               /* Number of records in stmt subjournal */
28306   int nExtra;                 /* Add this many bytes to each in-memory page */
28307   int pageSize;               /* Number of bytes in a page */
28308   int nPage;                  /* Total number of in-memory pages */
28309   int mxPage;                 /* Maximum number of pages to hold in cache */
28310   Pgno mxPgno;                /* Maximum allowed size of the database */
28311   Bitvec *pInJournal;         /* One bit for each page in the database file */
28312   Bitvec *pInStmt;            /* One bit for each page in the database */
28313   Bitvec *pAlwaysRollback;    /* One bit for each page marked always-rollback */
28314   char *zFilename;            /* Name of the database file */
28315   char *zJournal;             /* Name of the journal file */
28316   char *zDirectory;           /* Directory hold database and journal files */
28317   sqlite3_file *fd, *jfd;     /* File descriptors for database and journal */
28318   sqlite3_file *stfd;         /* File descriptor for the statement subjournal*/
28319   BusyHandler *pBusyHandler;  /* Pointer to sqlite.busyHandler */
28320   i64 journalOff;             /* Current byte offset in the journal file */
28321   i64 journalHdr;             /* Byte offset to previous journal header */
28322   i64 stmtHdrOff;             /* First journal header written this statement */
28323   i64 stmtCksum;              /* cksumInit when statement was started */
28324   i64 stmtJSize;              /* Size of journal at stmt_begin() */
28325   int sectorSize;             /* Assumed sector size during rollback */
28326 #ifdef SQLITE_TEST
28327   int nHit, nMiss;            /* Cache hits and missing */
28328   int nRead, nWrite;          /* Database pages read/written */
28329 #endif
28330   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
28331 #ifdef SQLITE_HAS_CODEC
28332   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
28333   void *pCodecArg;            /* First argument to xCodec() */
28334 #endif
28335   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
28336   char dbFileVers[16];        /* Changes whenever database file changes */
28337   i64 journalSizeLimit;       /* Size limit for persistent journal files */
28338   PCache *pPCache;            /* Pointer to page cache object */
28339 };
28340
28341 /*
28342 ** The following global variables hold counters used for
28343 ** testing purposes only.  These variables do not exist in
28344 ** a non-testing build.  These variables are not thread-safe.
28345 */
28346 #ifdef SQLITE_TEST
28347 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
28348 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
28349 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
28350 # define PAGER_INCR(v)  v++
28351 #else
28352 # define PAGER_INCR(v)
28353 #endif
28354
28355
28356
28357 /*
28358 ** Journal files begin with the following magic string.  The data
28359 ** was obtained from /dev/random.  It is used only as a sanity check.
28360 **
28361 ** Since version 2.8.0, the journal format contains additional sanity
28362 ** checking information.  If the power fails while the journal is begin
28363 ** written, semi-random garbage data might appear in the journal
28364 ** file after power is restored.  If an attempt is then made
28365 ** to roll the journal back, the database could be corrupted.  The additional
28366 ** sanity checking data is an attempt to discover the garbage in the
28367 ** journal and ignore it.
28368 **
28369 ** The sanity checking information for the new journal format consists
28370 ** of a 32-bit checksum on each page of data.  The checksum covers both
28371 ** the page number and the pPager->pageSize bytes of data for the page.
28372 ** This cksum is initialized to a 32-bit random value that appears in the
28373 ** journal file right after the header.  The random initializer is important,
28374 ** because garbage data that appears at the end of a journal is likely
28375 ** data that was once in other files that have now been deleted.  If the
28376 ** garbage data came from an obsolete journal file, the checksums might
28377 ** be correct.  But by initializing the checksum to random value which
28378 ** is different for every journal, we minimize that risk.
28379 */
28380 static const unsigned char aJournalMagic[] = {
28381   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
28382 };
28383
28384 /*
28385 ** The size of the header and of each page in the journal is determined
28386 ** by the following macros.
28387 */
28388 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
28389
28390 /*
28391 ** The journal header size for this pager. In the future, this could be
28392 ** set to some value read from the disk controller. The important
28393 ** characteristic is that it is the same size as a disk sector.
28394 */
28395 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
28396
28397 /*
28398 ** The macro MEMDB is true if we are dealing with an in-memory database.
28399 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
28400 ** the value of MEMDB will be a constant and the compiler will optimize
28401 ** out code that would never execute.
28402 */
28403 #ifdef SQLITE_OMIT_MEMORYDB
28404 # define MEMDB 0
28405 #else
28406 # define MEMDB pPager->memDb
28407 #endif
28408
28409 /*
28410 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
28411 ** reserved for working around a windows/posix incompatibility). It is
28412 ** used in the journal to signify that the remainder of the journal file 
28413 ** is devoted to storing a master journal name - there are no more pages to
28414 ** roll back. See comments for function writeMasterJournal() for details.
28415 */
28416 /* #define PAGER_MJ_PGNO(x) (PENDING_BYTE/((x)->pageSize)) */
28417 #define PAGER_MJ_PGNO(x) ((PENDING_BYTE/((x)->pageSize))+1)
28418
28419 /*
28420 ** The maximum legal page number is (2^31 - 1).
28421 */
28422 #define PAGER_MAX_PGNO 2147483647
28423
28424 /*
28425 ** Return true if page *pPg has already been written to the statement
28426 ** journal (or statement snapshot has been created, if *pPg is part
28427 ** of an in-memory database).
28428 */
28429 static int pageInStatement(PgHdr *pPg){
28430   Pager *pPager = pPg->pPager;
28431   if( MEMDB ){
28432     return pPg->apSave[1]!=0;
28433   }else{
28434     return sqlite3BitvecTest(pPager->pInStmt, pPg->pgno);
28435   }
28436 }
28437
28438 /*
28439 ** Read a 32-bit integer from the given file descriptor.  Store the integer
28440 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
28441 ** error code is something goes wrong.
28442 **
28443 ** All values are stored on disk as big-endian.
28444 */
28445 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
28446   unsigned char ac[4];
28447   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
28448   if( rc==SQLITE_OK ){
28449     *pRes = sqlite3Get4byte(ac);
28450   }
28451   return rc;
28452 }
28453
28454 /*
28455 ** Write a 32-bit integer into a string buffer in big-endian byte order.
28456 */
28457 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
28458
28459 /*
28460 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
28461 ** on success or an error code is something goes wrong.
28462 */
28463 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
28464   char ac[4];
28465   put32bits(ac, val);
28466   return sqlite3OsWrite(fd, ac, 4, offset);
28467 }
28468
28469 /*
28470 ** If file pFd is open, call sqlite3OsUnlock() on it.
28471 */
28472 static int osUnlock(sqlite3_file *pFd, int eLock){
28473   if( !pFd->pMethods ){
28474     return SQLITE_OK;
28475   }
28476   return sqlite3OsUnlock(pFd, eLock);
28477 }
28478
28479 /*
28480 ** This function determines whether or not the atomic-write optimization
28481 ** can be used with this pager. The optimization can be used if:
28482 **
28483 **  (a) the value returned by OsDeviceCharacteristics() indicates that
28484 **      a database page may be written atomically, and
28485 **  (b) the value returned by OsSectorSize() is less than or equal
28486 **      to the page size.
28487 **
28488 ** If the optimization cannot be used, 0 is returned. If it can be used,
28489 ** then the value returned is the size of the journal file when it
28490 ** contains rollback data for exactly one page.
28491 */
28492 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
28493 static int jrnlBufferSize(Pager *pPager){
28494   int dc;           /* Device characteristics */
28495   int nSector;      /* Sector size */
28496   int szPage;        /* Page size */
28497   sqlite3_file *fd = pPager->fd;
28498
28499   if( fd->pMethods ){
28500     dc = sqlite3OsDeviceCharacteristics(fd);
28501     nSector = sqlite3OsSectorSize(fd);
28502     szPage = pPager->pageSize;
28503   }
28504
28505   assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
28506   assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
28507
28508   if( !fd->pMethods || 
28509        (dc & (SQLITE_IOCAP_ATOMIC|(szPage>>8)) && nSector<=szPage) ){
28510     return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
28511   }
28512   return 0;
28513 }
28514 #endif
28515
28516 /*
28517 ** This function should be called when an error occurs within the pager
28518 ** code. The first argument is a pointer to the pager structure, the
28519 ** second the error-code about to be returned by a pager API function. 
28520 ** The value returned is a copy of the second argument to this function. 
28521 **
28522 ** If the second argument is SQLITE_IOERR, SQLITE_CORRUPT, or SQLITE_FULL
28523 ** the error becomes persistent. Until the persisten error is cleared,
28524 ** subsequent API calls on this Pager will immediately return the same 
28525 ** error code.
28526 **
28527 ** A persistent error indicates that the contents of the pager-cache 
28528 ** cannot be trusted. This state can be cleared by completely discarding 
28529 ** the contents of the pager-cache. If a transaction was active when
28530 ** the persistent error occured, then the rollback journal may need
28531 ** to be replayed.
28532 */
28533 static void pager_unlock(Pager *pPager);
28534 static int pager_error(Pager *pPager, int rc){
28535   int rc2 = rc & 0xff;
28536   assert(
28537        pPager->errCode==SQLITE_FULL ||
28538        pPager->errCode==SQLITE_OK ||
28539        (pPager->errCode & 0xff)==SQLITE_IOERR
28540   );
28541   if(
28542     rc2==SQLITE_FULL ||
28543     rc2==SQLITE_IOERR ||
28544     rc2==SQLITE_CORRUPT
28545   ){
28546     pPager->errCode = rc;
28547     if( pPager->state==PAGER_UNLOCK 
28548      && sqlite3PcacheRefCount(pPager->pPCache)==0 
28549     ){
28550       /* If the pager is already unlocked, call pager_unlock() now to
28551       ** clear the error state and ensure that the pager-cache is 
28552       ** completely empty.
28553       */
28554       pager_unlock(pPager);
28555     }
28556   }
28557   return rc;
28558 }
28559
28560 /*
28561 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
28562 ** on the cache using a hash function.  This is used for testing
28563 ** and debugging only.
28564 */
28565 #ifdef SQLITE_CHECK_PAGES
28566 /*
28567 ** Return a 32-bit hash of the page data for pPage.
28568 */
28569 static u32 pager_datahash(int nByte, unsigned char *pData){
28570   u32 hash = 0;
28571   int i;
28572   for(i=0; i<nByte; i++){
28573     hash = (hash*1039) + pData[i];
28574   }
28575   return hash;
28576 }
28577 static u32 pager_pagehash(PgHdr *pPage){
28578   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
28579 }
28580 static u32 pager_set_pagehash(PgHdr *pPage){
28581   pPage->pageHash = pager_pagehash(pPage);
28582 }
28583
28584 /*
28585 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
28586 ** is defined, and NDEBUG is not defined, an assert() statement checks
28587 ** that the page is either dirty or still matches the calculated page-hash.
28588 */
28589 #define CHECK_PAGE(x) checkPage(x)
28590 static void checkPage(PgHdr *pPg){
28591   Pager *pPager = pPg->pPager;
28592   assert( !pPg->pageHash || pPager->errCode || MEMDB 
28593       || (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
28594 }
28595
28596 #else
28597 #define pager_datahash(X,Y)  0
28598 #define pager_pagehash(X)  0
28599 #define CHECK_PAGE(x)
28600 #endif  /* SQLITE_CHECK_PAGES */
28601
28602 /*
28603 ** When this is called the journal file for pager pPager must be open.
28604 ** The master journal file name is read from the end of the file and 
28605 ** written into memory supplied by the caller. 
28606 **
28607 ** zMaster must point to a buffer of at least nMaster bytes allocated by
28608 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
28609 ** enough space to write the master journal name). If the master journal
28610 ** name in the journal is longer than nMaster bytes (including a
28611 ** nul-terminator), then this is handled as if no master journal name
28612 ** were present in the journal.
28613 **
28614 ** If no master journal file name is present zMaster[0] is set to 0 and
28615 ** SQLITE_OK returned.
28616 */
28617 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, int nMaster){
28618   int rc;
28619   u32 len;
28620   i64 szJ;
28621   u32 cksum;
28622   u32 u;                   /* Unsigned loop counter */
28623   unsigned char aMagic[8]; /* A buffer to hold the magic header */
28624
28625   zMaster[0] = '\0';
28626
28627   rc = sqlite3OsFileSize(pJrnl, &szJ);
28628   if( rc!=SQLITE_OK || szJ<16 ) return rc;
28629
28630   rc = read32bits(pJrnl, szJ-16, &len);
28631   if( rc!=SQLITE_OK ) return rc;
28632
28633   if( len>=nMaster ){
28634     return SQLITE_OK;
28635   }
28636
28637   rc = read32bits(pJrnl, szJ-12, &cksum);
28638   if( rc!=SQLITE_OK ) return rc;
28639
28640   rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8);
28641   if( rc!=SQLITE_OK || memcmp(aMagic, aJournalMagic, 8) ) return rc;
28642
28643   rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len);
28644   if( rc!=SQLITE_OK ){
28645     return rc;
28646   }
28647   zMaster[len] = '\0';
28648
28649   /* See if the checksum matches the master journal name */
28650   for(u=0; u<len; u++){
28651     cksum -= zMaster[u];
28652    }
28653   if( cksum ){
28654     /* If the checksum doesn't add up, then one or more of the disk sectors
28655     ** containing the master journal filename is corrupted. This means
28656     ** definitely roll back, so just return SQLITE_OK and report a (nul)
28657     ** master-journal filename.
28658     */
28659     zMaster[0] = '\0';
28660   }
28661    
28662   return SQLITE_OK;
28663 }
28664
28665 /*
28666 ** Seek the journal file descriptor to the next sector boundary where a
28667 ** journal header may be read or written. Pager.journalOff is updated with
28668 ** the new seek offset.
28669 **
28670 ** i.e for a sector size of 512:
28671 **
28672 ** Input Offset              Output Offset
28673 ** ---------------------------------------
28674 ** 0                         0
28675 ** 512                       512
28676 ** 100                       512
28677 ** 2000                      2048
28678 ** 
28679 */
28680 static void seekJournalHdr(Pager *pPager){
28681   i64 offset = 0;
28682   i64 c = pPager->journalOff;
28683   if( c ){
28684     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
28685   }
28686   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
28687   assert( offset>=c );
28688   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
28689   pPager->journalOff = offset;
28690 }
28691
28692 /*
28693 ** Write zeros over the header of the journal file.  This has the
28694 ** effect of invalidating the journal file and committing the
28695 ** transaction.
28696 */
28697 static int zeroJournalHdr(Pager *pPager, int doTruncate){
28698   int rc = SQLITE_OK;
28699   static const char zeroHdr[28] = {0};
28700
28701   if( pPager->journalOff ){
28702     i64 iLimit = pPager->journalSizeLimit;
28703
28704     IOTRACE(("JZEROHDR %p\n", pPager))
28705     if( doTruncate || iLimit==0 ){
28706       rc = sqlite3OsTruncate(pPager->jfd, 0);
28707     }else{
28708       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
28709     }
28710     if( rc==SQLITE_OK && !pPager->noSync ){
28711       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->sync_flags);
28712     }
28713
28714     /* At this point the transaction is committed but the write lock 
28715     ** is still held on the file. If there is a size limit configured for 
28716     ** the persistent journal and the journal file currently consumes more
28717     ** space than that limit allows for, truncate it now. There is no need
28718     ** to sync the file following this operation.
28719     */
28720     if( rc==SQLITE_OK && iLimit>0 ){
28721       i64 sz;
28722       rc = sqlite3OsFileSize(pPager->jfd, &sz);
28723       if( rc==SQLITE_OK && sz>iLimit ){
28724         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
28725       }
28726     }
28727   }
28728   return rc;
28729 }
28730
28731 /*
28732 ** The journal file must be open when this routine is called. A journal
28733 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
28734 ** current location.
28735 **
28736 ** The format for the journal header is as follows:
28737 ** - 8 bytes: Magic identifying journal format.
28738 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
28739 ** - 4 bytes: Random number used for page hash.
28740 ** - 4 bytes: Initial database page count.
28741 ** - 4 bytes: Sector size used by the process that wrote this journal.
28742 ** - 4 bytes: Database page size.
28743 ** 
28744 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
28745 */
28746 static int writeJournalHdr(Pager *pPager){
28747   int rc = SQLITE_OK;
28748   char *zHeader = pPager->pTmpSpace;
28749   int nHeader = pPager->pageSize;
28750   int nWrite;
28751
28752   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
28753     nHeader = JOURNAL_HDR_SZ(pPager);
28754   }
28755
28756   if( pPager->stmtHdrOff==0 ){
28757     pPager->stmtHdrOff = pPager->journalOff;
28758   }
28759
28760   seekJournalHdr(pPager);
28761   pPager->journalHdr = pPager->journalOff;
28762
28763   memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
28764
28765   /* 
28766   ** Write the nRec Field - the number of page records that follow this
28767   ** journal header. Normally, zero is written to this value at this time.
28768   ** After the records are added to the journal (and the journal synced, 
28769   ** if in full-sync mode), the zero is overwritten with the true number
28770   ** of records (see syncJournal()).
28771   **
28772   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
28773   ** reading the journal this value tells SQLite to assume that the
28774   ** rest of the journal file contains valid page records. This assumption
28775   ** is dangerous, as if a failure occured whilst writing to the journal
28776   ** file it may contain some garbage data. There are two scenarios
28777   ** where this risk can be ignored:
28778   **
28779   **   * When the pager is in no-sync mode. Corruption can follow a
28780   **     power failure in this case anyway.
28781   **
28782   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
28783   **     that garbage data is never appended to the journal file.
28784   */
28785   assert(pPager->fd->pMethods||pPager->noSync);
28786   if( (pPager->noSync) 
28787    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
28788   ){
28789     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
28790   }else{
28791     put32bits(&zHeader[sizeof(aJournalMagic)], 0);
28792   }
28793
28794   /* The random check-hash initialiser */ 
28795   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
28796   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
28797   /* The initial database size */
28798   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbSize);
28799   /* The assumed sector size for this process */
28800   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
28801   if( pPager->journalHdr==0 ){
28802     /* The page size */
28803     put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
28804   }
28805
28806   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
28807     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
28808     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
28809     pPager->journalOff += nHeader;
28810   }
28811
28812   return rc;
28813 }
28814
28815 /*
28816 ** The journal file must be open when this is called. A journal header file
28817 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
28818 ** file. See comments above function writeJournalHdr() for a description of
28819 ** the journal header format.
28820 **
28821 ** If the header is read successfully, *nRec is set to the number of
28822 ** page records following this header and *dbSize is set to the size of the
28823 ** database before the transaction began, in pages. Also, pPager->cksumInit
28824 ** is set to the value read from the journal header. SQLITE_OK is returned
28825 ** in this case.
28826 **
28827 ** If the journal header file appears to be corrupted, SQLITE_DONE is
28828 ** returned and *nRec and *dbSize are not set.  If JOURNAL_HDR_SZ bytes
28829 ** cannot be read from the journal file an error code is returned.
28830 */
28831 static int readJournalHdr(
28832   Pager *pPager, 
28833   i64 journalSize,
28834   u32 *pNRec, 
28835   u32 *pDbSize
28836 ){
28837   int rc;
28838   unsigned char aMagic[8]; /* A buffer to hold the magic header */
28839   i64 jrnlOff;
28840   int iPageSize;
28841
28842   seekJournalHdr(pPager);
28843   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
28844     return SQLITE_DONE;
28845   }
28846   jrnlOff = pPager->journalOff;
28847
28848   rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), jrnlOff);
28849   if( rc ) return rc;
28850   jrnlOff += sizeof(aMagic);
28851
28852   if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
28853     return SQLITE_DONE;
28854   }
28855
28856   rc = read32bits(pPager->jfd, jrnlOff, pNRec);
28857   if( rc ) return rc;
28858
28859   rc = read32bits(pPager->jfd, jrnlOff+4, &pPager->cksumInit);
28860   if( rc ) return rc;
28861
28862   rc = read32bits(pPager->jfd, jrnlOff+8, pDbSize);
28863   if( rc ) return rc;
28864
28865   rc = read32bits(pPager->jfd, jrnlOff+16, (u32 *)&iPageSize);
28866   if( rc==SQLITE_OK 
28867    && iPageSize>=512 
28868    && iPageSize<=SQLITE_MAX_PAGE_SIZE 
28869    && ((iPageSize-1)&iPageSize)==0 
28870   ){
28871     u16 pagesize = iPageSize;
28872     rc = sqlite3PagerSetPagesize(pPager, &pagesize);
28873   }
28874   if( rc ) return rc;
28875
28876   /* Update the assumed sector-size to match the value used by 
28877   ** the process that created this journal. If this journal was
28878   ** created by a process other than this one, then this routine
28879   ** is being called from within pager_playback(). The local value
28880   ** of Pager.sectorSize is restored at the end of that routine.
28881   */
28882   rc = read32bits(pPager->jfd, jrnlOff+12, (u32 *)&pPager->sectorSize);
28883   if( rc ) return rc;
28884
28885   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
28886   return SQLITE_OK;
28887 }
28888
28889
28890 /*
28891 ** Write the supplied master journal name into the journal file for pager
28892 ** pPager at the current location. The master journal name must be the last
28893 ** thing written to a journal file. If the pager is in full-sync mode, the
28894 ** journal file descriptor is advanced to the next sector boundary before
28895 ** anything is written. The format is:
28896 **
28897 ** + 4 bytes: PAGER_MJ_PGNO.
28898 ** + N bytes: length of master journal name.
28899 ** + 4 bytes: N
28900 ** + 4 bytes: Master journal name checksum.
28901 ** + 8 bytes: aJournalMagic[].
28902 **
28903 ** The master journal page checksum is the sum of the bytes in the master
28904 ** journal name.
28905 **
28906 ** If zMaster is a NULL pointer (occurs for a single database transaction), 
28907 ** this call is a no-op.
28908 */
28909 static int writeMasterJournal(Pager *pPager, const char *zMaster){
28910   int rc;
28911   int len; 
28912   int i; 
28913   i64 jrnlOff;
28914   i64 jrnlSize;
28915   u32 cksum = 0;
28916   char zBuf[sizeof(aJournalMagic)+2*4];
28917
28918   if( !zMaster || pPager->setMaster) return SQLITE_OK;
28919   pPager->setMaster = 1;
28920
28921   len = strlen(zMaster);
28922   for(i=0; i<len; i++){
28923     cksum += zMaster[i];
28924   }
28925
28926   /* If in full-sync mode, advance to the next disk sector before writing
28927   ** the master journal name. This is in case the previous page written to
28928   ** the journal has already been synced.
28929   */
28930   if( pPager->fullSync ){
28931     seekJournalHdr(pPager);
28932   }
28933   jrnlOff = pPager->journalOff;
28934   pPager->journalOff += (len+20);
28935
28936   rc = write32bits(pPager->jfd, jrnlOff, PAGER_MJ_PGNO(pPager));
28937   if( rc!=SQLITE_OK ) return rc;
28938   jrnlOff += 4;
28939
28940   rc = sqlite3OsWrite(pPager->jfd, zMaster, len, jrnlOff);
28941   if( rc!=SQLITE_OK ) return rc;
28942   jrnlOff += len;
28943
28944   put32bits(zBuf, len);
28945   put32bits(&zBuf[4], cksum);
28946   memcpy(&zBuf[8], aJournalMagic, sizeof(aJournalMagic));
28947   rc = sqlite3OsWrite(pPager->jfd, zBuf, 8+sizeof(aJournalMagic), jrnlOff);
28948   jrnlOff += 8+sizeof(aJournalMagic);
28949   pPager->needSync = !pPager->noSync;
28950
28951   /* If the pager is in peristent-journal mode, then the physical 
28952   ** journal-file may extend past the end of the master-journal name
28953   ** and 8 bytes of magic data just written to the file. This is 
28954   ** dangerous because the code to rollback a hot-journal file
28955   ** will not be able to find the master-journal name to determine 
28956   ** whether or not the journal is hot. 
28957   **
28958   ** Easiest thing to do in this scenario is to truncate the journal 
28959   ** file to the required size.
28960   */ 
28961   if( (rc==SQLITE_OK)
28962    && (rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))==SQLITE_OK
28963    && jrnlSize>jrnlOff
28964   ){
28965     rc = sqlite3OsTruncate(pPager->jfd, jrnlOff);
28966   }
28967   return rc;
28968 }
28969
28970 /*
28971 ** Find a page in the hash table given its page number.  Return
28972 ** a pointer to the page or NULL if not found.
28973 */
28974 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
28975   PgHdr *p;
28976   sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
28977   return p;
28978 }
28979
28980 /*
28981 ** Clear the in-memory cache.  This routine
28982 ** sets the state of the pager back to what it was when it was first
28983 ** opened.  Any outstanding pages are invalidated and subsequent attempts
28984 ** to access those pages will likely result in a coredump.
28985 */
28986 static void pager_reset(Pager *pPager){
28987   if( pPager->errCode ) return;
28988   sqlite3PcacheClear(pPager->pPCache);
28989 }
28990
28991 /*
28992 ** Unlock the database file. 
28993 **
28994 ** If the pager is currently in error state, discard the contents of 
28995 ** the cache and reset the Pager structure internal state. If there is
28996 ** an open journal-file, then the next time a shared-lock is obtained
28997 ** on the pager file (by this or any other process), it will be
28998 ** treated as a hot-journal and rolled back.
28999 */
29000 static void pager_unlock(Pager *pPager){
29001   if( !pPager->exclusiveMode ){
29002     if( !MEMDB ){
29003       int rc = osUnlock(pPager->fd, NO_LOCK);
29004       if( rc ) pPager->errCode = rc;
29005       pPager->dbSize = -1;
29006       IOTRACE(("UNLOCK %p\n", pPager))
29007
29008       /* Always close the journal file when dropping the database lock.
29009       ** Otherwise, another connection with journal_mode=delete might
29010       ** delete the file out from under us.
29011       */
29012       if( pPager->journalOpen ){
29013         sqlite3OsClose(pPager->jfd);
29014         pPager->journalOpen = 0;
29015         sqlite3BitvecDestroy(pPager->pInJournal);
29016         pPager->pInJournal = 0;
29017         sqlite3BitvecDestroy(pPager->pAlwaysRollback);
29018         pPager->pAlwaysRollback = 0;
29019       }
29020
29021       /* If Pager.errCode is set, the contents of the pager cache cannot be
29022       ** trusted. Now that the pager file is unlocked, the contents of the
29023       ** cache can be discarded and the error code safely cleared.
29024       */
29025       if( pPager->errCode ){
29026         if( rc==SQLITE_OK ) pPager->errCode = SQLITE_OK;
29027         pager_reset(pPager);
29028         if( pPager->stmtOpen ){
29029           sqlite3OsClose(pPager->stfd);
29030           sqlite3BitvecDestroy(pPager->pInStmt);
29031           pPager->pInStmt = 0;
29032         }
29033         pPager->stmtOpen = 0;
29034         pPager->stmtInUse = 0;
29035         pPager->journalOff = 0;
29036         pPager->journalStarted = 0;
29037         pPager->stmtAutoopen = 0;
29038         pPager->origDbSize = 0;
29039       }
29040     }
29041
29042     if( !MEMDB || pPager->errCode==SQLITE_OK ){
29043       pPager->state = PAGER_UNLOCK;
29044       pPager->changeCountDone = 0;
29045     }
29046   }
29047 }
29048
29049 /*
29050 ** Execute a rollback if a transaction is active and unlock the 
29051 ** database file. If the pager has already entered the error state, 
29052 ** do not attempt the rollback.
29053 */
29054 static void pagerUnlockAndRollback(Pager *p){
29055   if( p->errCode==SQLITE_OK && p->state>=PAGER_RESERVED ){
29056     sqlite3BeginBenignMalloc();
29057     sqlite3PagerRollback(p);
29058     sqlite3EndBenignMalloc();
29059   }
29060   pager_unlock(p);
29061 }
29062
29063 /*
29064 ** This routine ends a transaction.  A transaction is ended by either
29065 ** a COMMIT or a ROLLBACK.
29066 **
29067 ** When this routine is called, the pager has the journal file open and
29068 ** a RESERVED or EXCLUSIVE lock on the database.  This routine will release
29069 ** the database lock and acquires a SHARED lock in its place if that is
29070 ** the appropriate thing to do.  Release locks usually is appropriate,
29071 ** unless we are in exclusive access mode or unless this is a 
29072 ** COMMIT AND BEGIN or ROLLBACK AND BEGIN operation.
29073 **
29074 ** The journal file is either deleted or truncated.
29075 **
29076 ** TODO: Consider keeping the journal file open for temporary databases.
29077 ** This might give a performance improvement on windows where opening
29078 ** a file is an expensive operation.
29079 */
29080 static int pager_end_transaction(Pager *pPager, int hasMaster){
29081   int rc = SQLITE_OK;
29082   int rc2 = SQLITE_OK;
29083   assert( !MEMDB );
29084   if( pPager->state<PAGER_RESERVED ){
29085     return SQLITE_OK;
29086   }
29087   sqlite3PagerStmtCommit(pPager);
29088   if( pPager->stmtOpen && !pPager->exclusiveMode ){
29089     sqlite3OsClose(pPager->stfd);
29090     pPager->stmtOpen = 0;
29091   }
29092   if( pPager->journalOpen ){
29093     if( pPager->exclusiveMode 
29094      || pPager->journalMode==PAGER_JOURNALMODE_PERSIST
29095     ){
29096       rc = zeroJournalHdr(pPager, hasMaster);
29097       pager_error(pPager, rc);
29098       pPager->journalOff = 0;
29099       pPager->journalStarted = 0;
29100     }else{
29101       sqlite3OsClose(pPager->jfd);
29102       pPager->journalOpen = 0;
29103       if( rc==SQLITE_OK && !pPager->tempFile ){
29104         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
29105       }
29106     }
29107     sqlite3BitvecDestroy(pPager->pInJournal);
29108     pPager->pInJournal = 0;
29109     sqlite3BitvecDestroy(pPager->pAlwaysRollback);
29110     pPager->pAlwaysRollback = 0;
29111     sqlite3PcacheCleanAll(pPager->pPCache);
29112 #ifdef SQLITE_CHECK_PAGES
29113     sqlite3PcacheIterate(pPager->pPCache, pager_set_pagehash);
29114 #endif
29115     sqlite3PcacheClearFlags(pPager->pPCache,
29116        PGHDR_IN_JOURNAL | PGHDR_NEED_SYNC
29117     );
29118     pPager->dirtyCache = 0;
29119     pPager->nRec = 0;
29120   }else{
29121     assert( pPager->pInJournal==0 );
29122   }
29123
29124   if( !pPager->exclusiveMode ){
29125     rc2 = osUnlock(pPager->fd, SHARED_LOCK);
29126     pPager->state = PAGER_SHARED;
29127   }else if( pPager->state==PAGER_SYNCED ){
29128     pPager->state = PAGER_EXCLUSIVE;
29129   }
29130   pPager->origDbSize = 0;
29131   pPager->setMaster = 0;
29132   pPager->needSync = 0;
29133   /* lruListSetFirstSynced(pPager); */
29134   pPager->dbSize = -1;
29135   pPager->dbModified = 0;
29136
29137   return (rc==SQLITE_OK?rc2:rc);
29138 }
29139
29140 /*
29141 ** Compute and return a checksum for the page of data.
29142 **
29143 ** This is not a real checksum.  It is really just the sum of the 
29144 ** random initial value and the page number.  We experimented with
29145 ** a checksum of the entire data, but that was found to be too slow.
29146 **
29147 ** Note that the page number is stored at the beginning of data and
29148 ** the checksum is stored at the end.  This is important.  If journal
29149 ** corruption occurs due to a power failure, the most likely scenario
29150 ** is that one end or the other of the record will be changed.  It is
29151 ** much less likely that the two ends of the journal record will be
29152 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
29153 ** though fast and simple, catches the mostly likely kind of corruption.
29154 **
29155 ** FIX ME:  Consider adding every 200th (or so) byte of the data to the
29156 ** checksum.  That way if a single page spans 3 or more disk sectors and
29157 ** only the middle sector is corrupt, we will still have a reasonable
29158 ** chance of failing the checksum and thus detecting the problem.
29159 */
29160 static u32 pager_cksum(Pager *pPager, const u8 *aData){
29161   u32 cksum = pPager->cksumInit;
29162   int i = pPager->pageSize-200;
29163   while( i>0 ){
29164     cksum += aData[i];
29165     i -= 200;
29166   }
29167   return cksum;
29168 }
29169
29170 /* Forward declaration */
29171 static void makeClean(PgHdr*);
29172
29173 /*
29174 ** Read a single page from the journal file opened on file descriptor
29175 ** jfd.  Playback this one page.
29176 **
29177 ** The isMainJrnl flag is true if this is the main rollback journal and
29178 ** false for the statement journal.  The main rollback journal uses
29179 ** checksums - the statement journal does not.
29180 */
29181 static int pager_playback_one_page(
29182   Pager *pPager,       /* The pager being played back */
29183   sqlite3_file *jfd,   /* The file that is the journal being rolled back */
29184   i64 offset,          /* Offset of the page within the journal */
29185   int isMainJrnl       /* True for main rollback journal. False for Stmt jrnl */
29186 ){
29187   int rc;
29188   PgHdr *pPg;                   /* An existing page in the cache */
29189   Pgno pgno;                    /* The page number of a page in journal */
29190   u32 cksum;                    /* Checksum used for sanity checking */
29191   u8 *aData = (u8 *)pPager->pTmpSpace;   /* Temp storage for a page */
29192
29193   /* isMainJrnl should be true for the main journal and false for
29194   ** statement journals.  Verify that this is always the case
29195   */
29196   assert( jfd == (isMainJrnl ? pPager->jfd : pPager->stfd) );
29197   assert( aData );
29198
29199   rc = read32bits(jfd, offset, &pgno);
29200   if( rc!=SQLITE_OK ) return rc;
29201   rc = sqlite3OsRead(jfd, aData, pPager->pageSize, offset+4);
29202   if( rc!=SQLITE_OK ) return rc;
29203   pPager->journalOff += pPager->pageSize + 4;
29204
29205   /* Sanity checking on the page.  This is more important that I originally
29206   ** thought.  If a power failure occurs while the journal is being written,
29207   ** it could cause invalid data to be written into the journal.  We need to
29208   ** detect this invalid data (with high probability) and ignore it.
29209   */
29210   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
29211     return SQLITE_DONE;
29212   }
29213   if( pgno>(unsigned)pPager->dbSize ){
29214     return SQLITE_OK;
29215   }
29216   if( isMainJrnl ){
29217     rc = read32bits(jfd, offset+pPager->pageSize+4, &cksum);
29218     if( rc ) return rc;
29219     pPager->journalOff += 4;
29220     if( pager_cksum(pPager, aData)!=cksum ){
29221       return SQLITE_DONE;
29222     }
29223   }
29224
29225   assert( pPager->state==PAGER_RESERVED || pPager->state>=PAGER_EXCLUSIVE );
29226
29227   /* If the pager is in RESERVED state, then there must be a copy of this
29228   ** page in the pager cache. In this case just update the pager cache,
29229   ** not the database file. The page is left marked dirty in this case.
29230   **
29231   ** An exception to the above rule: If the database is in no-sync mode
29232   ** and a page is moved during an incremental vacuum then the page may
29233   ** not be in the pager cache. Later: if a malloc() or IO error occurs
29234   ** during a Movepage() call, then the page may not be in the cache
29235   ** either. So the condition described in the above paragraph is not
29236   ** assert()able.
29237   **
29238   ** If in EXCLUSIVE state, then we update the pager cache if it exists
29239   ** and the main file. The page is then marked not dirty.
29240   **
29241   ** Ticket #1171:  The statement journal might contain page content that is
29242   ** different from the page content at the start of the transaction.
29243   ** This occurs when a page is changed prior to the start of a statement
29244   ** then changed again within the statement.  When rolling back such a
29245   ** statement we must not write to the original database unless we know
29246   ** for certain that original page contents are synced into the main rollback
29247   ** journal.  Otherwise, a power loss might leave modified data in the
29248   ** database file without an entry in the rollback journal that can
29249   ** restore the database to its original form.  Two conditions must be
29250   ** met before writing to the database files. (1) the database must be
29251   ** locked.  (2) we know that the original page content is fully synced
29252   ** in the main journal either because the page is not in cache or else
29253   ** the page is marked as needSync==0.
29254   **
29255   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
29256   ** is possible to fail a statement on a database that does not yet exist.
29257   ** Do not attempt to write if database file has never been opened.
29258   */
29259   pPg = pager_lookup(pPager, pgno);
29260   PAGERTRACE4("PLAYBACK %d page %d hash(%08x)\n",
29261                PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, aData));
29262   if( (pPager->state>=PAGER_EXCLUSIVE)
29263    && (pPg==0 || 0==(pPg->flags&PGHDR_NEED_SYNC))
29264    && (pPager->fd->pMethods)
29265   ){
29266     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
29267     rc = sqlite3OsWrite(pPager->fd, aData, pPager->pageSize, ofst);
29268   }
29269   if( pPg ){
29270     /* No page should ever be explicitly rolled back that is in use, except
29271     ** for page 1 which is held in use in order to keep the lock on the
29272     ** database active. However such a page may be rolled back as a result
29273     ** of an internal error resulting in an automatic call to
29274     ** sqlite3PagerRollback().
29275     */
29276     void *pData;
29277     pData = pPg->pData;
29278     memcpy(pData, aData, pPager->pageSize);
29279     if( pPager->xReiniter ){
29280       pPager->xReiniter(pPg);
29281     }
29282     if( isMainJrnl ) makeClean(pPg);
29283 #ifdef SQLITE_CHECK_PAGES
29284     pPg->pageHash = pager_pagehash(pPg);
29285 #endif
29286     /* If this was page 1, then restore the value of Pager.dbFileVers.
29287     ** Do this before any decoding. */
29288     if( pgno==1 ){
29289       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
29290     }
29291
29292     /* Decode the page just read from disk */
29293     CODEC1(pPager, pData, pPg->pgno, 3);
29294     sqlite3PcacheRelease(pPg);
29295   }
29296   return rc;
29297 }
29298
29299 /*
29300 ** Parameter zMaster is the name of a master journal file. A single journal
29301 ** file that referred to the master journal file has just been rolled back.
29302 ** This routine checks if it is possible to delete the master journal file,
29303 ** and does so if it is.
29304 **
29305 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
29306 ** available for use within this function.
29307 **
29308 **
29309 ** The master journal file contains the names of all child journals.
29310 ** To tell if a master journal can be deleted, check to each of the
29311 ** children.  If all children are either missing or do not refer to
29312 ** a different master journal, then this master journal can be deleted.
29313 */
29314 static int pager_delmaster(Pager *pPager, const char *zMaster){
29315   sqlite3_vfs *pVfs = pPager->pVfs;
29316   int rc;
29317   int master_open = 0;
29318   sqlite3_file *pMaster;
29319   sqlite3_file *pJournal;
29320   char *zMasterJournal = 0; /* Contents of master journal file */
29321   i64 nMasterJournal;       /* Size of master journal file */
29322
29323   /* Open the master journal file exclusively in case some other process
29324   ** is running this routine also. Not that it makes too much difference.
29325   */
29326   pMaster = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile * 2);
29327   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
29328   if( !pMaster ){
29329     rc = SQLITE_NOMEM;
29330   }else{
29331     int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
29332     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
29333   }
29334   if( rc!=SQLITE_OK ) goto delmaster_out;
29335   master_open = 1;
29336
29337   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
29338   if( rc!=SQLITE_OK ) goto delmaster_out;
29339
29340   if( nMasterJournal>0 ){
29341     char *zJournal;
29342     char *zMasterPtr = 0;
29343     int nMasterPtr = pPager->pVfs->mxPathname+1;
29344
29345     /* Load the entire master journal file into space obtained from
29346     ** sqlite3_malloc() and pointed to by zMasterJournal. 
29347     */
29348     zMasterJournal = (char *)sqlite3Malloc(nMasterJournal + nMasterPtr);
29349     if( !zMasterJournal ){
29350       rc = SQLITE_NOMEM;
29351       goto delmaster_out;
29352     }
29353     zMasterPtr = &zMasterJournal[nMasterJournal];
29354     rc = sqlite3OsRead(pMaster, zMasterJournal, nMasterJournal, 0);
29355     if( rc!=SQLITE_OK ) goto delmaster_out;
29356
29357     zJournal = zMasterJournal;
29358     while( (zJournal-zMasterJournal)<nMasterJournal ){
29359       int exists;
29360       rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
29361       if( rc!=SQLITE_OK ){
29362         goto delmaster_out;
29363       }
29364       if( exists ){
29365         /* One of the journals pointed to by the master journal exists.
29366         ** Open it and check if it points at the master journal. If
29367         ** so, return without deleting the master journal file.
29368         */
29369         int c;
29370         int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
29371         rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
29372         if( rc!=SQLITE_OK ){
29373           goto delmaster_out;
29374         }
29375
29376         rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
29377         sqlite3OsClose(pJournal);
29378         if( rc!=SQLITE_OK ){
29379           goto delmaster_out;
29380         }
29381
29382         c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
29383         if( c ){
29384           /* We have a match. Do not delete the master journal file. */
29385           goto delmaster_out;
29386         }
29387       }
29388       zJournal += (strlen(zJournal)+1);
29389     }
29390   }
29391   
29392   rc = sqlite3OsDelete(pVfs, zMaster, 0);
29393
29394 delmaster_out:
29395   if( zMasterJournal ){
29396     sqlite3_free(zMasterJournal);
29397   }  
29398   if( master_open ){
29399     sqlite3OsClose(pMaster);
29400   }
29401   sqlite3_free(pMaster);
29402   return rc;
29403 }
29404
29405
29406 static void pager_truncate_cache(Pager *pPager);
29407
29408 /*
29409 ** Truncate the main file of the given pager to the number of pages
29410 ** indicated. Also truncate the cached representation of the file.
29411 **
29412 ** Might might be the case that the file on disk is smaller than nPage.
29413 ** This can happen, for example, if we are in the middle of a transaction
29414 ** which has extended the file size and the new pages are still all held
29415 ** in cache, then an INSERT or UPDATE does a statement rollback.  Some
29416 ** operating system implementations can get confused if you try to
29417 ** truncate a file to some size that is larger than it currently is,
29418 ** so detect this case and write a single zero byte to the end of the new
29419 ** file instead.
29420 */
29421 static int pager_truncate(Pager *pPager, int nPage){
29422   int rc = SQLITE_OK;
29423   if( pPager->state>=PAGER_EXCLUSIVE && pPager->fd->pMethods ){
29424     i64 currentSize, newSize;
29425     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
29426     newSize = pPager->pageSize*(i64)nPage;
29427     if( rc==SQLITE_OK && currentSize!=newSize ){
29428       if( currentSize>newSize ){
29429         rc = sqlite3OsTruncate(pPager->fd, newSize);
29430       }else{
29431         rc = sqlite3OsWrite(pPager->fd, "", 1, newSize-1);
29432       }
29433     }
29434   }
29435   if( rc==SQLITE_OK ){
29436     pPager->dbSize = nPage;
29437     pager_truncate_cache(pPager);
29438   }
29439   return rc;
29440 }
29441
29442 /*
29443 ** Set the sectorSize for the given pager.
29444 **
29445 ** The sector size is at least as big as the sector size reported
29446 ** by sqlite3OsSectorSize().  The minimum sector size is 512.
29447 */
29448 static void setSectorSize(Pager *pPager){
29449   assert(pPager->fd->pMethods||pPager->tempFile);
29450   if( !pPager->tempFile ){
29451     /* Sector size doesn't matter for temporary files. Also, the file
29452     ** may not have been opened yet, in whcih case the OsSectorSize()
29453     ** call will segfault.
29454     */
29455     pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
29456   }
29457   if( pPager->sectorSize<512 ){
29458     pPager->sectorSize = 512;
29459   }
29460 }
29461
29462 /*
29463 ** Playback the journal and thus restore the database file to
29464 ** the state it was in before we started making changes.  
29465 **
29466 ** The journal file format is as follows: 
29467 **
29468 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
29469 **  (2)  4 byte big-endian integer which is the number of valid page records
29470 **       in the journal.  If this value is 0xffffffff, then compute the
29471 **       number of page records from the journal size.
29472 **  (3)  4 byte big-endian integer which is the initial value for the 
29473 **       sanity checksum.
29474 **  (4)  4 byte integer which is the number of pages to truncate the
29475 **       database to during a rollback.
29476 **  (5)  4 byte big-endian integer which is the sector size.  The header
29477 **       is this many bytes in size.
29478 **  (6)  4 byte big-endian integer which is the page case.
29479 **  (7)  4 byte integer which is the number of bytes in the master journal
29480 **       name.  The value may be zero (indicate that there is no master
29481 **       journal.)
29482 **  (8)  N bytes of the master journal name.  The name will be nul-terminated
29483 **       and might be shorter than the value read from (5).  If the first byte
29484 **       of the name is \000 then there is no master journal.  The master
29485 **       journal name is stored in UTF-8.
29486 **  (9)  Zero or more pages instances, each as follows:
29487 **        +  4 byte page number.
29488 **        +  pPager->pageSize bytes of data.
29489 **        +  4 byte checksum
29490 **
29491 ** When we speak of the journal header, we mean the first 8 items above.
29492 ** Each entry in the journal is an instance of the 9th item.
29493 **
29494 ** Call the value from the second bullet "nRec".  nRec is the number of
29495 ** valid page entries in the journal.  In most cases, you can compute the
29496 ** value of nRec from the size of the journal file.  But if a power
29497 ** failure occurred while the journal was being written, it could be the
29498 ** case that the size of the journal file had already been increased but
29499 ** the extra entries had not yet made it safely to disk.  In such a case,
29500 ** the value of nRec computed from the file size would be too large.  For
29501 ** that reason, we always use the nRec value in the header.
29502 **
29503 ** If the nRec value is 0xffffffff it means that nRec should be computed
29504 ** from the file size.  This value is used when the user selects the
29505 ** no-sync option for the journal.  A power failure could lead to corruption
29506 ** in this case.  But for things like temporary table (which will be
29507 ** deleted when the power is restored) we don't care.  
29508 **
29509 ** If the file opened as the journal file is not a well-formed
29510 ** journal file then all pages up to the first corrupted page are rolled
29511 ** back (or no pages if the journal header is corrupted). The journal file
29512 ** is then deleted and SQLITE_OK returned, just as if no corruption had
29513 ** been encountered.
29514 **
29515 ** If an I/O or malloc() error occurs, the journal-file is not deleted
29516 ** and an error code is returned.
29517 */
29518 static int pager_playback(Pager *pPager, int isHot){
29519   sqlite3_vfs *pVfs = pPager->pVfs;
29520   i64 szJ;                 /* Size of the journal file in bytes */
29521   u32 nRec;                /* Number of Records in the journal */
29522   u32 u;                   /* Unsigned loop counter */
29523   Pgno mxPg = 0;           /* Size of the original file in pages */
29524   int rc;                  /* Result code of a subroutine */
29525   int res = 1;             /* Value returned by sqlite3OsAccess() */
29526   char *zMaster = 0;       /* Name of master journal file if any */
29527
29528   /* Figure out how many records are in the journal.  Abort early if
29529   ** the journal is empty.
29530   */
29531   assert( pPager->journalOpen );
29532   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
29533   if( rc!=SQLITE_OK || szJ==0 ){
29534     goto end_playback;
29535   }
29536
29537   /* Read the master journal name from the journal, if it is present.
29538   ** If a master journal file name is specified, but the file is not
29539   ** present on disk, then the journal is not hot and does not need to be
29540   ** played back.
29541   */
29542   zMaster = pPager->pTmpSpace;
29543   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
29544   if( rc==SQLITE_OK && zMaster[0] ){
29545     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
29546   }
29547   zMaster = 0;
29548   if( rc!=SQLITE_OK || !res ){
29549     goto end_playback;
29550   }
29551   pPager->journalOff = 0;
29552
29553   /* This loop terminates either when the readJournalHdr() call returns
29554   ** SQLITE_DONE or an IO error occurs. */
29555   while( 1 ){
29556
29557     /* Read the next journal header from the journal file.  If there are
29558     ** not enough bytes left in the journal file for a complete header, or
29559     ** it is corrupted, then a process must of failed while writing it.
29560     ** This indicates nothing more needs to be rolled back.
29561     */
29562     rc = readJournalHdr(pPager, szJ, &nRec, &mxPg);
29563     if( rc!=SQLITE_OK ){ 
29564       if( rc==SQLITE_DONE ){
29565         rc = SQLITE_OK;
29566       }
29567       goto end_playback;
29568     }
29569
29570     /* If nRec is 0xffffffff, then this journal was created by a process
29571     ** working in no-sync mode. This means that the rest of the journal
29572     ** file consists of pages, there are no more journal headers. Compute
29573     ** the value of nRec based on this assumption.
29574     */
29575     if( nRec==0xffffffff ){
29576       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
29577       nRec = (szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager);
29578     }
29579
29580     /* If nRec is 0 and this rollback is of a transaction created by this
29581     ** process and if this is the final header in the journal, then it means
29582     ** that this part of the journal was being filled but has not yet been
29583     ** synced to disk.  Compute the number of pages based on the remaining
29584     ** size of the file.
29585     **
29586     ** The third term of the test was added to fix ticket #2565.
29587     */
29588     if( nRec==0 && !isHot &&
29589         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
29590       nRec = (szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager);
29591     }
29592
29593     /* If this is the first header read from the journal, truncate the
29594     ** database file back to its original size.
29595     */
29596     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
29597       rc = pager_truncate(pPager, mxPg);
29598       if( rc!=SQLITE_OK ){
29599         goto end_playback;
29600       }
29601     }
29602
29603     /* Copy original pages out of the journal and back into the database file.
29604     */
29605     for(u=0; u<nRec; u++){
29606       rc = pager_playback_one_page(pPager, pPager->jfd, pPager->journalOff, 1);
29607       if( rc!=SQLITE_OK ){
29608         if( rc==SQLITE_DONE ){
29609           rc = SQLITE_OK;
29610           pPager->journalOff = szJ;
29611           break;
29612         }else{
29613           /* If we are unable to rollback, then the database is probably
29614           ** going to end up being corrupt.  It is corrupt to us, anyhow.
29615           ** Perhaps the next process to come along can fix it....
29616           */
29617           rc = SQLITE_CORRUPT;
29618           goto end_playback;
29619         }
29620       }
29621     }
29622   }
29623   /*NOTREACHED*/
29624   assert( 0 );
29625
29626 end_playback:
29627   if( rc==SQLITE_OK ){
29628     zMaster = pPager->pTmpSpace;
29629     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
29630   }
29631   if( rc==SQLITE_OK ){
29632     rc = pager_end_transaction(pPager, zMaster[0]!='\0');
29633   }
29634   if( rc==SQLITE_OK && zMaster[0] ){
29635     /* If there was a master journal and this routine will return success,
29636     ** see if it is possible to delete the master journal.
29637     */
29638     rc = pager_delmaster(pPager, zMaster);
29639   }
29640
29641   /* The Pager.sectorSize variable may have been updated while rolling
29642   ** back a journal created by a process with a different sector size
29643   ** value. Reset it to the correct value for this process.
29644   */
29645   setSectorSize(pPager);
29646   return rc;
29647 }
29648
29649 /*
29650 ** Playback the statement journal.
29651 **
29652 ** This is similar to playing back the transaction journal but with
29653 ** a few extra twists.
29654 **
29655 **    (1)  The number of pages in the database file at the start of
29656 **         the statement is stored in pPager->stmtSize, not in the
29657 **         journal file itself.
29658 **
29659 **    (2)  In addition to playing back the statement journal, also
29660 **         playback all pages of the transaction journal beginning
29661 **         at offset pPager->stmtJSize.
29662 */
29663 static int pager_stmt_playback(Pager *pPager){
29664   i64 szJ;                 /* Size of the full journal */
29665   i64 hdrOff;
29666   int nRec;                /* Number of Records */
29667   int i;                   /* Loop counter */
29668   int rc;
29669
29670   szJ = pPager->journalOff;
29671
29672   /* Set hdrOff to be the offset just after the end of the last journal
29673   ** page written before the first journal-header for this statement
29674   ** transaction was written, or the end of the file if no journal
29675   ** header was written.
29676   */
29677   hdrOff = pPager->stmtHdrOff;
29678   assert( pPager->fullSync || !hdrOff );
29679   if( !hdrOff ){
29680     hdrOff = szJ;
29681   }
29682   
29683   /* Truncate the database back to its original size.
29684   */
29685   rc = pager_truncate(pPager, pPager->stmtSize);
29686   assert( pPager->state>=PAGER_SHARED );
29687
29688   /* Figure out how many records are in the statement journal.
29689   */
29690   assert( pPager->stmtInUse && pPager->journalOpen );
29691   nRec = pPager->stmtNRec;
29692   
29693   /* Copy original pages out of the statement journal and back into the
29694   ** database file.  Note that the statement journal omits checksums from
29695   ** each record since power-failure recovery is not important to statement
29696   ** journals.
29697   */
29698   for(i=0; i<nRec; i++){
29699     i64 offset = i*(4+pPager->pageSize);
29700     rc = pager_playback_one_page(pPager, pPager->stfd, offset, 0);
29701     assert( rc!=SQLITE_DONE );
29702     if( rc!=SQLITE_OK ) goto end_stmt_playback;
29703   }
29704
29705   /* Now roll some pages back from the transaction journal. Pager.stmtJSize
29706   ** was the size of the journal file when this statement was started, so
29707   ** everything after that needs to be rolled back, either into the
29708   ** database, the memory cache, or both.
29709   **
29710   ** If it is not zero, then Pager.stmtHdrOff is the offset to the start
29711   ** of the first journal header written during this statement transaction.
29712   */
29713   pPager->journalOff = pPager->stmtJSize;
29714   pPager->cksumInit = pPager->stmtCksum;
29715   while( pPager->journalOff < hdrOff ){
29716     rc = pager_playback_one_page(pPager, pPager->jfd, pPager->journalOff, 1);
29717     assert( rc!=SQLITE_DONE );
29718     if( rc!=SQLITE_OK ) goto end_stmt_playback;
29719   }
29720
29721   while( pPager->journalOff < szJ ){
29722     u32 nJRec;         /* Number of Journal Records */
29723     u32 dummy;
29724     rc = readJournalHdr(pPager, szJ, &nJRec, &dummy);
29725     if( rc!=SQLITE_OK ){
29726       assert( rc!=SQLITE_DONE );
29727       goto end_stmt_playback;
29728     }
29729     if( nJRec==0 ){
29730       nJRec = (szJ - pPager->journalOff) / (pPager->pageSize+8);
29731     }
29732     for(i=nJRec-1; i>=0 && pPager->journalOff < szJ; i--){
29733       rc = pager_playback_one_page(pPager, pPager->jfd, pPager->journalOff, 1);
29734       assert( rc!=SQLITE_DONE );
29735       if( rc!=SQLITE_OK ) goto end_stmt_playback;
29736     }
29737   }
29738
29739   pPager->journalOff = szJ;
29740   
29741 end_stmt_playback:
29742   if( rc==SQLITE_OK) {
29743     pPager->journalOff = szJ;
29744     /* pager_reload_cache(pPager); */
29745   }
29746   return rc;
29747 }
29748
29749 /*
29750 ** Change the maximum number of in-memory pages that are allowed.
29751 */
29752 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
29753   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
29754 }
29755
29756 /*
29757 ** Adjust the robustness of the database to damage due to OS crashes
29758 ** or power failures by changing the number of syncs()s when writing
29759 ** the rollback journal.  There are three levels:
29760 **
29761 **    OFF       sqlite3OsSync() is never called.  This is the default
29762 **              for temporary and transient files.
29763 **
29764 **    NORMAL    The journal is synced once before writes begin on the
29765 **              database.  This is normally adequate protection, but
29766 **              it is theoretically possible, though very unlikely,
29767 **              that an inopertune power failure could leave the journal
29768 **              in a state which would cause damage to the database
29769 **              when it is rolled back.
29770 **
29771 **    FULL      The journal is synced twice before writes begin on the
29772 **              database (with some additional information - the nRec field
29773 **              of the journal header - being written in between the two
29774 **              syncs).  If we assume that writing a
29775 **              single disk sector is atomic, then this mode provides
29776 **              assurance that the journal will not be corrupted to the
29777 **              point of causing damage to the database during rollback.
29778 **
29779 ** Numeric values associated with these states are OFF==1, NORMAL=2,
29780 ** and FULL=3.
29781 */
29782 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
29783 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager *pPager, int level, int bFullFsync){
29784   pPager->noSync =  level==1 || pPager->tempFile || MEMDB;
29785   pPager->fullSync = level==3 && !pPager->tempFile;
29786   pPager->sync_flags = (bFullFsync?SQLITE_SYNC_FULL:SQLITE_SYNC_NORMAL);
29787   if( pPager->noSync ) pPager->needSync = 0;
29788 }
29789 #endif
29790
29791 /*
29792 ** The following global variable is incremented whenever the library
29793 ** attempts to open a temporary file.  This information is used for
29794 ** testing and analysis only.  
29795 */
29796 #ifdef SQLITE_TEST
29797 SQLITE_API int sqlite3_opentemp_count = 0;
29798 #endif
29799
29800 /*
29801 ** Open a temporary file. 
29802 **
29803 ** Write the file descriptor into *fd.  Return SQLITE_OK on success or some
29804 ** other error code if we fail. The OS will automatically delete the temporary
29805 ** file when it is closed.
29806 */
29807 static int sqlite3PagerOpentemp(
29808   Pager *pPager,        /* The pager object */
29809   sqlite3_file *pFile,  /* Write the file descriptor here */
29810   int vfsFlags          /* Flags passed through to the VFS */
29811 ){
29812   int rc;
29813
29814 #ifdef SQLITE_TEST
29815   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
29816 #endif
29817
29818   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
29819             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
29820   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
29821   assert( rc!=SQLITE_OK || pFile->pMethods );
29822   return rc;
29823 }
29824
29825 static int pagerStress(void *,PgHdr *);
29826
29827 /*
29828 ** Create a new page cache and put a pointer to the page cache in *ppPager.
29829 ** The file to be cached need not exist.  The file is not locked until
29830 ** the first call to sqlite3PagerGet() and is only held open until the
29831 ** last page is released using sqlite3PagerUnref().
29832 **
29833 ** If zFilename is NULL then a randomly-named temporary file is created
29834 ** and used as the file to be cached.  The file will be deleted
29835 ** automatically when it is closed.
29836 **
29837 ** If zFilename is ":memory:" then all information is held in cache.
29838 ** It is never written to disk.  This can be used to implement an
29839 ** in-memory database.
29840 */
29841 SQLITE_PRIVATE int sqlite3PagerOpen(
29842   sqlite3_vfs *pVfs,       /* The virtual file system to use */
29843   Pager **ppPager,         /* Return the Pager structure here */
29844   const char *zFilename,   /* Name of the database file to open */
29845   void (*xDesc)(DbPage*),  /* Page destructor function */
29846   int nExtra,              /* Extra bytes append to each in-memory page */
29847   int flags,               /* flags controlling this file */
29848   int vfsFlags             /* flags passed through to sqlite3_vfs.xOpen() */
29849 ){
29850   u8 *pPtr;
29851   Pager *pPager = 0;
29852   int rc = SQLITE_OK;
29853   int i;
29854   int tempFile = 0;
29855   int memDb = 0;
29856   int readOnly = 0;
29857   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0;
29858   int noReadlock = (flags & PAGER_NO_READLOCK)!=0;
29859   int journalFileSize = sqlite3JournalSize(pVfs);
29860   int pcacheSize = sqlite3PcacheSize();
29861   int szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;
29862   char *zPathname = 0;
29863   int nPathname = 0;
29864
29865   /* The default return is a NULL pointer */
29866   *ppPager = 0;
29867
29868   /* Compute and store the full pathname in an allocated buffer pointed
29869   ** to by zPathname, length nPathname. Or, if this is a temporary file,
29870   ** leave both nPathname and zPathname set to 0.
29871   */
29872   if( zFilename && zFilename[0] ){
29873     nPathname = pVfs->mxPathname+1;
29874     zPathname = sqlite3Malloc(nPathname*2);
29875     if( zPathname==0 ){
29876       return SQLITE_NOMEM;
29877     }
29878 #ifndef SQLITE_OMIT_MEMORYDB
29879     if( strcmp(zFilename,":memory:")==0 ){
29880       memDb = 1;
29881       zPathname[0] = 0;
29882       useJournal = 0;
29883     }else
29884 #endif
29885     {
29886       rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
29887     }
29888     if( rc!=SQLITE_OK ){
29889       sqlite3_free(zPathname);
29890       return rc;
29891     }
29892     nPathname = strlen(zPathname);
29893   }
29894
29895   /* Allocate memory for the pager structure */
29896   pPager = sqlite3MallocZero(
29897     sizeof(*pPager) +           /* Pager structure */
29898     pcacheSize      +           /* PCache object */
29899     journalFileSize +           /* The journal file structure */ 
29900     pVfs->szOsFile * 3 +        /* The main db and two journal files */ 
29901     3*nPathname + 40            /* zFilename, zDirectory, zJournal */
29902   );
29903   if( !pPager ){
29904     sqlite3_free(zPathname);
29905     return SQLITE_NOMEM;
29906   }
29907   pPager->pPCache = (PCache *)&pPager[1];
29908   pPtr = ((u8 *)&pPager[1]) + pcacheSize;
29909   pPager->vfsFlags = vfsFlags;
29910   pPager->fd = (sqlite3_file*)&pPtr[pVfs->szOsFile*0];
29911   pPager->stfd = (sqlite3_file*)&pPtr[pVfs->szOsFile*1];
29912   pPager->jfd = (sqlite3_file*)&pPtr[pVfs->szOsFile*2];
29913   pPager->zFilename = (char*)&pPtr[pVfs->szOsFile*2+journalFileSize];
29914   pPager->zDirectory = &pPager->zFilename[nPathname+1];
29915   pPager->zJournal = &pPager->zDirectory[nPathname+1];
29916   pPager->pVfs = pVfs;
29917   if( zPathname ){
29918     memcpy(pPager->zFilename, zPathname, nPathname+1);
29919     sqlite3_free(zPathname);
29920   }
29921
29922   /* Open the pager file.
29923   */
29924   if( zFilename && zFilename[0] && !memDb ){
29925     if( nPathname>(pVfs->mxPathname - sizeof("-journal")) ){
29926       rc = SQLITE_CANTOPEN;
29927     }else{
29928       int fout = 0;
29929       rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd,
29930                          pPager->vfsFlags, &fout);
29931       readOnly = (fout&SQLITE_OPEN_READONLY);
29932
29933       /* If the file was successfully opened for read/write access,
29934       ** choose a default page size in case we have to create the
29935       ** database file. The default page size is the maximum of:
29936       **
29937       **    + SQLITE_DEFAULT_PAGE_SIZE,
29938       **    + The value returned by sqlite3OsSectorSize()
29939       **    + The largest page size that can be written atomically.
29940       */
29941       if( rc==SQLITE_OK && !readOnly ){
29942         int iSectorSize = sqlite3OsSectorSize(pPager->fd);
29943         if( szPageDflt<iSectorSize ){
29944           szPageDflt = iSectorSize;
29945         }
29946 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
29947         {
29948           int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
29949           int ii;
29950           assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
29951           assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
29952           assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
29953           for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
29954             if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ) szPageDflt = ii;
29955           }
29956         }
29957 #endif
29958         if( szPageDflt>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
29959           szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
29960         }
29961       }
29962     }
29963   }else if( !memDb ){
29964     /* If a temporary file is requested, it is not opened immediately.
29965     ** In this case we accept the default page size and delay actually
29966     ** opening the file until the first call to OsWrite().
29967     */ 
29968     tempFile = 1;
29969     pPager->state = PAGER_EXCLUSIVE;
29970   }
29971
29972   if( pPager && rc==SQLITE_OK ){
29973     pPager->pTmpSpace = sqlite3PageMalloc(szPageDflt);
29974   }
29975
29976   /* If an error occured in either of the blocks above.
29977   ** Free the Pager structure and close the file.
29978   ** Since the pager is not allocated there is no need to set 
29979   ** any Pager.errMask variables.
29980   */
29981   if( !pPager || !pPager->pTmpSpace ){
29982     sqlite3OsClose(pPager->fd);
29983     sqlite3_free(pPager);
29984     return ((rc==SQLITE_OK)?SQLITE_NOMEM:rc);
29985   }
29986   nExtra = FORCE_ALIGNMENT(nExtra);
29987   sqlite3PcacheOpen(szPageDflt, nExtra, !memDb, xDesc, 
29988                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
29989
29990   PAGERTRACE3("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename);
29991   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
29992
29993   /* Fill in Pager.zDirectory[] */
29994   memcpy(pPager->zDirectory, pPager->zFilename, nPathname+1);
29995   for(i=strlen(pPager->zDirectory); i>0 && pPager->zDirectory[i-1]!='/'; i--){}
29996   if( i>0 ) pPager->zDirectory[i-1] = 0;
29997
29998   /* Fill in Pager.zJournal[] */
29999   if( zPathname ){
30000     memcpy(pPager->zJournal, pPager->zFilename, nPathname);
30001     memcpy(&pPager->zJournal[nPathname], "-journal", 9);
30002   }else{
30003     pPager->zJournal = 0;
30004   }
30005
30006   /* pPager->journalOpen = 0; */
30007   pPager->useJournal = useJournal;
30008   pPager->noReadlock = noReadlock && readOnly;
30009   /* pPager->stmtOpen = 0; */
30010   /* pPager->stmtInUse = 0; */
30011   /* pPager->nRef = 0; */
30012   pPager->dbSize = memDb-1;
30013   pPager->pageSize = szPageDflt;
30014   /* pPager->stmtSize = 0; */
30015   /* pPager->stmtJSize = 0; */
30016   /* pPager->nPage = 0; */
30017   pPager->mxPage = 100;
30018   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
30019   /* pPager->state = PAGER_UNLOCK; */
30020   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
30021   /* pPager->errMask = 0; */
30022   pPager->tempFile = tempFile;
30023   assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
30024           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
30025   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
30026   pPager->exclusiveMode = tempFile; 
30027   pPager->memDb = memDb;
30028   pPager->readOnly = readOnly;
30029   /* pPager->needSync = 0; */
30030   pPager->noSync = pPager->tempFile || !useJournal;
30031   pPager->fullSync = (pPager->noSync?0:1);
30032   pPager->sync_flags = SQLITE_SYNC_NORMAL;
30033   /* pPager->pFirst = 0; */
30034   /* pPager->pFirstSynced = 0; */
30035   /* pPager->pLast = 0; */
30036   pPager->nExtra = nExtra;
30037   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
30038   assert(pPager->fd->pMethods||memDb||tempFile);
30039   if( !memDb ){
30040     setSectorSize(pPager);
30041   }
30042   /* pPager->pBusyHandler = 0; */
30043   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
30044   *ppPager = pPager;
30045   return SQLITE_OK;
30046 }
30047
30048 /*
30049 ** Set the busy handler function.
30050 */
30051 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager *pPager, BusyHandler *pBusyHandler){
30052   pPager->pBusyHandler = pBusyHandler;
30053 }
30054
30055 /*
30056 ** Set the reinitializer for this pager.  If not NULL, the reinitializer
30057 ** is called when the content of a page in cache is restored to its original
30058 ** value as a result of a rollback.  The callback gives higher-level code
30059 ** an opportunity to restore the EXTRA section to agree with the restored
30060 ** page data.
30061 */
30062 SQLITE_PRIVATE void sqlite3PagerSetReiniter(Pager *pPager, void (*xReinit)(DbPage*)){
30063   pPager->xReiniter = xReinit;
30064 }
30065
30066 /*
30067 ** Set the page size to *pPageSize. If the suggest new page size is
30068 ** inappropriate, then an alternative page size is set to that
30069 ** value before returning.
30070 */
30071 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u16 *pPageSize){
30072   int rc = pPager->errCode;
30073   if( rc==SQLITE_OK ){
30074     u16 pageSize = *pPageSize;
30075     assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
30076     if( pageSize && pageSize!=pPager->pageSize 
30077      && (pPager->memDb==0 || pPager->dbSize==0)
30078      && sqlite3PcacheRefCount(pPager->pPCache)==0 
30079     ){
30080       char *pNew = (char *)sqlite3PageMalloc(pageSize);
30081       if( !pNew ){
30082         rc = SQLITE_NOMEM;
30083       }else{
30084         pager_reset(pPager);
30085         pPager->pageSize = pageSize;
30086         if( !pPager->memDb ) setSectorSize(pPager);
30087         sqlite3PageFree(pPager->pTmpSpace);
30088         pPager->pTmpSpace = pNew;
30089         sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
30090       }
30091     }
30092     *pPageSize = pPager->pageSize;
30093   }
30094   return rc;
30095 }
30096
30097 /*
30098 ** Return a pointer to the "temporary page" buffer held internally
30099 ** by the pager.  This is a buffer that is big enough to hold the
30100 ** entire content of a database page.  This buffer is used internally
30101 ** during rollback and will be overwritten whenever a rollback
30102 ** occurs.  But other modules are free to use it too, as long as
30103 ** no rollbacks are happening.
30104 */
30105 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
30106   return pPager->pTmpSpace;
30107 }
30108
30109 /*
30110 ** Attempt to set the maximum database page count if mxPage is positive. 
30111 ** Make no changes if mxPage is zero or negative.  And never reduce the
30112 ** maximum page count below the current size of the database.
30113 **
30114 ** Regardless of mxPage, return the current maximum page count.
30115 */
30116 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
30117   if( mxPage>0 ){
30118     pPager->mxPgno = mxPage;
30119   }
30120   sqlite3PagerPagecount(pPager, 0);
30121   return pPager->mxPgno;
30122 }
30123
30124 /*
30125 ** The following set of routines are used to disable the simulated
30126 ** I/O error mechanism.  These routines are used to avoid simulated
30127 ** errors in places where we do not care about errors.
30128 **
30129 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
30130 ** and generate no code.
30131 */
30132 #ifdef SQLITE_TEST
30133 SQLITE_API extern int sqlite3_io_error_pending;
30134 SQLITE_API extern int sqlite3_io_error_hit;
30135 static int saved_cnt;
30136 void disable_simulated_io_errors(void){
30137   saved_cnt = sqlite3_io_error_pending;
30138   sqlite3_io_error_pending = -1;
30139 }
30140 void enable_simulated_io_errors(void){
30141   sqlite3_io_error_pending = saved_cnt;
30142 }
30143 #else
30144 # define disable_simulated_io_errors()
30145 # define enable_simulated_io_errors()
30146 #endif
30147
30148 /*
30149 ** Read the first N bytes from the beginning of the file into memory
30150 ** that pDest points to. 
30151 **
30152 ** No error checking is done. The rational for this is that this function 
30153 ** may be called even if the file does not exist or contain a header. In 
30154 ** these cases sqlite3OsRead() will return an error, to which the correct 
30155 ** response is to zero the memory at pDest and continue.  A real IO error 
30156 ** will presumably recur and be picked up later (Todo: Think about this).
30157 */
30158 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
30159   int rc = SQLITE_OK;
30160   memset(pDest, 0, N);
30161   assert(MEMDB||pPager->fd->pMethods||pPager->tempFile);
30162   if( pPager->fd->pMethods ){
30163     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
30164     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
30165     if( rc==SQLITE_IOERR_SHORT_READ ){
30166       rc = SQLITE_OK;
30167     }
30168   }
30169   return rc;
30170 }
30171
30172 /*
30173 ** Return the total number of pages in the disk file associated with
30174 ** pPager. 
30175 **
30176 ** If the PENDING_BYTE lies on the page directly after the end of the
30177 ** file, then consider this page part of the file too. For example, if
30178 ** PENDING_BYTE is byte 4096 (the first byte of page 5) and the size of the
30179 ** file is 4096 bytes, 5 is returned instead of 4.
30180 */
30181 SQLITE_PRIVATE int sqlite3PagerPagecount(Pager *pPager, int *pnPage){
30182   i64 n = 0;
30183   int rc;
30184   assert( pPager!=0 );
30185   if( pPager->errCode ){
30186     rc = pPager->errCode;
30187     return rc;
30188   }
30189   if( pPager->dbSize>=0 ){
30190     n = pPager->dbSize;
30191   } else {
30192     assert(pPager->fd->pMethods||pPager->tempFile);
30193     if( (pPager->fd->pMethods)
30194      && (rc = sqlite3OsFileSize(pPager->fd, &n))!=SQLITE_OK ){
30195       pager_error(pPager, rc);
30196       return rc;
30197     }
30198     if( n>0 && n<pPager->pageSize ){
30199       n = 1;
30200     }else{
30201       n /= pPager->pageSize;
30202     }
30203     if( pPager->state!=PAGER_UNLOCK ){
30204       pPager->dbSize = n;
30205     }
30206   }
30207   if( n==(PENDING_BYTE/pPager->pageSize) ){
30208     n++;
30209   }
30210   if( n>pPager->mxPgno ){
30211     pPager->mxPgno = n;
30212   }
30213   if( pnPage ){
30214     *pnPage = n;
30215   }
30216   return SQLITE_OK;
30217 }
30218
30219 /*
30220 ** Forward declaration
30221 */
30222 static int syncJournal(Pager*);
30223
30224 /*
30225 ** This routine is used to truncate the cache when a database
30226 ** is truncated.  Drop from the cache all pages whose pgno is
30227 ** larger than pPager->dbSize and is unreferenced.
30228 **
30229 ** Referenced pages larger than pPager->dbSize are zeroed.
30230 **
30231 ** Actually, at the point this routine is called, it would be
30232 ** an error to have a referenced page.  But rather than delete
30233 ** that page and guarantee a subsequent segfault, it seems better
30234 ** to zero it and hope that we error out sanely.
30235 */
30236 static void pager_truncate_cache(Pager *pPager){
30237   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
30238 }
30239
30240 /*
30241 ** Try to obtain a lock on a file.  Invoke the busy callback if the lock
30242 ** is currently not available.  Repeat until the busy callback returns
30243 ** false or until the lock succeeds.
30244 **
30245 ** Return SQLITE_OK on success and an error code if we cannot obtain
30246 ** the lock.
30247 */
30248 static int pager_wait_on_lock(Pager *pPager, int locktype){
30249   int rc;
30250
30251   /* The OS lock values must be the same as the Pager lock values */
30252   assert( PAGER_SHARED==SHARED_LOCK );
30253   assert( PAGER_RESERVED==RESERVED_LOCK );
30254   assert( PAGER_EXCLUSIVE==EXCLUSIVE_LOCK );
30255
30256   /* If the file is currently unlocked then the size must be unknown */
30257   assert( pPager->state>=PAGER_SHARED || pPager->dbSize<0 || MEMDB );
30258
30259   if( pPager->state>=locktype ){
30260     rc = SQLITE_OK;
30261   }else{
30262     if( pPager->pBusyHandler ) pPager->pBusyHandler->nBusy = 0;
30263     do {
30264       rc = sqlite3OsLock(pPager->fd, locktype);
30265     }while( rc==SQLITE_BUSY && sqlite3InvokeBusyHandler(pPager->pBusyHandler) );
30266     if( rc==SQLITE_OK ){
30267       pPager->state = locktype;
30268       IOTRACE(("LOCK %p %d\n", pPager, locktype))
30269     }
30270   }
30271   return rc;
30272 }
30273
30274 /*
30275 ** Truncate the file to the number of pages specified.
30276 */
30277 SQLITE_PRIVATE int sqlite3PagerTruncate(Pager *pPager, Pgno nPage){
30278   int rc = SQLITE_OK;
30279   assert( pPager->state>=PAGER_SHARED || MEMDB );
30280
30281
30282   sqlite3PagerPagecount(pPager, 0);
30283   if( pPager->errCode ){
30284     rc = pPager->errCode;
30285   }else if( nPage<(unsigned)pPager->dbSize ){
30286     if( MEMDB ){
30287       pPager->dbSize = nPage;
30288       pager_truncate_cache(pPager);
30289     }else{
30290       rc = syncJournal(pPager);
30291       if( rc==SQLITE_OK ){
30292         /* Get an exclusive lock on the database before truncating. */
30293         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
30294       }
30295       if( rc==SQLITE_OK ){
30296         rc = pager_truncate(pPager, nPage);
30297       }
30298     }
30299   }
30300
30301   return rc;
30302 }
30303
30304 /*
30305 ** Shutdown the page cache.  Free all memory and close all files.
30306 **
30307 ** If a transaction was in progress when this routine is called, that
30308 ** transaction is rolled back.  All outstanding pages are invalidated
30309 ** and their memory is freed.  Any attempt to use a page associated
30310 ** with this page cache after this function returns will likely
30311 ** result in a coredump.
30312 **
30313 ** This function always succeeds. If a transaction is active an attempt
30314 ** is made to roll it back. If an error occurs during the rollback 
30315 ** a hot journal may be left in the filesystem but no error is returned
30316 ** to the caller.
30317 */
30318 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
30319
30320   disable_simulated_io_errors();
30321   sqlite3BeginBenignMalloc();
30322   pPager->errCode = 0;
30323   pPager->exclusiveMode = 0;
30324   pager_reset(pPager);
30325   pagerUnlockAndRollback(pPager);
30326   enable_simulated_io_errors();
30327   sqlite3EndBenignMalloc();
30328   PAGERTRACE2("CLOSE %d\n", PAGERID(pPager));
30329   IOTRACE(("CLOSE %p\n", pPager))
30330   if( pPager->journalOpen ){
30331     sqlite3OsClose(pPager->jfd);
30332   }
30333   sqlite3BitvecDestroy(pPager->pInJournal);
30334   sqlite3BitvecDestroy(pPager->pAlwaysRollback);
30335   if( pPager->stmtOpen ){
30336     sqlite3OsClose(pPager->stfd);
30337   }
30338   sqlite3OsClose(pPager->fd);
30339   /* Temp files are automatically deleted by the OS
30340   ** if( pPager->tempFile ){
30341   **   sqlite3OsDelete(pPager->zFilename);
30342   ** }
30343   */
30344
30345   sqlite3PageFree(pPager->pTmpSpace);
30346   sqlite3PcacheClose(pPager->pPCache);
30347   sqlite3_free(pPager);
30348   return SQLITE_OK;
30349 }
30350
30351 #if !defined(NDEBUG) || defined(SQLITE_TEST)
30352 /*
30353 ** Return the page number for the given page data.
30354 */
30355 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *p){
30356   return p->pgno;
30357 }
30358 #endif
30359
30360 /*
30361 ** Increment the reference count for a page.  The input pointer is
30362 ** a reference to the page data.
30363 */
30364 SQLITE_PRIVATE int sqlite3PagerRef(DbPage *pPg){
30365   sqlite3PcacheRef(pPg);
30366   return SQLITE_OK;
30367 }
30368
30369 /*
30370 ** Sync the journal.  In other words, make sure all the pages that have
30371 ** been written to the journal have actually reached the surface of the
30372 ** disk.  It is not safe to modify the original database file until after
30373 ** the journal has been synced.  If the original database is modified before
30374 ** the journal is synced and a power failure occurs, the unsynced journal
30375 ** data would be lost and we would be unable to completely rollback the
30376 ** database changes.  Database corruption would occur.
30377 ** 
30378 ** This routine also updates the nRec field in the header of the journal.
30379 ** (See comments on the pager_playback() routine for additional information.)
30380 ** If the sync mode is FULL, two syncs will occur.  First the whole journal
30381 ** is synced, then the nRec field is updated, then a second sync occurs.
30382 **
30383 ** For temporary databases, we do not care if we are able to rollback
30384 ** after a power failure, so no sync occurs.
30385 **
30386 ** If the IOCAP_SEQUENTIAL flag is set for the persistent media on which
30387 ** the database is stored, then OsSync() is never called on the journal
30388 ** file. In this case all that is required is to update the nRec field in
30389 ** the journal header.
30390 **
30391 ** This routine clears the needSync field of every page current held in
30392 ** memory.
30393 */
30394 static int syncJournal(Pager *pPager){
30395   int rc = SQLITE_OK;
30396
30397   /* Sync the journal before modifying the main database
30398   ** (assuming there is a journal and it needs to be synced.)
30399   */
30400   if( pPager->needSync ){
30401     if( !pPager->tempFile ){
30402       int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
30403       assert( pPager->journalOpen );
30404
30405       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
30406         /* Write the nRec value into the journal file header. If in
30407         ** full-synchronous mode, sync the journal first. This ensures that
30408         ** all data has really hit the disk before nRec is updated to mark
30409         ** it as a candidate for rollback.
30410         **
30411         ** This is not required if the persistent media supports the
30412         ** SAFE_APPEND property. Because in this case it is not possible 
30413         ** for garbage data to be appended to the file, the nRec field
30414         ** is populated with 0xFFFFFFFF when the journal header is written
30415         ** and never needs to be updated.
30416         */
30417         i64 jrnlOff;
30418         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
30419           PAGERTRACE2("SYNC journal of %d\n", PAGERID(pPager));
30420           IOTRACE(("JSYNC %p\n", pPager))
30421           rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags);
30422           if( rc!=0 ) return rc;
30423         }
30424
30425         jrnlOff = pPager->journalHdr + sizeof(aJournalMagic);
30426         IOTRACE(("JHDR %p %lld %d\n", pPager, jrnlOff, 4));
30427         rc = write32bits(pPager->jfd, jrnlOff, pPager->nRec);
30428         if( rc ) return rc;
30429       }
30430       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
30431         PAGERTRACE2("SYNC journal of %d\n", PAGERID(pPager));
30432         IOTRACE(("JSYNC %p\n", pPager))
30433         rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags| 
30434           (pPager->sync_flags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
30435         );
30436         if( rc!=0 ) return rc;
30437       }
30438       pPager->journalStarted = 1;
30439     }
30440     pPager->needSync = 0;
30441
30442     /* Erase the needSync flag from every page.
30443     */
30444     sqlite3PcacheClearFlags(pPager->pPCache, PGHDR_NEED_SYNC);
30445   }
30446
30447 #ifndef NDEBUG
30448   /* If the Pager.needSync flag is clear then the PgHdr.needSync
30449   ** flag must also be clear for all pages.  Verify that this
30450   ** invariant is true.
30451   */
30452   else{
30453     sqlite3PcacheAssertFlags(pPager->pPCache, 0, PGHDR_NEED_SYNC);
30454   }
30455 #endif
30456
30457   return rc;
30458 }
30459
30460 /*
30461 ** Given a list of pages (connected by the PgHdr.pDirty pointer) write
30462 ** every one of those pages out to the database file. No calls are made
30463 ** to the page-cache to mark the pages as clean. It is the responsibility
30464 ** of the caller to use PcacheCleanAll() or PcacheMakeClean() to mark
30465 ** the pages as clean.
30466 */
30467 static int pager_write_pagelist(PgHdr *pList){
30468   Pager *pPager;
30469   int rc;
30470
30471   if( pList==0 ) return SQLITE_OK;
30472   pPager = pList->pPager;
30473
30474   /* At this point there may be either a RESERVED or EXCLUSIVE lock on the
30475   ** database file. If there is already an EXCLUSIVE lock, the following
30476   ** calls to sqlite3OsLock() are no-ops.
30477   **
30478   ** Moving the lock from RESERVED to EXCLUSIVE actually involves going
30479   ** through an intermediate state PENDING.   A PENDING lock prevents new
30480   ** readers from attaching to the database but is unsufficient for us to
30481   ** write.  The idea of a PENDING lock is to prevent new readers from
30482   ** coming in while we wait for existing readers to clear.
30483   **
30484   ** While the pager is in the RESERVED state, the original database file
30485   ** is unchanged and we can rollback without having to playback the
30486   ** journal into the original database file.  Once we transition to
30487   ** EXCLUSIVE, it means the database file has been changed and any rollback
30488   ** will require a journal playback.
30489   */
30490   rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
30491   if( rc!=SQLITE_OK ){
30492     return rc;
30493   }
30494
30495   while( pList ){
30496
30497     /* If the file has not yet been opened, open it now. */
30498     if( !pPager->fd->pMethods ){
30499       assert(pPager->tempFile);
30500       rc = sqlite3PagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
30501       if( rc ) return rc;
30502     }
30503
30504     /* If there are dirty pages in the page cache with page numbers greater
30505     ** than Pager.dbSize, this means sqlite3PagerTruncate() was called to
30506     ** make the file smaller (presumably by auto-vacuum code). Do not write
30507     ** any such pages to the file.
30508     */
30509     if( pList->pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
30510       i64 offset = (pList->pgno-1)*(i64)pPager->pageSize;
30511       char *pData = CODEC2(pPager, pList->pData, pList->pgno, 6);
30512       PAGERTRACE4("STORE %d page %d hash(%08x)\n",
30513                    PAGERID(pPager), pList->pgno, pager_pagehash(pList));
30514       IOTRACE(("PGOUT %p %d\n", pPager, pList->pgno));
30515       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
30516       PAGER_INCR(sqlite3_pager_writedb_count);
30517       PAGER_INCR(pPager->nWrite);
30518       if( pList->pgno==1 ){
30519         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
30520       }
30521     }
30522 #ifndef NDEBUG
30523     else{
30524       PAGERTRACE3("NOSTORE %d page %d\n", PAGERID(pPager), pList->pgno);
30525     }
30526 #endif
30527     if( rc ) return rc;
30528 #ifdef SQLITE_CHECK_PAGES
30529     pList->pageHash = pager_pagehash(pList);
30530 #endif
30531     pList = pList->pDirty;
30532   }
30533
30534   return SQLITE_OK;
30535 }
30536
30537 /*
30538 ** This function is called by the pcache layer when it has reached some
30539 ** soft memory limit. The argument is a pointer to a purgeable Pager 
30540 ** object. This function attempts to make a single dirty page that has no
30541 ** outstanding references (if one exists) clean so that it can be recycled 
30542 ** by the pcache layer.
30543 */
30544 static int pagerStress(void *p, PgHdr *pPg){
30545   Pager *pPager = (Pager *)p;
30546   int rc = SQLITE_OK;
30547
30548   if( pPager->doNotSync ){
30549     return SQLITE_OK;
30550   }
30551
30552   assert( pPg->flags&PGHDR_DIRTY );
30553   if( pPager->errCode==SQLITE_OK ){
30554     if( pPg->flags&PGHDR_NEED_SYNC ){
30555       rc = syncJournal(pPager);
30556       if( rc==SQLITE_OK && pPager->fullSync && 
30557         !(sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
30558       ){
30559         pPager->nRec = 0;
30560         rc = writeJournalHdr(pPager);
30561       }
30562     }
30563     if( rc==SQLITE_OK ){
30564       pPg->pDirty = 0;
30565       rc = pager_write_pagelist(pPg);
30566     }
30567     if( rc!=SQLITE_OK ){
30568       pager_error(pPager, rc);
30569     }
30570   }
30571
30572   if( rc==SQLITE_OK ){
30573     sqlite3PcacheMakeClean(pPg);
30574   }
30575   return rc;
30576 }
30577
30578
30579 /*
30580 ** Return 1 if there is a hot journal on the given pager.
30581 ** A hot journal is one that needs to be played back.
30582 **
30583 ** If the current size of the database file is 0 but a journal file
30584 ** exists, that is probably an old journal left over from a prior
30585 ** database with the same name.  Just delete the journal.
30586 **
30587 ** Return negative if unable to determine the status of the journal.
30588 **
30589 ** This routine does not open the journal file to examine its
30590 ** content.  Hence, the journal might contain the name of a master
30591 ** journal file that has been deleted, and hence not be hot.  Or
30592 ** the header of the journal might be zeroed out.  This routine
30593 ** does not discover these cases of a non-hot journal - if the
30594 ** journal file exists and is not empty this routine assumes it
30595 ** is hot.  The pager_playback() routine will discover that the
30596 ** journal file is not really hot and will no-op.
30597 */
30598 static int hasHotJournal(Pager *pPager, int *pExists){
30599   sqlite3_vfs *pVfs = pPager->pVfs;
30600   int rc = SQLITE_OK;
30601   int exists;
30602   int locked;
30603   assert( pPager!=0 );
30604   assert( pPager->useJournal );
30605   assert( pPager->fd->pMethods );
30606   *pExists = 0;
30607   rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
30608   if( rc==SQLITE_OK && exists ){
30609     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
30610   }
30611   if( rc==SQLITE_OK && exists && !locked ){
30612     int nPage;
30613     rc = sqlite3PagerPagecount(pPager, &nPage);
30614     if( rc==SQLITE_OK ){
30615      if( nPage==0 ){
30616         sqlite3OsDelete(pVfs, pPager->zJournal, 0);
30617       }else{
30618         *pExists = 1;
30619       }
30620     }
30621   }
30622   return rc;
30623 }
30624
30625 /*
30626 ** Read the content of page pPg out of the database file.
30627 */
30628 static int readDbPage(Pager *pPager, PgHdr *pPg, Pgno pgno){
30629   int rc;
30630   i64 offset;
30631   assert( MEMDB==0 );
30632   assert(pPager->fd->pMethods||pPager->tempFile);
30633   if( !pPager->fd->pMethods ){
30634     return SQLITE_IOERR_SHORT_READ;
30635   }
30636   offset = (pgno-1)*(i64)pPager->pageSize;
30637   rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, offset);
30638   PAGER_INCR(sqlite3_pager_readdb_count);
30639   PAGER_INCR(pPager->nRead);
30640   IOTRACE(("PGIN %p %d\n", pPager, pgno));
30641   if( pgno==1 ){
30642     memcpy(&pPager->dbFileVers, &((u8*)pPg->pData)[24],
30643                                               sizeof(pPager->dbFileVers));
30644   }
30645   CODEC1(pPager, pPg->pData, pPg->pgno, 3);
30646   PAGERTRACE4("FETCH %d page %d hash(%08x)\n",
30647                PAGERID(pPager), pPg->pgno, pager_pagehash(pPg));
30648   return rc;
30649 }
30650
30651
30652 /*
30653 ** This function is called to obtain the shared lock required before
30654 ** data may be read from the pager cache. If the shared lock has already
30655 ** been obtained, this function is a no-op.
30656 **
30657 ** Immediately after obtaining the shared lock (if required), this function
30658 ** checks for a hot-journal file. If one is found, an emergency rollback
30659 ** is performed immediately.
30660 */
30661 static int pagerSharedLock(Pager *pPager){
30662   int rc = SQLITE_OK;
30663   int isErrorReset = 0;
30664
30665   /* If this database is opened for exclusive access, has no outstanding 
30666   ** page references and is in an error-state, now is the chance to clear
30667   ** the error. Discard the contents of the pager-cache and treat any
30668   ** open journal file as a hot-journal.
30669   */
30670   if( !MEMDB && pPager->exclusiveMode 
30671    && sqlite3PcacheRefCount(pPager->pPCache)==0 && pPager->errCode 
30672   ){
30673     if( pPager->journalOpen ){
30674       isErrorReset = 1;
30675     }
30676     pPager->errCode = SQLITE_OK;
30677     pager_reset(pPager);
30678   }
30679
30680   /* If the pager is still in an error state, do not proceed. The error 
30681   ** state will be cleared at some point in the future when all page 
30682   ** references are dropped and the cache can be discarded.
30683   */
30684   if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
30685     return pPager->errCode;
30686   }
30687
30688   if( pPager->state==PAGER_UNLOCK || isErrorReset ){
30689     sqlite3_vfs *pVfs = pPager->pVfs;
30690     if( !MEMDB ){
30691       int isHotJournal;
30692       assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
30693       if( !pPager->noReadlock ){
30694         rc = pager_wait_on_lock(pPager, SHARED_LOCK);
30695         if( rc!=SQLITE_OK ){
30696           assert( pPager->state==PAGER_UNLOCK );
30697           return pager_error(pPager, rc);
30698         }
30699         assert( pPager->state>=SHARED_LOCK );
30700       }
30701   
30702       /* If a journal file exists, and there is no RESERVED lock on the
30703       ** database file, then it either needs to be played back or deleted.
30704       */
30705       if( !isErrorReset ){
30706         rc = hasHotJournal(pPager, &isHotJournal);
30707         if( rc!=SQLITE_OK ){
30708           goto failed;
30709         }
30710       }
30711       if( isErrorReset || isHotJournal ){
30712         /* Get an EXCLUSIVE lock on the database file. At this point it is
30713         ** important that a RESERVED lock is not obtained on the way to the
30714         ** EXCLUSIVE lock. If it were, another process might open the
30715         ** database file, detect the RESERVED lock, and conclude that the
30716         ** database is safe to read while this process is still rolling it 
30717         ** back.
30718         ** 
30719         ** Because the intermediate RESERVED lock is not requested, the
30720         ** second process will get to this point in the code and fail to
30721         ** obtain its own EXCLUSIVE lock on the database file.
30722         */
30723         if( pPager->state<EXCLUSIVE_LOCK ){
30724           rc = sqlite3OsLock(pPager->fd, EXCLUSIVE_LOCK);
30725           if( rc!=SQLITE_OK ){
30726             rc = pager_error(pPager, rc);
30727             goto failed;
30728           }
30729           pPager->state = PAGER_EXCLUSIVE;
30730         }
30731  
30732         /* Open the journal for read/write access. This is because in 
30733         ** exclusive-access mode the file descriptor will be kept open and
30734         ** possibly used for a transaction later on. On some systems, the
30735         ** OsTruncate() call used in exclusive-access mode also requires
30736         ** a read/write file handle.
30737         */
30738         if( !isErrorReset && pPager->journalOpen==0 ){
30739           int res;
30740           rc = sqlite3OsAccess(pVfs,pPager->zJournal,SQLITE_ACCESS_EXISTS,&res);
30741           if( rc==SQLITE_OK ){
30742             if( res ){
30743               int fout = 0;
30744               int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
30745               assert( !pPager->tempFile );
30746               rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
30747               assert( rc!=SQLITE_OK || pPager->jfd->pMethods );
30748               if( fout&SQLITE_OPEN_READONLY ){
30749                 rc = SQLITE_BUSY;
30750                 sqlite3OsClose(pPager->jfd);
30751               }
30752             }else{
30753               /* If the journal does not exist, that means some other process
30754               ** has already rolled it back */
30755               rc = SQLITE_BUSY;
30756             }
30757           }
30758         }
30759         if( rc!=SQLITE_OK ){
30760           if( rc!=SQLITE_NOMEM && rc!=SQLITE_IOERR_UNLOCK 
30761            && rc!=SQLITE_IOERR_NOMEM 
30762           ){
30763             rc = SQLITE_BUSY;
30764           }
30765           goto failed;
30766         }
30767         pPager->journalOpen = 1;
30768         pPager->journalStarted = 0;
30769         pPager->journalOff = 0;
30770         pPager->setMaster = 0;
30771         pPager->journalHdr = 0;
30772  
30773         /* Playback and delete the journal.  Drop the database write
30774         ** lock and reacquire the read lock.
30775         */
30776         rc = pager_playback(pPager, 1);
30777         if( rc!=SQLITE_OK ){
30778           rc = pager_error(pPager, rc);
30779           goto failed;
30780         }
30781         assert(pPager->state==PAGER_SHARED || 
30782             (pPager->exclusiveMode && pPager->state>PAGER_SHARED)
30783         );
30784       }
30785
30786       if( sqlite3PcachePagecount(pPager->pPCache)>0 ){
30787         /* The shared-lock has just been acquired on the database file
30788         ** and there are already pages in the cache (from a previous
30789         ** read or write transaction).  Check to see if the database
30790         ** has been modified.  If the database has changed, flush the
30791         ** cache.
30792         **
30793         ** Database changes is detected by looking at 15 bytes beginning
30794         ** at offset 24 into the file.  The first 4 of these 16 bytes are
30795         ** a 32-bit counter that is incremented with each change.  The
30796         ** other bytes change randomly with each file change when
30797         ** a codec is in use.
30798         ** 
30799         ** There is a vanishingly small chance that a change will not be 
30800         ** detected.  The chance of an undetected change is so small that
30801         ** it can be neglected.
30802         */
30803         char dbFileVers[sizeof(pPager->dbFileVers)];
30804         sqlite3PagerPagecount(pPager, 0);
30805
30806         if( pPager->errCode ){
30807           rc = pPager->errCode;
30808           goto failed;
30809         }
30810
30811         if( pPager->dbSize>0 ){
30812           IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
30813           rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
30814           if( rc!=SQLITE_OK ){
30815             goto failed;
30816           }
30817         }else{
30818           memset(dbFileVers, 0, sizeof(dbFileVers));
30819         }
30820
30821         if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
30822           pager_reset(pPager);
30823         }
30824       }
30825     }
30826     assert( pPager->exclusiveMode || pPager->state<=PAGER_SHARED );
30827     if( pPager->state==PAGER_UNLOCK ){
30828       pPager->state = PAGER_SHARED;
30829     }
30830   }
30831
30832  failed:
30833   if( rc!=SQLITE_OK ){
30834     /* pager_unlock() is a no-op for exclusive mode and in-memory databases. */
30835     pager_unlock(pPager);
30836   }
30837   return rc;
30838 }
30839
30840 /*
30841 ** Make sure we have the content for a page.  If the page was
30842 ** previously acquired with noContent==1, then the content was
30843 ** just initialized to zeros instead of being read from disk.
30844 ** But now we need the real data off of disk.  So make sure we
30845 ** have it.  Read it in if we do not have it already.
30846 */
30847 static int pager_get_content(PgHdr *pPg){
30848   if( pPg->flags&PGHDR_NEED_READ ){
30849     int rc = readDbPage(pPg->pPager, pPg, pPg->pgno);
30850     if( rc==SQLITE_OK ){
30851       pPg->flags &= ~PGHDR_NEED_READ;
30852     }else{
30853       return rc;
30854     }
30855   }
30856   return SQLITE_OK;
30857 }
30858
30859 /*
30860 ** If the reference count has reached zero, and the pager is not in the
30861 ** middle of a write transaction or opened in exclusive mode, unlock it.
30862 */ 
30863 static void pagerUnlockIfUnused(Pager *pPager){
30864   if( (sqlite3PcacheRefCount(pPager->pPCache)==0)
30865     && (!pPager->exclusiveMode || pPager->journalOff>0) 
30866   ){
30867     pagerUnlockAndRollback(pPager);
30868   }
30869 }
30870
30871 /*
30872 ** Drop a page from the cache using sqlite3PcacheDrop().
30873 **
30874 ** If this means there are now no pages with references to them, a rollback
30875 ** occurs and the lock on the database is removed.
30876 */
30877 static void pagerDropPage(DbPage *pPg){
30878   Pager *pPager = pPg->pPager;
30879   sqlite3PcacheDrop(pPg);
30880   pagerUnlockIfUnused(pPager);
30881 }
30882
30883 /*
30884 ** Acquire a page.
30885 **
30886 ** A read lock on the disk file is obtained when the first page is acquired. 
30887 ** This read lock is dropped when the last page is released.
30888 **
30889 ** This routine works for any page number greater than 0.  If the database
30890 ** file is smaller than the requested page, then no actual disk
30891 ** read occurs and the memory image of the page is initialized to
30892 ** all zeros.  The extra data appended to a page is always initialized
30893 ** to zeros the first time a page is loaded into memory.
30894 **
30895 ** The acquisition might fail for several reasons.  In all cases,
30896 ** an appropriate error code is returned and *ppPage is set to NULL.
30897 **
30898 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
30899 ** to find a page in the in-memory cache first.  If the page is not already
30900 ** in memory, this routine goes to disk to read it in whereas Lookup()
30901 ** just returns 0.  This routine acquires a read-lock the first time it
30902 ** has to go to disk, and could also playback an old journal if necessary.
30903 ** Since Lookup() never goes to disk, it never has to deal with locks
30904 ** or journal files.
30905 **
30906 ** If noContent is false, the page contents are actually read from disk.
30907 ** If noContent is true, it means that we do not care about the contents
30908 ** of the page at this time, so do not do a disk read.  Just fill in the
30909 ** page content with zeros.  But mark the fact that we have not read the
30910 ** content by setting the PgHdr.needRead flag.  Later on, if 
30911 ** sqlite3PagerWrite() is called on this page or if this routine is
30912 ** called again with noContent==0, that means that the content is needed
30913 ** and the disk read should occur at that point.
30914 */
30915 SQLITE_PRIVATE int sqlite3PagerAcquire(
30916   Pager *pPager,      /* The pager open on the database file */
30917   Pgno pgno,          /* Page number to fetch */
30918   DbPage **ppPage,    /* Write a pointer to the page here */
30919   int noContent       /* Do not bother reading content from disk if true */
30920 ){
30921   PgHdr *pPg = 0;
30922   int rc;
30923
30924   assert( pPager->state==PAGER_UNLOCK 
30925        || sqlite3PcacheRefCount(pPager->pPCache)>0 
30926        || pgno==1 
30927   );
30928
30929   /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
30930   ** number greater than this, or zero, is requested.
30931   */
30932   if( pgno>PAGER_MAX_PGNO || pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
30933     return SQLITE_CORRUPT_BKPT;
30934   }
30935
30936   /* Make sure we have not hit any critical errors.
30937   */ 
30938   assert( pPager!=0 );
30939   *ppPage = 0;
30940
30941   /* If this is the first page accessed, then get a SHARED lock
30942   ** on the database file. pagerSharedLock() is a no-op if 
30943   ** a database lock is already held.
30944   */
30945   rc = pagerSharedLock(pPager);
30946   if( rc!=SQLITE_OK ){
30947     return rc;
30948   }
30949   assert( pPager->state!=PAGER_UNLOCK );
30950
30951   rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, &pPg);
30952   if( rc!=SQLITE_OK ){
30953     return rc;
30954   }
30955   if( pPg->pPager==0 ){
30956     /* The pager cache has created a new page. Its content needs to 
30957     ** be initialized.
30958     */
30959     int nMax;
30960     PAGER_INCR(pPager->nMiss);
30961     pPg->pPager = pPager;
30962     if( sqlite3BitvecTest(pPager->pInJournal, pgno) ){
30963       assert( !MEMDB );
30964       pPg->flags |= PGHDR_IN_JOURNAL;
30965     }
30966     memset(pPg->pExtra, 0, pPager->nExtra);
30967
30968     rc = sqlite3PagerPagecount(pPager, &nMax);
30969     if( rc!=SQLITE_OK ){
30970       sqlite3PagerUnref(pPg);
30971       return rc;
30972     }
30973
30974     if( nMax<(int)pgno || MEMDB || noContent ){
30975       if( pgno>pPager->mxPgno ){
30976         sqlite3PagerUnref(pPg);
30977         return SQLITE_FULL;
30978       }
30979       memset(pPg->pData, 0, pPager->pageSize);
30980       if( noContent ){
30981         pPg->flags |= PGHDR_NEED_READ;
30982       }
30983       IOTRACE(("ZERO %p %d\n", pPager, pgno));
30984     }else{
30985       rc = readDbPage(pPager, pPg, pgno);
30986       if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
30987         /* sqlite3PagerUnref(pPg); */
30988         pagerDropPage(pPg);
30989         return rc;
30990       }
30991     }
30992 #ifdef SQLITE_CHECK_PAGES
30993     pPg->pageHash = pager_pagehash(pPg);
30994 #endif
30995   }else{
30996     /* The requested page is in the page cache. */
30997     assert(sqlite3PcacheRefCount(pPager->pPCache)>0 || pgno==1);
30998     PAGER_INCR(pPager->nHit);
30999     if( !noContent ){
31000       rc = pager_get_content(pPg);
31001       if( rc ){
31002         sqlite3PagerUnref(pPg);
31003         return rc;
31004       }
31005     }
31006   }
31007
31008   *ppPage = pPg;
31009   return SQLITE_OK;
31010 }
31011
31012 /*
31013 ** Acquire a page if it is already in the in-memory cache.  Do
31014 ** not read the page from disk.  Return a pointer to the page,
31015 ** or 0 if the page is not in cache.
31016 **
31017 ** See also sqlite3PagerGet().  The difference between this routine
31018 ** and sqlite3PagerGet() is that _get() will go to the disk and read
31019 ** in the page if the page is not already in cache.  This routine
31020 ** returns NULL if the page is not in cache or if a disk I/O error 
31021 ** has ever happened.
31022 */
31023 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
31024   PgHdr *pPg = 0;
31025   assert( pPager!=0 );
31026   assert( pgno!=0 );
31027
31028   if( (pPager->state!=PAGER_UNLOCK)
31029    && (pPager->errCode==SQLITE_OK || pPager->errCode==SQLITE_FULL)
31030   ){
31031     sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
31032   }
31033
31034   return pPg;
31035 }
31036
31037 /*
31038 ** Release a page.
31039 **
31040 ** If the number of references to the page drop to zero, then the
31041 ** page is added to the LRU list.  When all references to all pages
31042 ** are released, a rollback occurs and the lock on the database is
31043 ** removed.
31044 */
31045 SQLITE_PRIVATE int sqlite3PagerUnref(DbPage *pPg){
31046   if( pPg ){
31047     Pager *pPager = pPg->pPager;
31048     sqlite3PcacheRelease(pPg);
31049     pagerUnlockIfUnused(pPager);
31050   }
31051   return SQLITE_OK;
31052 }
31053
31054 /*
31055 ** Create a journal file for pPager.  There should already be a RESERVED
31056 ** or EXCLUSIVE lock on the database file when this routine is called.
31057 **
31058 ** Return SQLITE_OK if everything.  Return an error code and release the
31059 ** write lock if anything goes wrong.
31060 */
31061 static int pager_open_journal(Pager *pPager){
31062   sqlite3_vfs *pVfs = pPager->pVfs;
31063   int flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_CREATE);
31064
31065   int rc;
31066   assert( !MEMDB );
31067   assert( pPager->state>=PAGER_RESERVED );
31068   assert( pPager->useJournal );
31069   assert( pPager->pInJournal==0 );
31070   sqlite3PagerPagecount(pPager, 0);
31071   pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
31072   if( pPager->pInJournal==0 ){
31073     rc = SQLITE_NOMEM;
31074     goto failed_to_open_journal;
31075   }
31076
31077   if( pPager->journalOpen==0 ){
31078     if( pPager->tempFile ){
31079       flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
31080     }else{
31081       flags |= (SQLITE_OPEN_MAIN_JOURNAL);
31082     }
31083 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
31084     rc = sqlite3JournalOpen(
31085         pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
31086     );
31087 #else
31088     rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
31089 #endif
31090     assert( rc!=SQLITE_OK || pPager->jfd->pMethods );
31091     pPager->journalOff = 0;
31092     pPager->setMaster = 0;
31093     pPager->journalHdr = 0;
31094     if( rc!=SQLITE_OK ){
31095       if( rc==SQLITE_NOMEM ){
31096         sqlite3OsDelete(pVfs, pPager->zJournal, 0);
31097       }
31098       goto failed_to_open_journal;
31099     }
31100   }
31101   pPager->journalOpen = 1;
31102   pPager->journalStarted = 0;
31103   pPager->needSync = 0;
31104   pPager->nRec = 0;
31105   if( pPager->errCode ){
31106     rc = pPager->errCode;
31107     goto failed_to_open_journal;
31108   }
31109   pPager->origDbSize = pPager->dbSize;
31110
31111   rc = writeJournalHdr(pPager);
31112
31113   if( pPager->stmtAutoopen && rc==SQLITE_OK ){
31114     rc = sqlite3PagerStmtBegin(pPager);
31115   }
31116   if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && rc!=SQLITE_IOERR_NOMEM ){
31117     rc = pager_end_transaction(pPager, 0);
31118     if( rc==SQLITE_OK ){
31119       rc = SQLITE_FULL;
31120     }
31121   }
31122   return rc;
31123
31124 failed_to_open_journal:
31125   sqlite3BitvecDestroy(pPager->pInJournal);
31126   pPager->pInJournal = 0;
31127   return rc;
31128 }
31129
31130 /*
31131 ** Acquire a write-lock on the database.  The lock is removed when
31132 ** the any of the following happen:
31133 **
31134 **   *  sqlite3PagerCommitPhaseTwo() is called.
31135 **   *  sqlite3PagerRollback() is called.
31136 **   *  sqlite3PagerClose() is called.
31137 **   *  sqlite3PagerUnref() is called to on every outstanding page.
31138 **
31139 ** The first parameter to this routine is a pointer to any open page of the
31140 ** database file.  Nothing changes about the page - it is used merely to
31141 ** acquire a pointer to the Pager structure and as proof that there is
31142 ** already a read-lock on the database.
31143 **
31144 ** The second parameter indicates how much space in bytes to reserve for a
31145 ** master journal file-name at the start of the journal when it is created.
31146 **
31147 ** A journal file is opened if this is not a temporary file.  For temporary
31148 ** files, the opening of the journal file is deferred until there is an
31149 ** actual need to write to the journal.
31150 **
31151 ** If the database is already reserved for writing, this routine is a no-op.
31152 **
31153 ** If exFlag is true, go ahead and get an EXCLUSIVE lock on the file
31154 ** immediately instead of waiting until we try to flush the cache.  The
31155 ** exFlag is ignored if a transaction is already active.
31156 */
31157 SQLITE_PRIVATE int sqlite3PagerBegin(DbPage *pPg, int exFlag){
31158   Pager *pPager = pPg->pPager;
31159   int rc = SQLITE_OK;
31160   assert( pPg->nRef>0 );
31161   assert( pPager->state!=PAGER_UNLOCK );
31162   if( pPager->state==PAGER_SHARED ){
31163     assert( pPager->pInJournal==0 );
31164     sqlite3PcacheAssertFlags(pPager->pPCache, 0, PGHDR_IN_JOURNAL);
31165     if( MEMDB ){
31166       pPager->state = PAGER_EXCLUSIVE;
31167       pPager->origDbSize = pPager->dbSize;
31168     }else{
31169       rc = sqlite3OsLock(pPager->fd, RESERVED_LOCK);
31170       if( rc==SQLITE_OK ){
31171         pPager->state = PAGER_RESERVED;
31172         if( exFlag ){
31173           rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
31174         }
31175       }
31176       if( rc!=SQLITE_OK ){
31177         return rc;
31178       }
31179       pPager->dirtyCache = 0;
31180       PAGERTRACE2("TRANSACTION %d\n", PAGERID(pPager));
31181       if( pPager->useJournal && !pPager->tempFile
31182              && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
31183         rc = pager_open_journal(pPager);
31184       }
31185     }
31186   }else if( pPager->journalOpen && pPager->journalOff==0 ){
31187     /* This happens when the pager was in exclusive-access mode the last
31188     ** time a (read or write) transaction was successfully concluded
31189     ** by this connection. Instead of deleting the journal file it was 
31190     ** kept open and either was truncated to 0 bytes or its header was
31191     ** overwritten with zeros.
31192     */
31193     assert( pPager->nRec==0 );
31194     assert( pPager->origDbSize==0 );
31195     assert( pPager->pInJournal==0 );
31196     sqlite3PagerPagecount(pPager, 0);
31197     pPager->pInJournal = sqlite3BitvecCreate( pPager->dbSize );
31198     if( !pPager->pInJournal ){
31199       rc = SQLITE_NOMEM;
31200     }else{
31201       pPager->origDbSize = pPager->dbSize;
31202       rc = writeJournalHdr(pPager);
31203     }
31204   }
31205   assert( !pPager->journalOpen || pPager->journalOff>0 || rc!=SQLITE_OK );
31206   return rc;
31207 }
31208
31209 /*
31210 ** Make a page dirty.  Set its dirty flag and add it to the dirty
31211 ** page list.
31212 */
31213 static void makeDirty(PgHdr *pPg){
31214   sqlite3PcacheMakeDirty(pPg);
31215 }
31216
31217 /*
31218 ** Make a page clean.  Clear its dirty bit and remove it from the
31219 ** dirty page list.
31220 */
31221 static void makeClean(PgHdr *pPg){
31222   sqlite3PcacheMakeClean(pPg);
31223 }
31224
31225
31226 /*
31227 ** Mark a data page as writeable.  The page is written into the journal 
31228 ** if it is not there already.  This routine must be called before making
31229 ** changes to a page.
31230 **
31231 ** The first time this routine is called, the pager creates a new
31232 ** journal and acquires a RESERVED lock on the database.  If the RESERVED
31233 ** lock could not be acquired, this routine returns SQLITE_BUSY.  The
31234 ** calling routine must check for that return value and be careful not to
31235 ** change any page data until this routine returns SQLITE_OK.
31236 **
31237 ** If the journal file could not be written because the disk is full,
31238 ** then this routine returns SQLITE_FULL and does an immediate rollback.
31239 ** All subsequent write attempts also return SQLITE_FULL until there
31240 ** is a call to sqlite3PagerCommit() or sqlite3PagerRollback() to
31241 ** reset.
31242 */
31243 static int pager_write(PgHdr *pPg){
31244   void *pData = pPg->pData;
31245   Pager *pPager = pPg->pPager;
31246   int rc = SQLITE_OK;
31247
31248   /* Check for errors
31249   */
31250   if( pPager->errCode ){ 
31251     return pPager->errCode;
31252   }
31253   if( pPager->readOnly ){
31254     return SQLITE_PERM;
31255   }
31256
31257   assert( !pPager->setMaster );
31258
31259   CHECK_PAGE(pPg);
31260
31261   /* If this page was previously acquired with noContent==1, that means
31262   ** we didn't really read in the content of the page.  This can happen
31263   ** (for example) when the page is being moved to the freelist.  But
31264   ** now we are (perhaps) moving the page off of the freelist for
31265   ** reuse and we need to know its original content so that content
31266   ** can be stored in the rollback journal.  So do the read at this
31267   ** time.
31268   */
31269   rc = pager_get_content(pPg);
31270   if( rc ){
31271     return rc;
31272   }
31273
31274   /* Mark the page as dirty.  If the page has already been written
31275   ** to the journal then we can return right away.
31276   */
31277   makeDirty(pPg);
31278   if( (pPg->flags&PGHDR_IN_JOURNAL)
31279    && (pageInStatement(pPg) || pPager->stmtInUse==0) 
31280   ){
31281     pPager->dirtyCache = 1;
31282     pPager->dbModified = 1;
31283   }else{
31284
31285     /* If we get this far, it means that the page needs to be
31286     ** written to the transaction journal or the ckeckpoint journal
31287     ** or both.
31288     **
31289     ** First check to see that the transaction journal exists and
31290     ** create it if it does not.
31291     */
31292     assert( pPager->state!=PAGER_UNLOCK );
31293     rc = sqlite3PagerBegin(pPg, 0);
31294     if( rc!=SQLITE_OK ){
31295       return rc;
31296     }
31297     assert( pPager->state>=PAGER_RESERVED );
31298     if( !pPager->journalOpen && pPager->useJournal
31299           && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
31300       rc = pager_open_journal(pPager);
31301       if( rc!=SQLITE_OK ) return rc;
31302     }
31303     pPager->dirtyCache = 1;
31304     pPager->dbModified = 1;
31305   
31306     /* The transaction journal now exists and we have a RESERVED or an
31307     ** EXCLUSIVE lock on the main database file.  Write the current page to
31308     ** the transaction journal if it is not there already.
31309     */
31310     if( !(pPg->flags&PGHDR_IN_JOURNAL) && (pPager->journalOpen || MEMDB) ){
31311       if( (int)pPg->pgno <= pPager->origDbSize ){
31312         if( MEMDB ){
31313           PAGERTRACE3("JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno);
31314           rc = sqlite3PcachePreserve(pPg, 0);
31315           if( rc!=SQLITE_OK ){
31316             return rc;
31317           }
31318         }else{
31319           u32 cksum;
31320           char *pData2;
31321
31322           /* We should never write to the journal file the page that
31323           ** contains the database locks.  The following assert verifies
31324           ** that we do not. */
31325           assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
31326           pData2 = CODEC2(pPager, pData, pPg->pgno, 7);
31327           cksum = pager_cksum(pPager, (u8*)pData2);
31328           rc = write32bits(pPager->jfd, pPager->journalOff, pPg->pgno);
31329           if( rc==SQLITE_OK ){
31330             rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize,
31331                                 pPager->journalOff + 4);
31332             pPager->journalOff += pPager->pageSize+4;
31333           }
31334           if( rc==SQLITE_OK ){
31335             rc = write32bits(pPager->jfd, pPager->journalOff, cksum);
31336             pPager->journalOff += 4;
31337           }
31338           IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
31339                    pPager->journalOff, pPager->pageSize));
31340           PAGER_INCR(sqlite3_pager_writej_count);
31341           PAGERTRACE5("JOURNAL %d page %d needSync=%d hash(%08x)\n",
31342                PAGERID(pPager), pPg->pgno, 
31343                ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg));
31344
31345           /* An error has occured writing to the journal file. The 
31346           ** transaction will be rolled back by the layer above.
31347           */
31348           if( rc!=SQLITE_OK ){
31349             return rc;
31350           }
31351
31352           pPager->nRec++;
31353           assert( pPager->pInJournal!=0 );
31354           sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
31355           if( !pPager->noSync ){
31356             pPg->flags |= PGHDR_NEED_SYNC;
31357           }
31358           if( pPager->stmtInUse ){
31359             sqlite3BitvecSet(pPager->pInStmt, pPg->pgno);
31360           }
31361         }
31362       }else{
31363         if( !pPager->journalStarted && !pPager->noSync ){
31364           pPg->flags |= PGHDR_NEED_SYNC;
31365         }
31366         PAGERTRACE4("APPEND %d page %d needSync=%d\n",
31367                 PAGERID(pPager), pPg->pgno,
31368                ((pPg->flags&PGHDR_NEED_SYNC)?1:0));
31369       }
31370       if( pPg->flags&PGHDR_NEED_SYNC ){
31371         pPager->needSync = 1;
31372       }
31373       pPg->flags |= PGHDR_IN_JOURNAL;
31374     }
31375   
31376     /* If the statement journal is open and the page is not in it,
31377     ** then write the current page to the statement journal.  Note that
31378     ** the statement journal format differs from the standard journal format
31379     ** in that it omits the checksums and the header.
31380     */
31381     if( pPager->stmtInUse 
31382      && !pageInStatement(pPg) 
31383      && (int)pPg->pgno<=pPager->stmtSize 
31384     ){
31385       assert( (pPg->flags&PGHDR_IN_JOURNAL) 
31386                  || (int)pPg->pgno>pPager->origDbSize );
31387       if( MEMDB ){
31388         rc = sqlite3PcachePreserve(pPg, 1);
31389         if( rc!=SQLITE_OK ){
31390           return rc;
31391         }
31392         PAGERTRACE3("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno);
31393       }else{
31394         i64 offset = pPager->stmtNRec*(4+pPager->pageSize);
31395         char *pData2 = CODEC2(pPager, pData, pPg->pgno, 7);
31396         rc = write32bits(pPager->stfd, offset, pPg->pgno);
31397         if( rc==SQLITE_OK ){
31398           rc = sqlite3OsWrite(pPager->stfd, pData2, pPager->pageSize, offset+4);
31399         }
31400         PAGERTRACE3("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno);
31401         if( rc!=SQLITE_OK ){
31402           return rc;
31403         }
31404         pPager->stmtNRec++;
31405         assert( pPager->pInStmt!=0 );
31406         sqlite3BitvecSet(pPager->pInStmt, pPg->pgno);
31407       }
31408     }
31409   }
31410
31411   /* Update the database size and return.
31412   */
31413   assert( pPager->state>=PAGER_SHARED );
31414   if( pPager->dbSize<(int)pPg->pgno ){
31415     pPager->dbSize = pPg->pgno;
31416     if( !MEMDB && pPager->dbSize==PENDING_BYTE/pPager->pageSize ){
31417       pPager->dbSize++;
31418     }
31419   }
31420   return rc;
31421 }
31422
31423 /*
31424 ** This function is used to mark a data-page as writable. It uses 
31425 ** pager_write() to open a journal file (if it is not already open)
31426 ** and write the page *pData to the journal.
31427 **
31428 ** The difference between this function and pager_write() is that this
31429 ** function also deals with the special case where 2 or more pages
31430 ** fit on a single disk sector. In this case all co-resident pages
31431 ** must have been written to the journal file before returning.
31432 */
31433 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
31434   int rc = SQLITE_OK;
31435
31436   PgHdr *pPg = pDbPage;
31437   Pager *pPager = pPg->pPager;
31438   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
31439
31440   if( !MEMDB && nPagePerSector>1 ){
31441     Pgno nPageCount;          /* Total number of pages in database file */
31442     Pgno pg1;                 /* First page of the sector pPg is located on. */
31443     int nPage;                /* Number of pages starting at pg1 to journal */
31444     int ii;
31445     int needSync = 0;
31446
31447     /* Set the doNotSync flag to 1. This is because we cannot allow a journal
31448     ** header to be written between the pages journaled by this function.
31449     */
31450     assert( pPager->doNotSync==0 );
31451     pPager->doNotSync = 1;
31452
31453     /* This trick assumes that both the page-size and sector-size are
31454     ** an integer power of 2. It sets variable pg1 to the identifier
31455     ** of the first page of the sector pPg is located on.
31456     */
31457     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
31458
31459     sqlite3PagerPagecount(pPager, (int *)&nPageCount);
31460     if( pPg->pgno>nPageCount ){
31461       nPage = (pPg->pgno - pg1)+1;
31462     }else if( (pg1+nPagePerSector-1)>nPageCount ){
31463       nPage = nPageCount+1-pg1;
31464     }else{
31465       nPage = nPagePerSector;
31466     }
31467     assert(nPage>0);
31468     assert(pg1<=pPg->pgno);
31469     assert((pg1+nPage)>pPg->pgno);
31470
31471     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
31472       Pgno pg = pg1+ii;
31473       PgHdr *pPage;
31474       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
31475         if( pg!=PAGER_MJ_PGNO(pPager) ){
31476           rc = sqlite3PagerGet(pPager, pg, &pPage);
31477           if( rc==SQLITE_OK ){
31478             rc = pager_write(pPage);
31479             if( pPage->flags&PGHDR_NEED_SYNC ){
31480               needSync = 1;
31481             }
31482             sqlite3PagerUnref(pPage);
31483           }
31484         }
31485       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
31486         if( pPage->flags&PGHDR_NEED_SYNC ){
31487           needSync = 1;
31488         }
31489         sqlite3PagerUnref(pPage);
31490       }
31491     }
31492
31493     /* If the PgHdr.needSync flag is set for any of the nPage pages 
31494     ** starting at pg1, then it needs to be set for all of them. Because
31495     ** writing to any of these nPage pages may damage the others, the
31496     ** journal file must contain sync()ed copies of all of them
31497     ** before any of them can be written out to the database file.
31498     */
31499     if( needSync ){
31500       assert( !MEMDB && pPager->noSync==0 );
31501       for(ii=0; ii<nPage && needSync; ii++){
31502         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
31503         if( pPage ) pPage->flags |= PGHDR_NEED_SYNC;
31504         sqlite3PagerUnref(pPage);
31505       }
31506       assert(pPager->needSync);
31507     }
31508
31509     assert( pPager->doNotSync==1 );
31510     pPager->doNotSync = 0;
31511   }else{
31512     rc = pager_write(pDbPage);
31513   }
31514   return rc;
31515 }
31516
31517 /*
31518 ** Return TRUE if the page given in the argument was previously passed
31519 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
31520 ** to change the content of the page.
31521 */
31522 #ifndef NDEBUG
31523 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
31524   return pPg->flags&PGHDR_DIRTY;
31525 }
31526 #endif
31527
31528 /*
31529 ** A call to this routine tells the pager that it is not necessary to
31530 ** write the information on page pPg back to the disk, even though
31531 ** that page might be marked as dirty.
31532 **
31533 ** The overlying software layer calls this routine when all of the data
31534 ** on the given page is unused.  The pager marks the page as clean so
31535 ** that it does not get written to disk.
31536 **
31537 ** Tests show that this optimization, together with the
31538 ** sqlite3PagerDontRollback() below, more than double the speed
31539 ** of large INSERT operations and quadruple the speed of large DELETEs.
31540 **
31541 ** When this routine is called, set the alwaysRollback flag to true.
31542 ** Subsequent calls to sqlite3PagerDontRollback() for the same page
31543 ** will thereafter be ignored.  This is necessary to avoid a problem
31544 ** where a page with data is added to the freelist during one part of
31545 ** a transaction then removed from the freelist during a later part
31546 ** of the same transaction and reused for some other purpose.  When it
31547 ** is first added to the freelist, this routine is called.  When reused,
31548 ** the sqlite3PagerDontRollback() routine is called.  But because the
31549 ** page contains critical data, we still need to be sure it gets
31550 ** rolled back in spite of the sqlite3PagerDontRollback() call.
31551 */
31552 SQLITE_PRIVATE int sqlite3PagerDontWrite(DbPage *pDbPage){
31553   PgHdr *pPg = pDbPage;
31554   Pager *pPager = pPg->pPager;
31555   int rc;
31556
31557   if( MEMDB || pPg->pgno>pPager->origDbSize ){
31558     return SQLITE_OK;
31559   }
31560   if( pPager->pAlwaysRollback==0 ){
31561     assert( pPager->pInJournal );
31562     pPager->pAlwaysRollback = sqlite3BitvecCreate(pPager->origDbSize);
31563     if( !pPager->pAlwaysRollback ){
31564       return SQLITE_NOMEM;
31565     }
31566   }
31567   rc = sqlite3BitvecSet(pPager->pAlwaysRollback, pPg->pgno);
31568
31569   if( rc==SQLITE_OK && (pPg->flags&PGHDR_DIRTY) && !pPager->stmtInUse ){
31570     assert( pPager->state>=PAGER_SHARED );
31571     if( pPager->dbSize==(int)pPg->pgno && pPager->origDbSize<pPager->dbSize ){
31572       /* If this pages is the last page in the file and the file has grown
31573       ** during the current transaction, then do NOT mark the page as clean.
31574       ** When the database file grows, we must make sure that the last page
31575       ** gets written at least once so that the disk file will be the correct
31576       ** size. If you do not write this page and the size of the file
31577       ** on the disk ends up being too small, that can lead to database
31578       ** corruption during the next transaction.
31579       */
31580     }else{
31581       PAGERTRACE3("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager));
31582       IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
31583       pPg->flags |= PGHDR_DONT_WRITE;
31584 #ifdef SQLITE_CHECK_PAGES
31585       pPg->pageHash = pager_pagehash(pPg);
31586 #endif
31587     }
31588   }
31589   return rc;
31590 }
31591
31592 /*
31593 ** A call to this routine tells the pager that if a rollback occurs,
31594 ** it is not necessary to restore the data on the given page.  This
31595 ** means that the pager does not have to record the given page in the
31596 ** rollback journal.
31597 **
31598 ** If we have not yet actually read the content of this page (if
31599 ** the PgHdr.needRead flag is set) then this routine acts as a promise
31600 ** that we will never need to read the page content in the future.
31601 ** so the needRead flag can be cleared at this point.
31602 */
31603 SQLITE_PRIVATE void sqlite3PagerDontRollback(DbPage *pPg){
31604   Pager *pPager = pPg->pPager;
31605
31606   assert( pPager->state>=PAGER_RESERVED );
31607
31608   /* If the journal file is not open, or DontWrite() has been called on
31609   ** this page (DontWrite() sets the alwaysRollback flag), then this
31610   ** function is a no-op.
31611   */
31612   if( pPager->journalOpen==0 
31613    || sqlite3BitvecTest(pPager->pAlwaysRollback, pPg->pgno)
31614    || pPg->pgno>pPager->origDbSize
31615   ){
31616     return;
31617   }
31618   assert( !MEMDB );    /* For a memdb, pPager->journalOpen is always 0 */
31619
31620 #ifdef SQLITE_SECURE_DELETE
31621   if( (pPg->flags & PGHDR_IN_JOURNAL)!=0 || (int)pPg->pgno>pPager->origDbSize ){
31622     return;
31623   }
31624 #endif
31625
31626   /* If SECURE_DELETE is disabled, then there is no way that this
31627   ** routine can be called on a page for which sqlite3PagerDontWrite()
31628   ** has not been previously called during the same transaction.
31629   ** And if DontWrite() has previously been called, the following
31630   ** conditions must be met.
31631   **
31632   ** (Later:)  Not true.  If the database is corrupted by having duplicate
31633   ** pages on the freelist (ex: corrupt9.test) then the following is not
31634   ** necessarily true:
31635   */
31636   /* assert( !pPg->inJournal && (int)pPg->pgno <= pPager->origDbSize ); */
31637
31638   assert( pPager->pInJournal!=0 );
31639   sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
31640   pPg->flags |= PGHDR_IN_JOURNAL;
31641   pPg->flags &= ~PGHDR_NEED_READ;
31642   if( pPager->stmtInUse ){
31643     assert( pPager->stmtSize >= pPager->origDbSize );
31644     sqlite3BitvecSet(pPager->pInStmt, pPg->pgno);
31645   }
31646   PAGERTRACE3("DONT_ROLLBACK page %d of %d\n", pPg->pgno, PAGERID(pPager));
31647   IOTRACE(("GARBAGE %p %d\n", pPager, pPg->pgno))
31648 }
31649
31650
31651 /*
31652 ** This routine is called to increment the database file change-counter,
31653 ** stored at byte 24 of the pager file.
31654 */
31655 static int pager_incr_changecounter(Pager *pPager, int isDirect){
31656   PgHdr *pPgHdr;
31657   u32 change_counter;
31658   int rc = SQLITE_OK;
31659
31660 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
31661   assert( isDirect==0 );  /* isDirect is only true for atomic writes */
31662 #endif
31663   if( !pPager->changeCountDone ){
31664     /* Open page 1 of the file for writing. */
31665     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
31666     if( rc!=SQLITE_OK ) return rc;
31667
31668     if( !isDirect ){
31669       rc = sqlite3PagerWrite(pPgHdr);
31670       if( rc!=SQLITE_OK ){
31671         sqlite3PagerUnref(pPgHdr);
31672         return rc;
31673       }
31674     }
31675
31676     /* Increment the value just read and write it back to byte 24. */
31677     change_counter = sqlite3Get4byte((u8*)pPager->dbFileVers);
31678     change_counter++;
31679     put32bits(((char*)pPgHdr->pData)+24, change_counter);
31680
31681 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
31682     if( isDirect && pPager->fd->pMethods ){
31683       const void *zBuf = pPgHdr->pData;
31684       rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
31685     }
31686 #endif
31687
31688     /* Release the page reference. */
31689     sqlite3PagerUnref(pPgHdr);
31690     pPager->changeCountDone = 1;
31691   }
31692   return rc;
31693 }
31694
31695 /*
31696 ** Sync the pager file to disk.
31697 */
31698 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
31699   int rc;
31700   if( MEMDB ){
31701     rc = SQLITE_OK;
31702   }else{
31703     rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
31704   }
31705   return rc;
31706 }
31707
31708 /*
31709 ** Sync the database file for the pager pPager. zMaster points to the name
31710 ** of a master journal file that should be written into the individual
31711 ** journal file. zMaster may be NULL, which is interpreted as no master
31712 ** journal (a single database transaction).
31713 **
31714 ** This routine ensures that the journal is synced, all dirty pages written
31715 ** to the database file and the database file synced. The only thing that
31716 ** remains to commit the transaction is to delete the journal file (or
31717 ** master journal file if specified).
31718 **
31719 ** Note that if zMaster==NULL, this does not overwrite a previous value
31720 ** passed to an sqlite3PagerCommitPhaseOne() call.
31721 **
31722 ** If parameter nTrunc is non-zero, then the pager file is truncated to
31723 ** nTrunc pages (this is used by auto-vacuum databases).
31724 **
31725 ** If the final parameter - noSync - is true, then the database file itself
31726 ** is not synced. The caller must call sqlite3PagerSync() directly to
31727 ** sync the database file before calling CommitPhaseTwo() to delete the
31728 ** journal file in this case.
31729 */
31730 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
31731   Pager *pPager, 
31732   const char *zMaster, 
31733   Pgno nTrunc,
31734   int noSync
31735 ){
31736   int rc = SQLITE_OK;
31737
31738   if( pPager->errCode ){
31739     return pPager->errCode;
31740   }
31741
31742   /* If no changes have been made, we can leave the transaction early.
31743   */
31744   if( pPager->dbModified==0 &&
31745         (pPager->journalMode!=PAGER_JOURNALMODE_DELETE ||
31746           pPager->exclusiveMode!=0) ){
31747     assert( pPager->dirtyCache==0 || pPager->journalOpen==0 );
31748     return SQLITE_OK;
31749   }
31750
31751   PAGERTRACE4("DATABASE SYNC: File=%s zMaster=%s nTrunc=%d\n", 
31752       pPager->zFilename, zMaster, nTrunc);
31753
31754   /* If this is an in-memory db, or no pages have been written to, or this
31755   ** function has already been called, it is a no-op.
31756   */
31757   if( pPager->state!=PAGER_SYNCED && !MEMDB && pPager->dirtyCache ){
31758     PgHdr *pPg;
31759
31760 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
31761     /* The atomic-write optimization can be used if all of the
31762     ** following are true:
31763     **
31764     **    + The file-system supports the atomic-write property for
31765     **      blocks of size page-size, and
31766     **    + This commit is not part of a multi-file transaction, and
31767     **    + Exactly one page has been modified and store in the journal file.
31768     **
31769     ** If the optimization can be used, then the journal file will never
31770     ** be created for this transaction.
31771     */
31772     int useAtomicWrite;
31773     pPg = sqlite3PcacheDirtyList(pPager->pPCache);
31774     useAtomicWrite = (
31775         !zMaster && 
31776         pPager->journalOpen &&
31777         pPager->journalOff==jrnlBufferSize(pPager) && 
31778         nTrunc==0 && 
31779         (pPg==0 || pPg->pDirty==0)
31780     );
31781     assert( pPager->journalOpen || pPager->journalMode==PAGER_JOURNALMODE_OFF );
31782     if( useAtomicWrite ){
31783       /* Update the nRec field in the journal file. */
31784       int offset = pPager->journalHdr + sizeof(aJournalMagic);
31785       assert(pPager->nRec==1);
31786       rc = write32bits(pPager->jfd, offset, pPager->nRec);
31787
31788       /* Update the db file change counter. The following call will modify
31789       ** the in-memory representation of page 1 to include the updated
31790       ** change counter and then write page 1 directly to the database
31791       ** file. Because of the atomic-write property of the host file-system, 
31792       ** this is safe.
31793       */
31794       if( rc==SQLITE_OK ){
31795         rc = pager_incr_changecounter(pPager, 1);
31796       }
31797     }else{
31798       rc = sqlite3JournalCreate(pPager->jfd);
31799     }
31800
31801     if( !useAtomicWrite && rc==SQLITE_OK )
31802 #endif
31803
31804     /* If a master journal file name has already been written to the
31805     ** journal file, then no sync is required. This happens when it is
31806     ** written, then the process fails to upgrade from a RESERVED to an
31807     ** EXCLUSIVE lock. The next time the process tries to commit the
31808     ** transaction the m-j name will have already been written.
31809     */
31810     if( !pPager->setMaster ){
31811       rc = pager_incr_changecounter(pPager, 0);
31812       if( rc!=SQLITE_OK ) goto sync_exit;
31813       if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
31814 #ifndef SQLITE_OMIT_AUTOVACUUM
31815         if( nTrunc!=0 ){
31816           /* If this transaction has made the database smaller, then all pages
31817           ** being discarded by the truncation must be written to the journal
31818           ** file.
31819           */
31820           Pgno i;
31821           int iSkip = PAGER_MJ_PGNO(pPager);
31822           for( i=nTrunc+1; i<=pPager->origDbSize; i++ ){
31823             if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
31824               rc = sqlite3PagerGet(pPager, i, &pPg);
31825               if( rc!=SQLITE_OK ) goto sync_exit;
31826               rc = sqlite3PagerWrite(pPg);
31827               sqlite3PagerUnref(pPg);
31828               if( rc!=SQLITE_OK ) goto sync_exit;
31829             }
31830           } 
31831         }
31832 #endif
31833         rc = writeMasterJournal(pPager, zMaster);
31834         if( rc!=SQLITE_OK ) goto sync_exit;
31835         rc = syncJournal(pPager);
31836       }
31837     }
31838     if( rc!=SQLITE_OK ) goto sync_exit;
31839
31840 #ifndef SQLITE_OMIT_AUTOVACUUM
31841     if( nTrunc!=0 ){
31842       rc = sqlite3PagerTruncate(pPager, nTrunc);
31843       if( rc!=SQLITE_OK ) goto sync_exit;
31844     }
31845 #endif
31846
31847     /* Write all dirty pages to the database file */
31848     pPg = sqlite3PcacheDirtyList(pPager->pPCache);
31849     rc = pager_write_pagelist(pPg);
31850     if( rc!=SQLITE_OK ){
31851       assert( rc!=SQLITE_IOERR_BLOCKED );
31852       /* The error might have left the dirty list all fouled up here,
31853       ** but that does not matter because if the if the dirty list did
31854       ** get corrupted, then the transaction will roll back and
31855       ** discard the dirty list.  There is an assert in
31856       ** pager_get_all_dirty_pages() that verifies that no attempt
31857       ** is made to use an invalid dirty list.
31858       */
31859       goto sync_exit;
31860     }
31861     sqlite3PcacheCleanAll(pPager->pPCache);
31862
31863     /* Sync the database file. */
31864     if( !pPager->noSync && !noSync ){
31865       rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
31866     }
31867     IOTRACE(("DBSYNC %p\n", pPager))
31868
31869     pPager->state = PAGER_SYNCED;
31870   }else if( MEMDB && nTrunc!=0 ){
31871     rc = sqlite3PagerTruncate(pPager, nTrunc);
31872   }
31873
31874 sync_exit:
31875   if( rc==SQLITE_IOERR_BLOCKED ){
31876     /* pager_incr_changecounter() may attempt to obtain an exclusive
31877      * lock to spill the cache and return IOERR_BLOCKED. But since 
31878      * there is no chance the cache is inconsistent, it is
31879      * better to return SQLITE_BUSY.
31880      */
31881     rc = SQLITE_BUSY;
31882   }
31883   return rc;
31884 }
31885
31886
31887 /*
31888 ** Commit all changes to the database and release the write lock.
31889 **
31890 ** If the commit fails for any reason, a rollback attempt is made
31891 ** and an error code is returned.  If the commit worked, SQLITE_OK
31892 ** is returned.
31893 */
31894 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
31895   int rc = SQLITE_OK;
31896
31897   if( pPager->errCode ){
31898     return pPager->errCode;
31899   }
31900   if( pPager->state<PAGER_RESERVED ){
31901     return SQLITE_ERROR;
31902   }
31903   if( pPager->dbModified==0 &&
31904         (pPager->journalMode!=PAGER_JOURNALMODE_DELETE ||
31905           pPager->exclusiveMode!=0) ){
31906     assert( pPager->dirtyCache==0 || pPager->journalOpen==0 );
31907     return SQLITE_OK;
31908   }
31909   PAGERTRACE2("COMMIT %d\n", PAGERID(pPager));
31910   if( MEMDB ){
31911     sqlite3PcacheCommit(pPager->pPCache, 0);
31912     sqlite3PcacheCleanAll(pPager->pPCache);
31913     sqlite3PcacheAssertFlags(pPager->pPCache, 0, PGHDR_IN_JOURNAL);
31914     pPager->state = PAGER_SHARED;
31915   }else{
31916     assert( pPager->state==PAGER_SYNCED || !pPager->dirtyCache );
31917     rc = pager_end_transaction(pPager, pPager->setMaster);
31918     rc = pager_error(pPager, rc);
31919   }
31920   return rc;
31921 }
31922
31923 /*
31924 ** Rollback all changes.  The database falls back to PAGER_SHARED mode.
31925 ** All in-memory cache pages revert to their original data contents.
31926 ** The journal is deleted.
31927 **
31928 ** This routine cannot fail unless some other process is not following
31929 ** the correct locking protocol or unless some other
31930 ** process is writing trash into the journal file (SQLITE_CORRUPT) or
31931 ** unless a prior malloc() failed (SQLITE_NOMEM).  Appropriate error
31932 ** codes are returned for all these occasions.  Otherwise,
31933 ** SQLITE_OK is returned.
31934 */
31935 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
31936   int rc = SQLITE_OK;
31937   PAGERTRACE2("ROLLBACK %d\n", PAGERID(pPager));
31938   if( MEMDB ){
31939     sqlite3PcacheRollback(pPager->pPCache, 1, pPager->xReiniter);
31940     sqlite3PcacheRollback(pPager->pPCache, 0, pPager->xReiniter);
31941     sqlite3PcacheCleanAll(pPager->pPCache);
31942     sqlite3PcacheAssertFlags(pPager->pPCache, 0, PGHDR_IN_JOURNAL);
31943     pPager->dbSize = pPager->origDbSize;
31944     pager_truncate_cache(pPager);
31945     pPager->stmtInUse = 0;
31946     pPager->state = PAGER_SHARED;
31947   }else if( !pPager->dirtyCache || !pPager->journalOpen ){
31948     rc = pager_end_transaction(pPager, pPager->setMaster);
31949   }else if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
31950     if( pPager->state>=PAGER_EXCLUSIVE ){
31951       pager_playback(pPager, 0);
31952     }
31953     rc = pPager->errCode;
31954   }else{
31955     if( pPager->state==PAGER_RESERVED ){
31956       int rc2;
31957       rc = pager_playback(pPager, 0);
31958       rc2 = pager_end_transaction(pPager, pPager->setMaster);
31959       if( rc==SQLITE_OK ){
31960         rc = rc2;
31961       }
31962     }else{
31963       rc = pager_playback(pPager, 0);
31964     }
31965
31966     pPager->dbSize = -1;
31967
31968     /* If an error occurs during a ROLLBACK, we can no longer trust the pager
31969     ** cache. So call pager_error() on the way out to make any error 
31970     ** persistent.
31971     */
31972     rc = pager_error(pPager, rc);
31973   }
31974   return rc;
31975 }
31976
31977 /*
31978 ** Return TRUE if the database file is opened read-only.  Return FALSE
31979 ** if the database is (in theory) writable.
31980 */
31981 SQLITE_PRIVATE int sqlite3PagerIsreadonly(Pager *pPager){
31982   return pPager->readOnly;
31983 }
31984
31985 /*
31986 ** Return the number of references to the pager.
31987 */
31988 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
31989   return sqlite3PcacheRefCount(pPager->pPCache);
31990 }
31991
31992 #ifdef SQLITE_TEST
31993 /*
31994 ** This routine is used for testing and analysis only.
31995 */
31996 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
31997   static int a[11];
31998   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
31999   a[1] = sqlite3PcachePagecount(pPager->pPCache);
32000   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
32001   a[3] = pPager->dbSize;
32002   a[4] = pPager->state;
32003   a[5] = pPager->errCode;
32004   a[6] = pPager->nHit;
32005   a[7] = pPager->nMiss;
32006   a[8] = 0;  /* Used to be pPager->nOvfl */
32007   a[9] = pPager->nRead;
32008   a[10] = pPager->nWrite;
32009   return a;
32010 }
32011 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
32012   return MEMDB;
32013 }
32014 #endif
32015
32016 /*
32017 ** Set the statement rollback point.
32018 **
32019 ** This routine should be called with the transaction journal already
32020 ** open.  A new statement journal is created that can be used to rollback
32021 ** changes of a single SQL command within a larger transaction.
32022 */
32023 static int pagerStmtBegin(Pager *pPager){
32024   int rc;
32025   assert( !pPager->stmtInUse );
32026   assert( pPager->state>=PAGER_SHARED );
32027   assert( pPager->dbSize>=0 );
32028   PAGERTRACE2("STMT-BEGIN %d\n", PAGERID(pPager));
32029   if( MEMDB ){
32030     pPager->stmtInUse = 1;
32031     pPager->stmtSize = pPager->dbSize;
32032     return SQLITE_OK;
32033   }
32034   if( !pPager->journalOpen ){
32035     pPager->stmtAutoopen = 1;
32036     return SQLITE_OK;
32037   }
32038   assert( pPager->journalOpen );
32039   assert( pPager->pInStmt==0 );
32040   pPager->pInStmt = sqlite3BitvecCreate(pPager->dbSize);
32041   if( pPager->pInStmt==0 ){
32042     /* sqlite3OsLock(pPager->fd, SHARED_LOCK); */
32043     return SQLITE_NOMEM;
32044   }
32045   pPager->stmtJSize = pPager->journalOff;
32046   pPager->stmtSize = pPager->dbSize;
32047   pPager->stmtHdrOff = 0;
32048   pPager->stmtCksum = pPager->cksumInit;
32049   if( !pPager->stmtOpen ){
32050     rc = sqlite3PagerOpentemp(pPager, pPager->stfd, SQLITE_OPEN_SUBJOURNAL);
32051     if( rc ){
32052       goto stmt_begin_failed;
32053     }
32054     pPager->stmtOpen = 1;
32055     pPager->stmtNRec = 0;
32056   }
32057   pPager->stmtInUse = 1;
32058   return SQLITE_OK;
32059  
32060 stmt_begin_failed:
32061   if( pPager->pInStmt ){
32062     sqlite3BitvecDestroy(pPager->pInStmt);
32063     pPager->pInStmt = 0;
32064   }
32065   return rc;
32066 }
32067 SQLITE_PRIVATE int sqlite3PagerStmtBegin(Pager *pPager){
32068   int rc;
32069   rc = pagerStmtBegin(pPager);
32070   return rc;
32071 }
32072
32073 /*
32074 ** Commit a statement.
32075 */
32076 SQLITE_PRIVATE int sqlite3PagerStmtCommit(Pager *pPager){
32077   if( pPager->stmtInUse ){
32078     PAGERTRACE2("STMT-COMMIT %d\n", PAGERID(pPager));
32079     if( !MEMDB ){
32080       sqlite3BitvecDestroy(pPager->pInStmt);
32081       pPager->pInStmt = 0;
32082     }else{
32083       sqlite3PcacheCommit(pPager->pPCache, 1);
32084     }
32085     pPager->stmtNRec = 0;
32086     pPager->stmtInUse = 0;
32087   }
32088   pPager->stmtAutoopen = 0;
32089   return SQLITE_OK;
32090 }
32091
32092 /*
32093 ** Rollback a statement.
32094 */
32095 SQLITE_PRIVATE int sqlite3PagerStmtRollback(Pager *pPager){
32096   int rc;
32097   if( pPager->stmtInUse ){
32098     PAGERTRACE2("STMT-ROLLBACK %d\n", PAGERID(pPager));
32099     if( MEMDB ){
32100       sqlite3PcacheRollback(pPager->pPCache, 1, pPager->xReiniter);
32101       pPager->dbSize = pPager->stmtSize;
32102       pager_truncate_cache(pPager);
32103       rc = SQLITE_OK;
32104     }else{
32105       rc = pager_stmt_playback(pPager);
32106     }
32107     sqlite3PagerStmtCommit(pPager);
32108   }else{
32109     rc = SQLITE_OK;
32110   }
32111   pPager->stmtAutoopen = 0;
32112   return rc;
32113 }
32114
32115 /*
32116 ** Return the full pathname of the database file.
32117 */
32118 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
32119   return pPager->zFilename;
32120 }
32121
32122 /*
32123 ** Return the VFS structure for the pager.
32124 */
32125 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
32126   return pPager->pVfs;
32127 }
32128
32129 /*
32130 ** Return the file handle for the database file associated
32131 ** with the pager.  This might return NULL if the file has
32132 ** not yet been opened.
32133 */
32134 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
32135   return pPager->fd;
32136 }
32137
32138 /*
32139 ** Return the directory of the database file.
32140 */
32141 SQLITE_PRIVATE const char *sqlite3PagerDirname(Pager *pPager){
32142   return pPager->zDirectory;
32143 }
32144
32145 /*
32146 ** Return the full pathname of the journal file.
32147 */
32148 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
32149   return pPager->zJournal;
32150 }
32151
32152 /*
32153 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
32154 ** if fsync()s are executed normally.
32155 */
32156 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
32157   return pPager->noSync;
32158 }
32159
32160 #ifdef SQLITE_HAS_CODEC
32161 /*
32162 ** Set the codec for this pager
32163 */
32164 SQLITE_PRIVATE void sqlite3PagerSetCodec(
32165   Pager *pPager,
32166   void *(*xCodec)(void*,void*,Pgno,int),
32167   void *pCodecArg
32168 ){
32169   pPager->xCodec = xCodec;
32170   pPager->pCodecArg = pCodecArg;
32171 }
32172 #endif
32173
32174 #ifndef SQLITE_OMIT_AUTOVACUUM
32175 /*
32176 ** Move the page pPg to location pgno in the file.
32177 **
32178 ** There must be no references to the page previously located at
32179 ** pgno (which we call pPgOld) though that page is allowed to be
32180 ** in cache.  If the page previously located at pgno is not already
32181 ** in the rollback journal, it is not put there by by this routine.
32182 **
32183 ** References to the page pPg remain valid. Updating any
32184 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
32185 ** allocated along with the page) is the responsibility of the caller.
32186 **
32187 ** A transaction must be active when this routine is called. It used to be
32188 ** required that a statement transaction was not active, but this restriction
32189 ** has been removed (CREATE INDEX needs to move a page when a statement
32190 ** transaction is active).
32191 **
32192 ** If the fourth argument, isCommit, is non-zero, then this page is being
32193 ** moved as part of a database reorganization just before the transaction 
32194 ** is being committed. In this case, it is guaranteed that the database page 
32195 ** pPg refers to will not be written to again within this transaction.
32196 */
32197 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
32198   PgHdr *pPgOld;  /* The page being overwritten. */
32199   Pgno needSyncPgno = 0;
32200
32201   assert( pPg->nRef>0 );
32202
32203   PAGERTRACE5("MOVE %d page %d (needSync=%d) moves to %d\n", 
32204       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno);
32205   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
32206
32207   pager_get_content(pPg);
32208
32209   /* If the journal needs to be sync()ed before page pPg->pgno can
32210   ** be written to, store pPg->pgno in local variable needSyncPgno.
32211   **
32212   ** If the isCommit flag is set, there is no need to remember that
32213   ** the journal needs to be sync()ed before database page pPg->pgno 
32214   ** can be written to. The caller has already promised not to write to it.
32215   */
32216   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
32217     needSyncPgno = pPg->pgno;
32218     assert( (pPg->flags&PGHDR_IN_JOURNAL) || (int)pgno>pPager->origDbSize );
32219     assert( pPg->flags&PGHDR_DIRTY );
32220     assert( pPager->needSync );
32221   }
32222
32223   /* If the cache contains a page with page-number pgno, remove it
32224   ** from its hash chain. Also, if the PgHdr.needSync was set for 
32225   ** page pgno before the 'move' operation, it needs to be retained 
32226   ** for the page moved there.
32227   */
32228   pPg->flags &= ~(PGHDR_NEED_SYNC|PGHDR_IN_JOURNAL);
32229   pPgOld = pager_lookup(pPager, pgno);
32230   assert( !pPgOld || pPgOld->nRef==1 );
32231   if( pPgOld ){
32232     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
32233   }
32234   if( sqlite3BitvecTest(pPager->pInJournal, pgno) ){
32235     assert( !MEMDB );
32236     pPg->flags |= PGHDR_IN_JOURNAL;
32237   }
32238
32239   sqlite3PcacheMove(pPg, pgno);
32240   if( pPgOld ){
32241     sqlite3PcacheMove(pPgOld, 0);
32242     sqlite3PcacheRelease(pPgOld);
32243   }
32244
32245   makeDirty(pPg);
32246   pPager->dirtyCache = 1;
32247   pPager->dbModified = 1;
32248
32249   if( needSyncPgno ){
32250     /* If needSyncPgno is non-zero, then the journal file needs to be 
32251     ** sync()ed before any data is written to database file page needSyncPgno.
32252     ** Currently, no such page exists in the page-cache and the 
32253     ** "is journaled" bitvec flag has been set. This needs to be remedied by
32254     ** loading the page into the pager-cache and setting the PgHdr.needSync 
32255     ** flag.
32256     **
32257     ** If the attempt to load the page into the page-cache fails, (due
32258     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
32259     ** array. Otherwise, if the page is loaded and written again in
32260     ** this transaction, it may be written to the database file before
32261     ** it is synced into the journal file. This way, it may end up in
32262     ** the journal file twice, but that is not a problem.
32263     **
32264     ** The sqlite3PagerGet() call may cause the journal to sync. So make
32265     ** sure the Pager.needSync flag is set too.
32266     */
32267     int rc;
32268     PgHdr *pPgHdr;
32269     assert( pPager->needSync );
32270     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
32271     if( rc!=SQLITE_OK ){
32272       if( pPager->pInJournal && (int)needSyncPgno<=pPager->origDbSize ){
32273         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno);
32274       }
32275       return rc;
32276     }
32277     pPager->needSync = 1;
32278     assert( pPager->noSync==0 && !MEMDB );
32279     pPgHdr->flags |= PGHDR_NEED_SYNC;
32280     pPgHdr->flags |= PGHDR_IN_JOURNAL;
32281     makeDirty(pPgHdr);
32282     sqlite3PagerUnref(pPgHdr);
32283   }
32284
32285   return SQLITE_OK;
32286 }
32287 #endif
32288
32289 /*
32290 ** Return a pointer to the data for the specified page.
32291 */
32292 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
32293   assert( pPg->nRef>0 );
32294   return pPg->pData;
32295 }
32296
32297 /*
32298 ** Return a pointer to the Pager.nExtra bytes of "extra" space 
32299 ** allocated along with the specified page.
32300 */
32301 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
32302   Pager *pPager = pPg->pPager;
32303   return (pPager?pPg->pExtra:0);
32304 }
32305
32306 /*
32307 ** Get/set the locking-mode for this pager. Parameter eMode must be one
32308 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
32309 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
32310 ** the locking-mode is set to the value specified.
32311 **
32312 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
32313 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
32314 ** locking-mode.
32315 */
32316 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
32317   assert( eMode==PAGER_LOCKINGMODE_QUERY
32318             || eMode==PAGER_LOCKINGMODE_NORMAL
32319             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
32320   assert( PAGER_LOCKINGMODE_QUERY<0 );
32321   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
32322   if( eMode>=0 && !pPager->tempFile ){
32323     pPager->exclusiveMode = eMode;
32324   }
32325   return (int)pPager->exclusiveMode;
32326 }
32327
32328 /*
32329 ** Get/set the journal-mode for this pager. Parameter eMode must be one
32330 ** of PAGER_JOURNALMODE_QUERY, PAGER_JOURNALMODE_DELETE or 
32331 ** PAGER_JOURNALMODE_PERSIST. If the parameter is not _QUERY, then
32332 ** the journal-mode is set to the value specified.
32333 **
32334 ** The returned value is either PAGER_JOURNALMODE_DELETE or
32335 ** PAGER_JOURNALMODE_PERSIST, indicating the current (possibly updated)
32336 ** journal-mode.
32337 */
32338 SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *pPager, int eMode){
32339   assert( eMode==PAGER_JOURNALMODE_QUERY
32340             || eMode==PAGER_JOURNALMODE_DELETE
32341             || eMode==PAGER_JOURNALMODE_PERSIST
32342             || eMode==PAGER_JOURNALMODE_OFF );
32343   assert( PAGER_JOURNALMODE_QUERY<0 );
32344   assert( PAGER_JOURNALMODE_DELETE>=0 && PAGER_JOURNALMODE_PERSIST>=0 );
32345   if( eMode>=0 ){
32346     pPager->journalMode = eMode;
32347   }
32348   return (int)pPager->journalMode;
32349 }
32350
32351 /*
32352 ** Get/set the size-limit used for persistent journal files.
32353 */
32354 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
32355   if( iLimit>=-1 ){
32356     pPager->journalSizeLimit = iLimit;
32357   }
32358   return pPager->journalSizeLimit;
32359 }
32360
32361 #endif /* SQLITE_OMIT_DISKIO */
32362
32363 /************** End of pager.c ***********************************************/
32364 /************** Begin file btmutex.c *****************************************/
32365 /*
32366 ** 2007 August 27
32367 **
32368 ** The author disclaims copyright to this source code.  In place of
32369 ** a legal notice, here is a blessing:
32370 **
32371 **    May you do good and not evil.
32372 **    May you find forgiveness for yourself and forgive others.
32373 **    May you share freely, never taking more than you give.
32374 **
32375 *************************************************************************
32376 **
32377 ** $Id: btmutex.c,v 1.10 2008/07/14 19:39:17 drh Exp $
32378 **
32379 ** This file contains code used to implement mutexes on Btree objects.
32380 ** This code really belongs in btree.c.  But btree.c is getting too
32381 ** big and we want to break it down some.  This packaged seemed like
32382 ** a good breakout.
32383 */
32384 /************** Include btreeInt.h in the middle of btmutex.c ****************/
32385 /************** Begin file btreeInt.h ****************************************/
32386 /*
32387 ** 2004 April 6
32388 **
32389 ** The author disclaims copyright to this source code.  In place of
32390 ** a legal notice, here is a blessing:
32391 **
32392 **    May you do good and not evil.
32393 **    May you find forgiveness for yourself and forgive others.
32394 **    May you share freely, never taking more than you give.
32395 **
32396 *************************************************************************
32397 ** $Id: btreeInt.h,v 1.31 2008/09/18 17:34:44 danielk1977 Exp $
32398 **
32399 ** This file implements a external (disk-based) database using BTrees.
32400 ** For a detailed discussion of BTrees, refer to
32401 **
32402 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
32403 **     "Sorting And Searching", pages 473-480. Addison-Wesley
32404 **     Publishing Company, Reading, Massachusetts.
32405 **
32406 ** The basic idea is that each page of the file contains N database
32407 ** entries and N+1 pointers to subpages.
32408 **
32409 **   ----------------------------------------------------------------
32410 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
32411 **   ----------------------------------------------------------------
32412 **
32413 ** All of the keys on the page that Ptr(0) points to have values less
32414 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
32415 ** values greater than Key(0) and less than Key(1).  All of the keys
32416 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
32417 ** so forth.
32418 **
32419 ** Finding a particular key requires reading O(log(M)) pages from the 
32420 ** disk where M is the number of entries in the tree.
32421 **
32422 ** In this implementation, a single file can hold one or more separate 
32423 ** BTrees.  Each BTree is identified by the index of its root page.  The
32424 ** key and data for any entry are combined to form the "payload".  A
32425 ** fixed amount of payload can be carried directly on the database
32426 ** page.  If the payload is larger than the preset amount then surplus
32427 ** bytes are stored on overflow pages.  The payload for an entry
32428 ** and the preceding pointer are combined to form a "Cell".  Each 
32429 ** page has a small header which contains the Ptr(N) pointer and other
32430 ** information such as the size of key and data.
32431 **
32432 ** FORMAT DETAILS
32433 **
32434 ** The file is divided into pages.  The first page is called page 1,
32435 ** the second is page 2, and so forth.  A page number of zero indicates
32436 ** "no such page".  The page size can be anything between 512 and 65536.
32437 ** Each page can be either a btree page, a freelist page or an overflow
32438 ** page.
32439 **
32440 ** The first page is always a btree page.  The first 100 bytes of the first
32441 ** page contain a special header (the "file header") that describes the file.
32442 ** The format of the file header is as follows:
32443 **
32444 **   OFFSET   SIZE    DESCRIPTION
32445 **      0      16     Header string: "SQLite format 3\000"
32446 **     16       2     Page size in bytes.  
32447 **     18       1     File format write version
32448 **     19       1     File format read version
32449 **     20       1     Bytes of unused space at the end of each page
32450 **     21       1     Max embedded payload fraction
32451 **     22       1     Min embedded payload fraction
32452 **     23       1     Min leaf payload fraction
32453 **     24       4     File change counter
32454 **     28       4     Reserved for future use
32455 **     32       4     First freelist page
32456 **     36       4     Number of freelist pages in the file
32457 **     40      60     15 4-byte meta values passed to higher layers
32458 **
32459 ** All of the integer values are big-endian (most significant byte first).
32460 **
32461 ** The file change counter is incremented when the database is changed
32462 ** This counter allows other processes to know when the file has changed
32463 ** and thus when they need to flush their cache.
32464 **
32465 ** The max embedded payload fraction is the amount of the total usable
32466 ** space in a page that can be consumed by a single cell for standard
32467 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
32468 ** is to limit the maximum cell size so that at least 4 cells will fit
32469 ** on one page.  Thus the default max embedded payload fraction is 64.
32470 **
32471 ** If the payload for a cell is larger than the max payload, then extra
32472 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
32473 ** as many bytes as possible are moved into the overflow pages without letting
32474 ** the cell size drop below the min embedded payload fraction.
32475 **
32476 ** The min leaf payload fraction is like the min embedded payload fraction
32477 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
32478 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
32479 ** not specified in the header.
32480 **
32481 ** Each btree pages is divided into three sections:  The header, the
32482 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
32483 ** file header that occurs before the page header.
32484 **
32485 **      |----------------|
32486 **      | file header    |   100 bytes.  Page 1 only.
32487 **      |----------------|
32488 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
32489 **      |----------------|
32490 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
32491 **      | array          |   |  Grows downward
32492 **      |                |   v
32493 **      |----------------|
32494 **      | unallocated    |
32495 **      | space          |
32496 **      |----------------|   ^  Grows upwards
32497 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
32498 **      | area           |   |  and free space fragments.
32499 **      |----------------|
32500 **
32501 ** The page headers looks like this:
32502 **
32503 **   OFFSET   SIZE     DESCRIPTION
32504 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
32505 **      1       2      byte offset to the first freeblock
32506 **      3       2      number of cells on this page
32507 **      5       2      first byte of the cell content area
32508 **      7       1      number of fragmented free bytes
32509 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
32510 **
32511 ** The flags define the format of this btree page.  The leaf flag means that
32512 ** this page has no children.  The zerodata flag means that this page carries
32513 ** only keys and no data.  The intkey flag means that the key is a integer
32514 ** which is stored in the key size entry of the cell header rather than in
32515 ** the payload area.
32516 **
32517 ** The cell pointer array begins on the first byte after the page header.
32518 ** The cell pointer array contains zero or more 2-byte numbers which are
32519 ** offsets from the beginning of the page to the cell content in the cell
32520 ** content area.  The cell pointers occur in sorted order.  The system strives
32521 ** to keep free space after the last cell pointer so that new cells can
32522 ** be easily added without having to defragment the page.
32523 **
32524 ** Cell content is stored at the very end of the page and grows toward the
32525 ** beginning of the page.
32526 **
32527 ** Unused space within the cell content area is collected into a linked list of
32528 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
32529 ** to the first freeblock is given in the header.  Freeblocks occur in
32530 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
32531 ** any group of 3 or fewer unused bytes in the cell content area cannot
32532 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
32533 ** a fragment.  The total number of bytes in all fragments is recorded.
32534 ** in the page header at offset 7.
32535 **
32536 **    SIZE    DESCRIPTION
32537 **      2     Byte offset of the next freeblock
32538 **      2     Bytes in this freeblock
32539 **
32540 ** Cells are of variable length.  Cells are stored in the cell content area at
32541 ** the end of the page.  Pointers to the cells are in the cell pointer array
32542 ** that immediately follows the page header.  Cells is not necessarily
32543 ** contiguous or in order, but cell pointers are contiguous and in order.
32544 **
32545 ** Cell content makes use of variable length integers.  A variable
32546 ** length integer is 1 to 9 bytes where the lower 7 bits of each 
32547 ** byte are used.  The integer consists of all bytes that have bit 8 set and
32548 ** the first byte with bit 8 clear.  The most significant byte of the integer
32549 ** appears first.  A variable-length integer may not be more than 9 bytes long.
32550 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
32551 ** allows a 64-bit integer to be encoded in 9 bytes.
32552 **
32553 **    0x00                      becomes  0x00000000
32554 **    0x7f                      becomes  0x0000007f
32555 **    0x81 0x00                 becomes  0x00000080
32556 **    0x82 0x00                 becomes  0x00000100
32557 **    0x80 0x7f                 becomes  0x0000007f
32558 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
32559 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
32560 **
32561 ** Variable length integers are used for rowids and to hold the number of
32562 ** bytes of key and data in a btree cell.
32563 **
32564 ** The content of a cell looks like this:
32565 **
32566 **    SIZE    DESCRIPTION
32567 **      4     Page number of the left child. Omitted if leaf flag is set.
32568 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
32569 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
32570 **      *     Payload
32571 **      4     First page of the overflow chain.  Omitted if no overflow
32572 **
32573 ** Overflow pages form a linked list.  Each page except the last is completely
32574 ** filled with data (pagesize - 4 bytes).  The last page can have as little
32575 ** as 1 byte of data.
32576 **
32577 **    SIZE    DESCRIPTION
32578 **      4     Page number of next overflow page
32579 **      *     Data
32580 **
32581 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
32582 ** file header points to the first in a linked list of trunk page.  Each trunk
32583 ** page points to multiple leaf pages.  The content of a leaf page is
32584 ** unspecified.  A trunk page looks like this:
32585 **
32586 **    SIZE    DESCRIPTION
32587 **      4     Page number of next trunk page
32588 **      4     Number of leaf pointers on this page
32589 **      *     zero or more pages numbers of leaves
32590 */
32591
32592 /* Round up a number to the next larger multiple of 8.  This is used
32593 ** to force 8-byte alignment on 64-bit architectures.
32594 */
32595 #define ROUND8(x)   ((x+7)&~7)
32596
32597
32598 /* The following value is the maximum cell size assuming a maximum page
32599 ** size give above.
32600 */
32601 #define MX_CELL_SIZE(pBt)  (pBt->pageSize-8)
32602
32603 /* The maximum number of cells on a single page of the database.  This
32604 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
32605 ** plus 2 bytes for the index to the cell in the page header).  Such
32606 ** small cells will be rare, but they are possible.
32607 */
32608 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
32609
32610 /* Forward declarations */
32611 typedef struct MemPage MemPage;
32612 typedef struct BtLock BtLock;
32613
32614 /*
32615 ** This is a magic string that appears at the beginning of every
32616 ** SQLite database in order to identify the file as a real database.
32617 **
32618 ** You can change this value at compile-time by specifying a
32619 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
32620 ** header must be exactly 16 bytes including the zero-terminator so
32621 ** the string itself should be 15 characters long.  If you change
32622 ** the header, then your custom library will not be able to read 
32623 ** databases generated by the standard tools and the standard tools
32624 ** will not be able to read databases created by your custom library.
32625 */
32626 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
32627 #  define SQLITE_FILE_HEADER "SQLite format 3"
32628 #endif
32629
32630 /*
32631 ** Page type flags.  An ORed combination of these flags appear as the
32632 ** first byte of on-disk image of every BTree page.
32633 */
32634 #define PTF_INTKEY    0x01
32635 #define PTF_ZERODATA  0x02
32636 #define PTF_LEAFDATA  0x04
32637 #define PTF_LEAF      0x08
32638
32639 /*
32640 ** As each page of the file is loaded into memory, an instance of the following
32641 ** structure is appended and initialized to zero.  This structure stores
32642 ** information about the page that is decoded from the raw file page.
32643 **
32644 ** The pParent field points back to the parent page.  This allows us to
32645 ** walk up the BTree from any leaf to the root.  Care must be taken to
32646 ** unref() the parent page pointer when this page is no longer referenced.
32647 ** The pageDestructor() routine handles that chore.
32648 **
32649 ** Access to all fields of this structure is controlled by the mutex
32650 ** stored in MemPage.pBt->mutex.
32651 */
32652 struct MemPage {
32653   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
32654   u8 idxShift;         /* True if Cell indices have changed */
32655   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
32656   u8 intKey;           /* True if intkey flag is set */
32657   u8 leaf;             /* True if leaf flag is set */
32658   u8 hasData;          /* True if this page stores data */
32659   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
32660   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
32661   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
32662   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
32663   u16 cellOffset;      /* Index in aData of first cell pointer */
32664   u16 idxParent;       /* Index in parent of this node */
32665   u16 nFree;           /* Number of free bytes on the page */
32666   u16 nCell;           /* Number of cells on this page, local and ovfl */
32667   u16 maskPage;        /* Mask for page offset */
32668   struct _OvflCell {   /* Cells that will not fit on aData[] */
32669     u8 *pCell;          /* Pointers to the body of the overflow cell */
32670     u16 idx;            /* Insert this cell before idx-th non-overflow cell */
32671   } aOvfl[5];
32672   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
32673   u8 *aData;           /* Pointer to disk image of the page data */
32674   DbPage *pDbPage;     /* Pager page handle */
32675   Pgno pgno;           /* Page number for this page */
32676   MemPage *pParent;    /* The parent of this page.  NULL for root */
32677 };
32678
32679 /*
32680 ** Possible values for the MemPage.isInit variable. When a page is first
32681 ** loaded or if the data stored in the MemPage struct is invalidated, 
32682 ** MemPage.isInit is set to PAGE_ISINIT_NONE. If the MemPage structure
32683 ** is fully initialized, then MemPage.isInit is set to PAGE_ISINIT_FULL.
32684 ** MemPage.isInit is set to PAGE_ISINIT_DATA when the MemPage struct is
32685 ** populated, but the MemPage.pParent variable is not necessarily correct.
32686 */
32687 #define PAGE_ISINIT_NONE 0
32688 #define PAGE_ISINIT_DATA 1
32689 #define PAGE_ISINIT_FULL 2
32690
32691 /*
32692 ** The in-memory image of a disk page has the auxiliary information appended
32693 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
32694 ** that extra information.
32695 */
32696 #define EXTRA_SIZE sizeof(MemPage)
32697
32698 /* A Btree handle
32699 **
32700 ** A database connection contains a pointer to an instance of
32701 ** this object for every database file that it has open.  This structure
32702 ** is opaque to the database connection.  The database connection cannot
32703 ** see the internals of this structure and only deals with pointers to
32704 ** this structure.
32705 **
32706 ** For some database files, the same underlying database cache might be 
32707 ** shared between multiple connections.  In that case, each contection
32708 ** has it own pointer to this object.  But each instance of this object
32709 ** points to the same BtShared object.  The database cache and the
32710 ** schema associated with the database file are all contained within
32711 ** the BtShared object.
32712 **
32713 ** All fields in this structure are accessed under sqlite3.mutex.
32714 ** The pBt pointer itself may not be changed while there exists cursors 
32715 ** in the referenced BtShared that point back to this Btree since those
32716 ** cursors have to do go through this Btree to find their BtShared and
32717 ** they often do so without holding sqlite3.mutex.
32718 */
32719 struct Btree {
32720   sqlite3 *db;       /* The database connection holding this btree */
32721   BtShared *pBt;     /* Sharable content of this btree */
32722   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
32723   u8 sharable;       /* True if we can share pBt with another db */
32724   u8 locked;         /* True if db currently has pBt locked */
32725   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
32726   Btree *pNext;      /* List of other sharable Btrees from the same db */
32727   Btree *pPrev;      /* Back pointer of the same list */
32728 };
32729
32730 /*
32731 ** Btree.inTrans may take one of the following values.
32732 **
32733 ** If the shared-data extension is enabled, there may be multiple users
32734 ** of the Btree structure. At most one of these may open a write transaction,
32735 ** but any number may have active read transactions.
32736 */
32737 #define TRANS_NONE  0
32738 #define TRANS_READ  1
32739 #define TRANS_WRITE 2
32740
32741 /*
32742 ** An instance of this object represents a single database file.
32743 ** 
32744 ** A single database file can be in use as the same time by two
32745 ** or more database connections.  When two or more connections are
32746 ** sharing the same database file, each connection has it own
32747 ** private Btree object for the file and each of those Btrees points
32748 ** to this one BtShared object.  BtShared.nRef is the number of
32749 ** connections currently sharing this database file.
32750 **
32751 ** Fields in this structure are accessed under the BtShared.mutex
32752 ** mutex, except for nRef and pNext which are accessed under the
32753 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
32754 ** may not be modified once it is initially set as long as nRef>0.
32755 ** The pSchema field may be set once under BtShared.mutex and
32756 ** thereafter is unchanged as long as nRef>0.
32757 */
32758 struct BtShared {
32759   Pager *pPager;        /* The page cache */
32760   sqlite3 *db;          /* Database connection currently using this Btree */
32761   BtCursor *pCursor;    /* A list of all open cursors */
32762   MemPage *pPage1;      /* First page of the database */
32763   u8 inStmt;            /* True if we are in a statement subtransaction */
32764   u8 readOnly;          /* True if the underlying file is readonly */
32765   u8 pageSizeFixed;     /* True if the page size can no longer be changed */
32766 #ifndef SQLITE_OMIT_AUTOVACUUM
32767   u8 autoVacuum;        /* True if auto-vacuum is enabled */
32768   u8 incrVacuum;        /* True if incr-vacuum is enabled */
32769   Pgno nTrunc;          /* Non-zero if the db will be truncated (incr vacuum) */
32770 #endif
32771   u16 pageSize;         /* Total number of bytes on a page */
32772   u16 usableSize;       /* Number of usable bytes on each page */
32773   int maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
32774   int minLocal;         /* Minimum local payload in non-LEAFDATA tables */
32775   int maxLeaf;          /* Maximum local payload in a LEAFDATA table */
32776   int minLeaf;          /* Minimum local payload in a LEAFDATA table */
32777   u8 inTransaction;     /* Transaction state */
32778   int nTransaction;     /* Number of open transactions (read + write) */
32779   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
32780   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
32781   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */
32782   BusyHandler busyHdr;  /* The busy handler for this btree */
32783 #ifndef SQLITE_OMIT_SHARED_CACHE
32784   int nRef;             /* Number of references to this structure */
32785   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
32786   BtLock *pLock;        /* List of locks held on this shared-btree struct */
32787   Btree *pExclusive;    /* Btree with an EXCLUSIVE lock on the whole db */
32788 #endif
32789   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
32790 };
32791
32792 /*
32793 ** An instance of the following structure is used to hold information
32794 ** about a cell.  The parseCellPtr() function fills in this structure
32795 ** based on information extract from the raw disk page.
32796 */
32797 typedef struct CellInfo CellInfo;
32798 struct CellInfo {
32799   u8 *pCell;     /* Pointer to the start of cell content */
32800   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
32801   u32 nData;     /* Number of bytes of data */
32802   u32 nPayload;  /* Total amount of payload */
32803   u16 nHeader;   /* Size of the cell content header in bytes */
32804   u16 nLocal;    /* Amount of payload held locally */
32805   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
32806   u16 nSize;     /* Size of the cell content on the main b-tree page */
32807 };
32808
32809 /*
32810 ** A cursor is a pointer to a particular entry within a particular
32811 ** b-tree within a database file.
32812 **
32813 ** The entry is identified by its MemPage and the index in
32814 ** MemPage.aCell[] of the entry.
32815 **
32816 ** When a single database file can shared by two more database connections,
32817 ** but cursors cannot be shared.  Each cursor is associated with a
32818 ** particular database connection identified BtCursor.pBtree.db.
32819 **
32820 ** Fields in this structure are accessed under the BtShared.mutex
32821 ** found at self->pBt->mutex. 
32822 */
32823 struct BtCursor {
32824   Btree *pBtree;            /* The Btree to which this cursor belongs */
32825   BtShared *pBt;            /* The BtShared this cursor points to */
32826   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
32827   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
32828   Pgno pgnoRoot;            /* The root page of this tree */
32829   MemPage *pPage;           /* Page that contains the entry */
32830   int idx;                  /* Index of the entry in pPage->aCell[] */
32831   CellInfo info;            /* A parse of the cell we are pointing at */
32832   u8 wrFlag;                /* True if writable */
32833   u8 atLast;                /* Cursor pointing to the last entry */
32834   u8 validNKey;             /* True if info.nKey is valid */
32835   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
32836   void *pKey;      /* Saved key that was cursor's last known position */
32837   i64 nKey;        /* Size of pKey, or last integer key */
32838   int skip;        /* (skip<0) -> Prev() is a no-op. (skip>0) -> Next() is */
32839 #ifndef SQLITE_OMIT_INCRBLOB
32840   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
32841   Pgno *aOverflow;          /* Cache of overflow page locations */
32842 #endif
32843 };
32844
32845 /*
32846 ** Potential values for BtCursor.eState.
32847 **
32848 ** CURSOR_VALID:
32849 **   Cursor points to a valid entry. getPayload() etc. may be called.
32850 **
32851 ** CURSOR_INVALID:
32852 **   Cursor does not point to a valid entry. This can happen (for example) 
32853 **   because the table is empty or because BtreeCursorFirst() has not been
32854 **   called.
32855 **
32856 ** CURSOR_REQUIRESEEK:
32857 **   The table that this cursor was opened on still exists, but has been 
32858 **   modified since the cursor was last used. The cursor position is saved
32859 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
32860 **   this state, restoreCursorPosition() can be called to attempt to
32861 **   seek the cursor to the saved position.
32862 **
32863 ** CURSOR_FAULT:
32864 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
32865 **   on a different connection that shares the BtShared cache with this
32866 **   cursor.  The error has left the cache in an inconsistent state.
32867 **   Do nothing else with this cursor.  Any attempt to use the cursor
32868 **   should return the error code stored in BtCursor.skip
32869 */
32870 #define CURSOR_INVALID           0
32871 #define CURSOR_VALID             1
32872 #define CURSOR_REQUIRESEEK       2
32873 #define CURSOR_FAULT             3
32874
32875 /* The database page the PENDING_BYTE occupies. This page is never used.
32876 ** TODO: This macro is very similary to PAGER_MJ_PGNO() in pager.c. They
32877 ** should possibly be consolidated (presumably in pager.h).
32878 **
32879 ** If disk I/O is omitted (meaning that the database is stored purely
32880 ** in memory) then there is no pending byte.
32881 */
32882 #ifdef SQLITE_OMIT_DISKIO
32883 # define PENDING_BYTE_PAGE(pBt)  0x7fffffff
32884 #else
32885 # define PENDING_BYTE_PAGE(pBt) ((PENDING_BYTE/(pBt)->pageSize)+1)
32886 #endif
32887
32888 /*
32889 ** A linked list of the following structures is stored at BtShared.pLock.
32890 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
32891 ** is opened on the table with root page BtShared.iTable. Locks are removed
32892 ** from this list when a transaction is committed or rolled back, or when
32893 ** a btree handle is closed.
32894 */
32895 struct BtLock {
32896   Btree *pBtree;        /* Btree handle holding this lock */
32897   Pgno iTable;          /* Root page of table */
32898   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
32899   BtLock *pNext;        /* Next in BtShared.pLock list */
32900 };
32901
32902 /* Candidate values for BtLock.eLock */
32903 #define READ_LOCK     1
32904 #define WRITE_LOCK    2
32905
32906 /*
32907 ** These macros define the location of the pointer-map entry for a 
32908 ** database page. The first argument to each is the number of usable
32909 ** bytes on each page of the database (often 1024). The second is the
32910 ** page number to look up in the pointer map.
32911 **
32912 ** PTRMAP_PAGENO returns the database page number of the pointer-map
32913 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
32914 ** the offset of the requested map entry.
32915 **
32916 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
32917 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
32918 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
32919 ** this test.
32920 */
32921 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
32922 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
32923 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
32924
32925 /*
32926 ** The pointer map is a lookup table that identifies the parent page for
32927 ** each child page in the database file.  The parent page is the page that
32928 ** contains a pointer to the child.  Every page in the database contains
32929 ** 0 or 1 parent pages.  (In this context 'database page' refers
32930 ** to any page that is not part of the pointer map itself.)  Each pointer map
32931 ** entry consists of a single byte 'type' and a 4 byte parent page number.
32932 ** The PTRMAP_XXX identifiers below are the valid types.
32933 **
32934 ** The purpose of the pointer map is to facility moving pages from one
32935 ** position in the file to another as part of autovacuum.  When a page
32936 ** is moved, the pointer in its parent must be updated to point to the
32937 ** new location.  The pointer map is used to locate the parent page quickly.
32938 **
32939 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
32940 **                  used in this case.
32941 **
32942 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
32943 **                  is not used in this case.
32944 **
32945 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
32946 **                   overflow pages. The page number identifies the page that
32947 **                   contains the cell with a pointer to this overflow page.
32948 **
32949 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
32950 **                   overflow pages. The page-number identifies the previous
32951 **                   page in the overflow page list.
32952 **
32953 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
32954 **               identifies the parent page in the btree.
32955 */
32956 #define PTRMAP_ROOTPAGE 1
32957 #define PTRMAP_FREEPAGE 2
32958 #define PTRMAP_OVERFLOW1 3
32959 #define PTRMAP_OVERFLOW2 4
32960 #define PTRMAP_BTREE 5
32961
32962 /* A bunch of assert() statements to check the transaction state variables
32963 ** of handle p (type Btree*) are internally consistent.
32964 */
32965 #define btreeIntegrity(p) \
32966   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
32967   assert( p->pBt->inTransaction>=p->inTrans ); 
32968
32969
32970 /*
32971 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
32972 ** if the database supports auto-vacuum or not. Because it is used
32973 ** within an expression that is an argument to another macro 
32974 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
32975 ** So, this macro is defined instead.
32976 */
32977 #ifndef SQLITE_OMIT_AUTOVACUUM
32978 #define ISAUTOVACUUM (pBt->autoVacuum)
32979 #else
32980 #define ISAUTOVACUUM 0
32981 #endif
32982
32983
32984 /*
32985 ** This structure is passed around through all the sanity checking routines
32986 ** in order to keep track of some global state information.
32987 */
32988 typedef struct IntegrityCk IntegrityCk;
32989 struct IntegrityCk {
32990   BtShared *pBt;    /* The tree being checked out */
32991   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
32992   int nPage;        /* Number of pages in the database */
32993   int *anRef;       /* Number of times each page is referenced */
32994   int mxErr;        /* Stop accumulating errors when this reaches zero */
32995   int nErr;         /* Number of messages written to zErrMsg so far */
32996   int mallocFailed; /* A memory allocation error has occurred */
32997   StrAccum errMsg;  /* Accumulate the error message text here */
32998 };
32999
33000 /*
33001 ** Read or write a two- and four-byte big-endian integer values.
33002 */
33003 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
33004 #define put2byte(p,v) ((p)[0] = (v)>>8, (p)[1] = (v))
33005 #define get4byte sqlite3Get4byte
33006 #define put4byte sqlite3Put4byte
33007
33008 /*
33009 ** Internal routines that should be accessed by the btree layer only.
33010 */
33011 SQLITE_PRIVATE int sqlite3BtreeGetPage(BtShared*, Pgno, MemPage**, int);
33012 SQLITE_PRIVATE int sqlite3BtreeInitPage(MemPage *pPage, MemPage *pParent);
33013 SQLITE_PRIVATE void sqlite3BtreeParseCellPtr(MemPage*, u8*, CellInfo*);
33014 SQLITE_PRIVATE void sqlite3BtreeParseCell(MemPage*, int, CellInfo*);
33015 SQLITE_PRIVATE int sqlite3BtreeRestoreCursorPosition(BtCursor *pCur);
33016 SQLITE_PRIVATE void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur);
33017 SQLITE_PRIVATE void sqlite3BtreeReleaseTempCursor(BtCursor *pCur);
33018 SQLITE_PRIVATE int sqlite3BtreeIsRootPage(MemPage *pPage);
33019 SQLITE_PRIVATE void sqlite3BtreeMoveToParent(BtCursor *pCur);
33020
33021 /************** End of btreeInt.h ********************************************/
33022 /************** Continuing where we left off in btmutex.c ********************/
33023 #if SQLITE_THREADSAFE && !defined(SQLITE_OMIT_SHARED_CACHE)
33024
33025
33026 /*
33027 ** Enter a mutex on the given BTree object.
33028 **
33029 ** If the object is not sharable, then no mutex is ever required
33030 ** and this routine is a no-op.  The underlying mutex is non-recursive.
33031 ** But we keep a reference count in Btree.wantToLock so the behavior
33032 ** of this interface is recursive.
33033 **
33034 ** To avoid deadlocks, multiple Btrees are locked in the same order
33035 ** by all database connections.  The p->pNext is a list of other
33036 ** Btrees belonging to the same database connection as the p Btree
33037 ** which need to be locked after p.  If we cannot get a lock on
33038 ** p, then first unlock all of the others on p->pNext, then wait
33039 ** for the lock to become available on p, then relock all of the
33040 ** subsequent Btrees that desire a lock.
33041 */
33042 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
33043   Btree *pLater;
33044
33045   /* Some basic sanity checking on the Btree.  The list of Btrees
33046   ** connected by pNext and pPrev should be in sorted order by
33047   ** Btree.pBt value. All elements of the list should belong to
33048   ** the same connection. Only shared Btrees are on the list. */
33049   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
33050   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
33051   assert( p->pNext==0 || p->pNext->db==p->db );
33052   assert( p->pPrev==0 || p->pPrev->db==p->db );
33053   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
33054
33055   /* Check for locking consistency */
33056   assert( !p->locked || p->wantToLock>0 );
33057   assert( p->sharable || p->wantToLock==0 );
33058
33059   /* We should already hold a lock on the database connection */
33060   assert( sqlite3_mutex_held(p->db->mutex) );
33061
33062   if( !p->sharable ) return;
33063   p->wantToLock++;
33064   if( p->locked ) return;
33065
33066 #ifndef SQLITE_MUTEX_NOOP
33067   /* In most cases, we should be able to acquire the lock we
33068   ** want without having to go throught the ascending lock
33069   ** procedure that follows.  Just be sure not to block.
33070   */
33071   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
33072     p->locked = 1;
33073     return;
33074   }
33075
33076   /* To avoid deadlock, first release all locks with a larger
33077   ** BtShared address.  Then acquire our lock.  Then reacquire
33078   ** the other BtShared locks that we used to hold in ascending
33079   ** order.
33080   */
33081   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
33082     assert( pLater->sharable );
33083     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
33084     assert( !pLater->locked || pLater->wantToLock>0 );
33085     if( pLater->locked ){
33086       sqlite3_mutex_leave(pLater->pBt->mutex);
33087       pLater->locked = 0;
33088     }
33089   }
33090   sqlite3_mutex_enter(p->pBt->mutex);
33091   p->locked = 1;
33092   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
33093     if( pLater->wantToLock ){
33094       sqlite3_mutex_enter(pLater->pBt->mutex);
33095       pLater->locked = 1;
33096     }
33097   }
33098 #endif /* SQLITE_MUTEX_NOOP */
33099 }
33100
33101 /*
33102 ** Exit the recursive mutex on a Btree.
33103 */
33104 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
33105   if( p->sharable ){
33106     assert( p->wantToLock>0 );
33107     p->wantToLock--;
33108     if( p->wantToLock==0 ){
33109       assert( p->locked );
33110       sqlite3_mutex_leave(p->pBt->mutex);
33111       p->locked = 0;
33112     }
33113   }
33114 }
33115
33116 #ifndef NDEBUG
33117 /*
33118 ** Return true if the BtShared mutex is held on the btree.  
33119 **
33120 ** This routine makes no determination one why or another if the
33121 ** database connection mutex is held.
33122 **
33123 ** This routine is used only from within assert() statements.
33124 */
33125 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
33126   return (p->sharable==0 ||
33127              (p->locked && p->wantToLock && sqlite3_mutex_held(p->pBt->mutex)));
33128 }
33129 #endif
33130
33131
33132 #ifndef SQLITE_OMIT_INCRBLOB
33133 /*
33134 ** Enter and leave a mutex on a Btree given a cursor owned by that
33135 ** Btree.  These entry points are used by incremental I/O and can be
33136 ** omitted if that module is not used.
33137 */
33138 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
33139   sqlite3BtreeEnter(pCur->pBtree);
33140 }
33141 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
33142   sqlite3BtreeLeave(pCur->pBtree);
33143 }
33144 #endif /* SQLITE_OMIT_INCRBLOB */
33145
33146
33147 /*
33148 ** Enter the mutex on every Btree associated with a database
33149 ** connection.  This is needed (for example) prior to parsing
33150 ** a statement since we will be comparing table and column names
33151 ** against all schemas and we do not want those schemas being
33152 ** reset out from under us.
33153 **
33154 ** There is a corresponding leave-all procedures.
33155 **
33156 ** Enter the mutexes in accending order by BtShared pointer address
33157 ** to avoid the possibility of deadlock when two threads with
33158 ** two or more btrees in common both try to lock all their btrees
33159 ** at the same instant.
33160 */
33161 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
33162   int i;
33163   Btree *p, *pLater;
33164   assert( sqlite3_mutex_held(db->mutex) );
33165   for(i=0; i<db->nDb; i++){
33166     p = db->aDb[i].pBt;
33167     if( p && p->sharable ){
33168       p->wantToLock++;
33169       if( !p->locked ){
33170         assert( p->wantToLock==1 );
33171         while( p->pPrev ) p = p->pPrev;
33172         while( p->locked && p->pNext ) p = p->pNext;
33173         for(pLater = p->pNext; pLater; pLater=pLater->pNext){
33174           if( pLater->locked ){
33175             sqlite3_mutex_leave(pLater->pBt->mutex);
33176             pLater->locked = 0;
33177           }
33178         }
33179         while( p ){
33180           sqlite3_mutex_enter(p->pBt->mutex);
33181           p->locked++;
33182           p = p->pNext;
33183         }
33184       }
33185     }
33186   }
33187 }
33188 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
33189   int i;
33190   Btree *p;
33191   assert( sqlite3_mutex_held(db->mutex) );
33192   for(i=0; i<db->nDb; i++){
33193     p = db->aDb[i].pBt;
33194     if( p && p->sharable ){
33195       assert( p->wantToLock>0 );
33196       p->wantToLock--;
33197       if( p->wantToLock==0 ){
33198         assert( p->locked );
33199         sqlite3_mutex_leave(p->pBt->mutex);
33200         p->locked = 0;
33201       }
33202     }
33203   }
33204 }
33205
33206 #ifndef NDEBUG
33207 /*
33208 ** Return true if the current thread holds the database connection
33209 ** mutex and all required BtShared mutexes.
33210 **
33211 ** This routine is used inside assert() statements only.
33212 */
33213 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
33214   int i;
33215   if( !sqlite3_mutex_held(db->mutex) ){
33216     return 0;
33217   }
33218   for(i=0; i<db->nDb; i++){
33219     Btree *p;
33220     p = db->aDb[i].pBt;
33221     if( p && p->sharable &&
33222          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
33223       return 0;
33224     }
33225   }
33226   return 1;
33227 }
33228 #endif /* NDEBUG */
33229
33230 /*
33231 ** Add a new Btree pointer to a BtreeMutexArray. 
33232 ** if the pointer can possibly be shared with
33233 ** another database connection.
33234 **
33235 ** The pointers are kept in sorted order by pBtree->pBt.  That
33236 ** way when we go to enter all the mutexes, we can enter them
33237 ** in order without every having to backup and retry and without
33238 ** worrying about deadlock.
33239 **
33240 ** The number of shared btrees will always be small (usually 0 or 1)
33241 ** so an insertion sort is an adequate algorithm here.
33242 */
33243 SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray *pArray, Btree *pBtree){
33244   int i, j;
33245   BtShared *pBt;
33246   if( pBtree==0 || pBtree->sharable==0 ) return;
33247 #ifndef NDEBUG
33248   {
33249     for(i=0; i<pArray->nMutex; i++){
33250       assert( pArray->aBtree[i]!=pBtree );
33251     }
33252   }
33253 #endif
33254   assert( pArray->nMutex>=0 );
33255   assert( pArray->nMutex<sizeof(pArray->aBtree)/sizeof(pArray->aBtree[0])-1 );
33256   pBt = pBtree->pBt;
33257   for(i=0; i<pArray->nMutex; i++){
33258     assert( pArray->aBtree[i]!=pBtree );
33259     if( pArray->aBtree[i]->pBt>pBt ){
33260       for(j=pArray->nMutex; j>i; j--){
33261         pArray->aBtree[j] = pArray->aBtree[j-1];
33262       }
33263       pArray->aBtree[i] = pBtree;
33264       pArray->nMutex++;
33265       return;
33266     }
33267   }
33268   pArray->aBtree[pArray->nMutex++] = pBtree;
33269 }
33270
33271 /*
33272 ** Enter the mutex of every btree in the array.  This routine is
33273 ** called at the beginning of sqlite3VdbeExec().  The mutexes are
33274 ** exited at the end of the same function.
33275 */
33276 SQLITE_PRIVATE void sqlite3BtreeMutexArrayEnter(BtreeMutexArray *pArray){
33277   int i;
33278   for(i=0; i<pArray->nMutex; i++){
33279     Btree *p = pArray->aBtree[i];
33280     /* Some basic sanity checking */
33281     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
33282     assert( !p->locked || p->wantToLock>0 );
33283
33284     /* We should already hold a lock on the database connection */
33285     assert( sqlite3_mutex_held(p->db->mutex) );
33286
33287     p->wantToLock++;
33288     if( !p->locked && p->sharable ){
33289       sqlite3_mutex_enter(p->pBt->mutex);
33290       p->locked = 1;
33291     }
33292   }
33293 }
33294
33295 /*
33296 ** Leave the mutex of every btree in the group.
33297 */
33298 SQLITE_PRIVATE void sqlite3BtreeMutexArrayLeave(BtreeMutexArray *pArray){
33299   int i;
33300   for(i=0; i<pArray->nMutex; i++){
33301     Btree *p = pArray->aBtree[i];
33302     /* Some basic sanity checking */
33303     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
33304     assert( p->locked || !p->sharable );
33305     assert( p->wantToLock>0 );
33306
33307     /* We should already hold a lock on the database connection */
33308     assert( sqlite3_mutex_held(p->db->mutex) );
33309
33310     p->wantToLock--;
33311     if( p->wantToLock==0 && p->locked ){
33312       sqlite3_mutex_leave(p->pBt->mutex);
33313       p->locked = 0;
33314     }
33315   }
33316 }
33317
33318
33319 #endif  /* SQLITE_THREADSAFE && !SQLITE_OMIT_SHARED_CACHE */
33320
33321 /************** End of btmutex.c *********************************************/
33322 /************** Begin file btree.c *******************************************/
33323 /*
33324 ** 2004 April 6
33325 **
33326 ** The author disclaims copyright to this source code.  In place of
33327 ** a legal notice, here is a blessing:
33328 **
33329 **    May you do good and not evil.
33330 **    May you find forgiveness for yourself and forgive others.
33331 **    May you share freely, never taking more than you give.
33332 **
33333 *************************************************************************
33334 ** $Id: btree.c,v 1.516 2008/09/19 16:39:38 danielk1977 Exp $
33335 **
33336 ** This file implements a external (disk-based) database using BTrees.
33337 ** See the header comment on "btreeInt.h" for additional information.
33338 ** Including a description of file format and an overview of operation.
33339 */
33340
33341 /*
33342 ** The header string that appears at the beginning of every
33343 ** SQLite database.
33344 */
33345 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
33346
33347 /*
33348 ** Set this global variable to 1 to enable tracing using the TRACE
33349 ** macro.
33350 */
33351 #if 0
33352 int sqlite3BtreeTrace=0;  /* True to enable tracing */
33353 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
33354 #else
33355 # define TRACE(X)
33356 #endif
33357
33358
33359
33360 #ifndef SQLITE_OMIT_SHARED_CACHE
33361 /*
33362 ** A list of BtShared objects that are eligible for participation
33363 ** in shared cache.  This variable has file scope during normal builds,
33364 ** but the test harness needs to access it so we make it global for 
33365 ** test builds.
33366 */
33367 #ifdef SQLITE_TEST
33368 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
33369 #else
33370 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
33371 #endif
33372 #endif /* SQLITE_OMIT_SHARED_CACHE */
33373
33374 #ifndef SQLITE_OMIT_SHARED_CACHE
33375 /*
33376 ** Enable or disable the shared pager and schema features.
33377 **
33378 ** This routine has no effect on existing database connections.
33379 ** The shared cache setting effects only future calls to
33380 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
33381 */
33382 SQLITE_API int sqlite3_enable_shared_cache(int enable){
33383   sqlite3GlobalConfig.sharedCacheEnabled = enable;
33384   return SQLITE_OK;
33385 }
33386 #endif
33387
33388
33389 /*
33390 ** Forward declaration
33391 */
33392 static int checkReadLocks(Btree*, Pgno, BtCursor*, i64);
33393
33394
33395 #ifdef SQLITE_OMIT_SHARED_CACHE
33396   /*
33397   ** The functions queryTableLock(), lockTable() and unlockAllTables()
33398   ** manipulate entries in the BtShared.pLock linked list used to store
33399   ** shared-cache table level locks. If the library is compiled with the
33400   ** shared-cache feature disabled, then there is only ever one user
33401   ** of each BtShared structure and so this locking is not necessary. 
33402   ** So define the lock related functions as no-ops.
33403   */
33404   #define queryTableLock(a,b,c) SQLITE_OK
33405   #define lockTable(a,b,c) SQLITE_OK
33406   #define unlockAllTables(a)
33407 #endif
33408
33409 #ifndef SQLITE_OMIT_SHARED_CACHE
33410 /*
33411 ** Query to see if btree handle p may obtain a lock of type eLock 
33412 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
33413 ** SQLITE_OK if the lock may be obtained (by calling lockTable()), or
33414 ** SQLITE_LOCKED if not.
33415 */
33416 static int queryTableLock(Btree *p, Pgno iTab, u8 eLock){
33417   BtShared *pBt = p->pBt;
33418   BtLock *pIter;
33419
33420   assert( sqlite3BtreeHoldsMutex(p) );
33421   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
33422   assert( p->db!=0 );
33423   
33424   /* This is a no-op if the shared-cache is not enabled */
33425   if( !p->sharable ){
33426     return SQLITE_OK;
33427   }
33428
33429   /* If some other connection is holding an exclusive lock, the
33430   ** requested lock may not be obtained.
33431   */
33432   if( pBt->pExclusive && pBt->pExclusive!=p ){
33433     return SQLITE_LOCKED;
33434   }
33435
33436   /* This (along with lockTable()) is where the ReadUncommitted flag is
33437   ** dealt with. If the caller is querying for a read-lock and the flag is
33438   ** set, it is unconditionally granted - even if there are write-locks
33439   ** on the table. If a write-lock is requested, the ReadUncommitted flag
33440   ** is not considered.
33441   **
33442   ** In function lockTable(), if a read-lock is demanded and the 
33443   ** ReadUncommitted flag is set, no entry is added to the locks list 
33444   ** (BtShared.pLock).
33445   **
33446   ** To summarize: If the ReadUncommitted flag is set, then read cursors do
33447   ** not create or respect table locks. The locking procedure for a 
33448   ** write-cursor does not change.
33449   */
33450   if( 
33451     0==(p->db->flags&SQLITE_ReadUncommitted) || 
33452     eLock==WRITE_LOCK ||
33453     iTab==MASTER_ROOT
33454   ){
33455     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
33456       if( pIter->pBtree!=p && pIter->iTable==iTab && 
33457           (pIter->eLock!=eLock || eLock!=READ_LOCK) ){
33458         return SQLITE_LOCKED;
33459       }
33460     }
33461   }
33462   return SQLITE_OK;
33463 }
33464 #endif /* !SQLITE_OMIT_SHARED_CACHE */
33465
33466 #ifndef SQLITE_OMIT_SHARED_CACHE
33467 /*
33468 ** Add a lock on the table with root-page iTable to the shared-btree used
33469 ** by Btree handle p. Parameter eLock must be either READ_LOCK or 
33470 ** WRITE_LOCK.
33471 **
33472 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_BUSY and
33473 ** SQLITE_NOMEM may also be returned.
33474 */
33475 static int lockTable(Btree *p, Pgno iTable, u8 eLock){
33476   BtShared *pBt = p->pBt;
33477   BtLock *pLock = 0;
33478   BtLock *pIter;
33479
33480   assert( sqlite3BtreeHoldsMutex(p) );
33481   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
33482   assert( p->db!=0 );
33483
33484   /* This is a no-op if the shared-cache is not enabled */
33485   if( !p->sharable ){
33486     return SQLITE_OK;
33487   }
33488
33489   assert( SQLITE_OK==queryTableLock(p, iTable, eLock) );
33490
33491   /* If the read-uncommitted flag is set and a read-lock is requested,
33492   ** return early without adding an entry to the BtShared.pLock list. See
33493   ** comment in function queryTableLock() for more info on handling 
33494   ** the ReadUncommitted flag.
33495   */
33496   if( 
33497     (p->db->flags&SQLITE_ReadUncommitted) && 
33498     (eLock==READ_LOCK) &&
33499     iTable!=MASTER_ROOT
33500   ){
33501     return SQLITE_OK;
33502   }
33503
33504   /* First search the list for an existing lock on this table. */
33505   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
33506     if( pIter->iTable==iTable && pIter->pBtree==p ){
33507       pLock = pIter;
33508       break;
33509     }
33510   }
33511
33512   /* If the above search did not find a BtLock struct associating Btree p
33513   ** with table iTable, allocate one and link it into the list.
33514   */
33515   if( !pLock ){
33516     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
33517     if( !pLock ){
33518       return SQLITE_NOMEM;
33519     }
33520     pLock->iTable = iTable;
33521     pLock->pBtree = p;
33522     pLock->pNext = pBt->pLock;
33523     pBt->pLock = pLock;
33524   }
33525
33526   /* Set the BtLock.eLock variable to the maximum of the current lock
33527   ** and the requested lock. This means if a write-lock was already held
33528   ** and a read-lock requested, we don't incorrectly downgrade the lock.
33529   */
33530   assert( WRITE_LOCK>READ_LOCK );
33531   if( eLock>pLock->eLock ){
33532     pLock->eLock = eLock;
33533   }
33534
33535   return SQLITE_OK;
33536 }
33537 #endif /* !SQLITE_OMIT_SHARED_CACHE */
33538
33539 #ifndef SQLITE_OMIT_SHARED_CACHE
33540 /*
33541 ** Release all the table locks (locks obtained via calls to the lockTable()
33542 ** procedure) held by Btree handle p.
33543 */
33544 static void unlockAllTables(Btree *p){
33545   BtShared *pBt = p->pBt;
33546   BtLock **ppIter = &pBt->pLock;
33547
33548   assert( sqlite3BtreeHoldsMutex(p) );
33549   assert( p->sharable || 0==*ppIter );
33550
33551   while( *ppIter ){
33552     BtLock *pLock = *ppIter;
33553     assert( pBt->pExclusive==0 || pBt->pExclusive==pLock->pBtree );
33554     if( pLock->pBtree==p ){
33555       *ppIter = pLock->pNext;
33556       sqlite3_free(pLock);
33557     }else{
33558       ppIter = &pLock->pNext;
33559     }
33560   }
33561
33562   if( pBt->pExclusive==p ){
33563     pBt->pExclusive = 0;
33564   }
33565 }
33566 #endif /* SQLITE_OMIT_SHARED_CACHE */
33567
33568 static void releasePage(MemPage *pPage);  /* Forward reference */
33569
33570 /*
33571 ** Verify that the cursor holds a mutex on the BtShared
33572 */
33573 #ifndef NDEBUG
33574 static int cursorHoldsMutex(BtCursor *p){
33575   return sqlite3_mutex_held(p->pBt->mutex);
33576 }
33577 #endif
33578
33579
33580 #ifndef SQLITE_OMIT_INCRBLOB
33581 /*
33582 ** Invalidate the overflow page-list cache for cursor pCur, if any.
33583 */
33584 static void invalidateOverflowCache(BtCursor *pCur){
33585   assert( cursorHoldsMutex(pCur) );
33586   sqlite3_free(pCur->aOverflow);
33587   pCur->aOverflow = 0;
33588 }
33589
33590 /*
33591 ** Invalidate the overflow page-list cache for all cursors opened
33592 ** on the shared btree structure pBt.
33593 */
33594 static void invalidateAllOverflowCache(BtShared *pBt){
33595   BtCursor *p;
33596   assert( sqlite3_mutex_held(pBt->mutex) );
33597   for(p=pBt->pCursor; p; p=p->pNext){
33598     invalidateOverflowCache(p);
33599   }
33600 }
33601 #else
33602   #define invalidateOverflowCache(x)
33603   #define invalidateAllOverflowCache(x)
33604 #endif
33605
33606 /*
33607 ** Save the current cursor position in the variables BtCursor.nKey 
33608 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
33609 */
33610 static int saveCursorPosition(BtCursor *pCur){
33611   int rc;
33612
33613   assert( CURSOR_VALID==pCur->eState );
33614   assert( 0==pCur->pKey );
33615   assert( cursorHoldsMutex(pCur) );
33616
33617   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
33618
33619   /* If this is an intKey table, then the above call to BtreeKeySize()
33620   ** stores the integer key in pCur->nKey. In this case this value is
33621   ** all that is required. Otherwise, if pCur is not open on an intKey
33622   ** table, then malloc space for and store the pCur->nKey bytes of key 
33623   ** data.
33624   */
33625   if( rc==SQLITE_OK && 0==pCur->pPage->intKey){
33626     void *pKey = sqlite3Malloc(pCur->nKey);
33627     if( pKey ){
33628       rc = sqlite3BtreeKey(pCur, 0, pCur->nKey, pKey);
33629       if( rc==SQLITE_OK ){
33630         pCur->pKey = pKey;
33631       }else{
33632         sqlite3_free(pKey);
33633       }
33634     }else{
33635       rc = SQLITE_NOMEM;
33636     }
33637   }
33638   assert( !pCur->pPage->intKey || !pCur->pKey );
33639
33640   if( rc==SQLITE_OK ){
33641     releasePage(pCur->pPage);
33642     pCur->pPage = 0;
33643     pCur->eState = CURSOR_REQUIRESEEK;
33644   }
33645
33646   invalidateOverflowCache(pCur);
33647   return rc;
33648 }
33649
33650 /*
33651 ** Save the positions of all cursors except pExcept open on the table 
33652 ** with root-page iRoot. Usually, this is called just before cursor
33653 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
33654 */
33655 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
33656   BtCursor *p;
33657   assert( sqlite3_mutex_held(pBt->mutex) );
33658   assert( pExcept==0 || pExcept->pBt==pBt );
33659   for(p=pBt->pCursor; p; p=p->pNext){
33660     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) && 
33661         p->eState==CURSOR_VALID ){
33662       int rc = saveCursorPosition(p);
33663       if( SQLITE_OK!=rc ){
33664         return rc;
33665       }
33666     }
33667   }
33668   return SQLITE_OK;
33669 }
33670
33671 /*
33672 ** Clear the current cursor position.
33673 */
33674 static void clearCursorPosition(BtCursor *pCur){
33675   assert( cursorHoldsMutex(pCur) );
33676   sqlite3_free(pCur->pKey);
33677   pCur->pKey = 0;
33678   pCur->eState = CURSOR_INVALID;
33679 }
33680
33681 /*
33682 ** Restore the cursor to the position it was in (or as close to as possible)
33683 ** when saveCursorPosition() was called. Note that this call deletes the 
33684 ** saved position info stored by saveCursorPosition(), so there can be
33685 ** at most one effective restoreCursorPosition() call after each 
33686 ** saveCursorPosition().
33687 */
33688 SQLITE_PRIVATE int sqlite3BtreeRestoreCursorPosition(BtCursor *pCur){
33689   int rc;
33690   assert( cursorHoldsMutex(pCur) );
33691   assert( pCur->eState>=CURSOR_REQUIRESEEK );
33692   if( pCur->eState==CURSOR_FAULT ){
33693     return pCur->skip;
33694   }
33695   pCur->eState = CURSOR_INVALID;
33696   rc = sqlite3BtreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skip);
33697   if( rc==SQLITE_OK ){
33698     sqlite3_free(pCur->pKey);
33699     pCur->pKey = 0;
33700     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
33701   }
33702   return rc;
33703 }
33704
33705 #define restoreCursorPosition(p) \
33706   (p->eState>=CURSOR_REQUIRESEEK ? \
33707          sqlite3BtreeRestoreCursorPosition(p) : \
33708          SQLITE_OK)
33709
33710 /*
33711 ** Determine whether or not a cursor has moved from the position it
33712 ** was last placed at.  Cursor can move when the row they are pointing
33713 ** at is deleted out from under them.
33714 **
33715 ** This routine returns an error code if something goes wrong.  The
33716 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
33717 */
33718 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
33719   int rc;
33720
33721   rc = restoreCursorPosition(pCur);
33722   if( rc ){
33723     *pHasMoved = 1;
33724     return rc;
33725   }
33726   if( pCur->eState!=CURSOR_VALID || pCur->skip!=0 ){
33727     *pHasMoved = 1;
33728   }else{
33729     *pHasMoved = 0;
33730   }
33731   return SQLITE_OK;
33732 }
33733
33734 #ifndef SQLITE_OMIT_AUTOVACUUM
33735 /*
33736 ** Given a page number of a regular database page, return the page
33737 ** number for the pointer-map page that contains the entry for the
33738 ** input page number.
33739 */
33740 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
33741   int nPagesPerMapPage, iPtrMap, ret;
33742   assert( sqlite3_mutex_held(pBt->mutex) );
33743   nPagesPerMapPage = (pBt->usableSize/5)+1;
33744   iPtrMap = (pgno-2)/nPagesPerMapPage;
33745   ret = (iPtrMap*nPagesPerMapPage) + 2; 
33746   if( ret==PENDING_BYTE_PAGE(pBt) ){
33747     ret++;
33748   }
33749   return ret;
33750 }
33751
33752 /*
33753 ** Write an entry into the pointer map.
33754 **
33755 ** This routine updates the pointer map entry for page number 'key'
33756 ** so that it maps to type 'eType' and parent page number 'pgno'.
33757 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
33758 */
33759 static int ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent){
33760   DbPage *pDbPage;  /* The pointer map page */
33761   u8 *pPtrmap;      /* The pointer map data */
33762   Pgno iPtrmap;     /* The pointer map page number */
33763   int offset;       /* Offset in pointer map page */
33764   int rc;
33765
33766   assert( sqlite3_mutex_held(pBt->mutex) );
33767   /* The master-journal page number must never be used as a pointer map page */
33768   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
33769
33770   assert( pBt->autoVacuum );
33771   if( key==0 ){
33772     return SQLITE_CORRUPT_BKPT;
33773   }
33774   iPtrmap = PTRMAP_PAGENO(pBt, key);
33775   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
33776   if( rc!=SQLITE_OK ){
33777     return rc;
33778   }
33779   offset = PTRMAP_PTROFFSET(iPtrmap, key);
33780   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
33781
33782   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
33783     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
33784     rc = sqlite3PagerWrite(pDbPage);
33785     if( rc==SQLITE_OK ){
33786       pPtrmap[offset] = eType;
33787       put4byte(&pPtrmap[offset+1], parent);
33788     }
33789   }
33790
33791   sqlite3PagerUnref(pDbPage);
33792   return rc;
33793 }
33794
33795 /*
33796 ** Read an entry from the pointer map.
33797 **
33798 ** This routine retrieves the pointer map entry for page 'key', writing
33799 ** the type and parent page number to *pEType and *pPgno respectively.
33800 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
33801 */
33802 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
33803   DbPage *pDbPage;   /* The pointer map page */
33804   int iPtrmap;       /* Pointer map page index */
33805   u8 *pPtrmap;       /* Pointer map page data */
33806   int offset;        /* Offset of entry in pointer map */
33807   int rc;
33808
33809   assert( sqlite3_mutex_held(pBt->mutex) );
33810
33811   iPtrmap = PTRMAP_PAGENO(pBt, key);
33812   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
33813   if( rc!=0 ){
33814     return rc;
33815   }
33816   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
33817
33818   offset = PTRMAP_PTROFFSET(iPtrmap, key);
33819   assert( pEType!=0 );
33820   *pEType = pPtrmap[offset];
33821   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
33822
33823   sqlite3PagerUnref(pDbPage);
33824   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
33825   return SQLITE_OK;
33826 }
33827
33828 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
33829   #define ptrmapPut(w,x,y,z) SQLITE_OK
33830   #define ptrmapGet(w,x,y,z) SQLITE_OK
33831   #define ptrmapPutOvfl(y,z) SQLITE_OK
33832 #endif
33833
33834 /*
33835 ** Given a btree page and a cell index (0 means the first cell on
33836 ** the page, 1 means the second cell, and so forth) return a pointer
33837 ** to the cell content.
33838 **
33839 ** This routine works only for pages that do not contain overflow cells.
33840 */
33841 #define findCell(P,I) \
33842   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
33843
33844 /*
33845 ** This a more complex version of findCell() that works for
33846 ** pages that do contain overflow cells.  See insert
33847 */
33848 static u8 *findOverflowCell(MemPage *pPage, int iCell){
33849   int i;
33850   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
33851   for(i=pPage->nOverflow-1; i>=0; i--){
33852     int k;
33853     struct _OvflCell *pOvfl;
33854     pOvfl = &pPage->aOvfl[i];
33855     k = pOvfl->idx;
33856     if( k<=iCell ){
33857       if( k==iCell ){
33858         return pOvfl->pCell;
33859       }
33860       iCell--;
33861     }
33862   }
33863   return findCell(pPage, iCell);
33864 }
33865
33866 /*
33867 ** Parse a cell content block and fill in the CellInfo structure.  There
33868 ** are two versions of this function.  sqlite3BtreeParseCell() takes a 
33869 ** cell index as the second argument and sqlite3BtreeParseCellPtr() 
33870 ** takes a pointer to the body of the cell as its second argument.
33871 **
33872 ** Within this file, the parseCell() macro can be called instead of
33873 ** sqlite3BtreeParseCellPtr(). Using some compilers, this will be faster.
33874 */
33875 SQLITE_PRIVATE void sqlite3BtreeParseCellPtr(
33876   MemPage *pPage,         /* Page containing the cell */
33877   u8 *pCell,              /* Pointer to the cell text. */
33878   CellInfo *pInfo         /* Fill in this structure */
33879 ){
33880   int n;                  /* Number bytes in cell content header */
33881   u32 nPayload;           /* Number of bytes of cell payload */
33882
33883   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
33884
33885   pInfo->pCell = pCell;
33886   assert( pPage->leaf==0 || pPage->leaf==1 );
33887   n = pPage->childPtrSize;
33888   assert( n==4-4*pPage->leaf );
33889   if( pPage->intKey ){
33890     if( pPage->hasData ){
33891       n += getVarint32(&pCell[n], nPayload);
33892     }else{
33893       nPayload = 0;
33894     }
33895     n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
33896     pInfo->nData = nPayload;
33897   }else{
33898     pInfo->nData = 0;
33899     n += getVarint32(&pCell[n], nPayload);
33900     pInfo->nKey = nPayload;
33901   }
33902   pInfo->nPayload = nPayload;
33903   pInfo->nHeader = n;
33904   if( likely(nPayload<=pPage->maxLocal) ){
33905     /* This is the (easy) common case where the entire payload fits
33906     ** on the local page.  No overflow is required.
33907     */
33908     int nSize;          /* Total size of cell content in bytes */
33909     nSize = nPayload + n;
33910     pInfo->nLocal = nPayload;
33911     pInfo->iOverflow = 0;
33912     if( (nSize & ~3)==0 ){
33913       nSize = 4;        /* Minimum cell size is 4 */
33914     }
33915     pInfo->nSize = nSize;
33916   }else{
33917     /* If the payload will not fit completely on the local page, we have
33918     ** to decide how much to store locally and how much to spill onto
33919     ** overflow pages.  The strategy is to minimize the amount of unused
33920     ** space on overflow pages while keeping the amount of local storage
33921     ** in between minLocal and maxLocal.
33922     **
33923     ** Warning:  changing the way overflow payload is distributed in any
33924     ** way will result in an incompatible file format.
33925     */
33926     int minLocal;  /* Minimum amount of payload held locally */
33927     int maxLocal;  /* Maximum amount of payload held locally */
33928     int surplus;   /* Overflow payload available for local storage */
33929
33930     minLocal = pPage->minLocal;
33931     maxLocal = pPage->maxLocal;
33932     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
33933     if( surplus <= maxLocal ){
33934       pInfo->nLocal = surplus;
33935     }else{
33936       pInfo->nLocal = minLocal;
33937     }
33938     pInfo->iOverflow = pInfo->nLocal + n;
33939     pInfo->nSize = pInfo->iOverflow + 4;
33940   }
33941 }
33942 #define parseCell(pPage, iCell, pInfo) \
33943   sqlite3BtreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
33944 SQLITE_PRIVATE void sqlite3BtreeParseCell(
33945   MemPage *pPage,         /* Page containing the cell */
33946   int iCell,              /* The cell index.  First cell is 0 */
33947   CellInfo *pInfo         /* Fill in this structure */
33948 ){
33949   parseCell(pPage, iCell, pInfo);
33950 }
33951
33952 /*
33953 ** Compute the total number of bytes that a Cell needs in the cell
33954 ** data area of the btree-page.  The return number includes the cell
33955 ** data header and the local payload, but not any overflow page or
33956 ** the space used by the cell pointer.
33957 */
33958 #ifndef NDEBUG
33959 static u16 cellSize(MemPage *pPage, int iCell){
33960   CellInfo info;
33961   sqlite3BtreeParseCell(pPage, iCell, &info);
33962   return info.nSize;
33963 }
33964 #endif
33965 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
33966   CellInfo info;
33967   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
33968   return info.nSize;
33969 }
33970
33971 #ifndef SQLITE_OMIT_AUTOVACUUM
33972 /*
33973 ** If the cell pCell, part of page pPage contains a pointer
33974 ** to an overflow page, insert an entry into the pointer-map
33975 ** for the overflow page.
33976 */
33977 static int ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell){
33978   CellInfo info;
33979   assert( pCell!=0 );
33980   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
33981   assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
33982   if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
33983     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
33984     return ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno);
33985   }
33986   return SQLITE_OK;
33987 }
33988 /*
33989 ** If the cell with index iCell on page pPage contains a pointer
33990 ** to an overflow page, insert an entry into the pointer-map
33991 ** for the overflow page.
33992 */
33993 static int ptrmapPutOvfl(MemPage *pPage, int iCell){
33994   u8 *pCell;
33995   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
33996   pCell = findOverflowCell(pPage, iCell);
33997   return ptrmapPutOvflPtr(pPage, pCell);
33998 }
33999 #endif
34000
34001
34002 /*
34003 ** Defragment the page given.  All Cells are moved to the
34004 ** end of the page and all free space is collected into one
34005 ** big FreeBlk that occurs in between the header and cell
34006 ** pointer array and the cell content area.
34007 */
34008 static void defragmentPage(MemPage *pPage){
34009   int i;                     /* Loop counter */
34010   int pc;                    /* Address of a i-th cell */
34011   int addr;                  /* Offset of first byte after cell pointer array */
34012   int hdr;                   /* Offset to the page header */
34013   int size;                  /* Size of a cell */
34014   int usableSize;            /* Number of usable bytes on a page */
34015   int cellOffset;            /* Offset to the cell pointer array */
34016   int cbrk;                  /* Offset to the cell content area */
34017   int nCell;                 /* Number of cells on the page */
34018   unsigned char *data;       /* The page data */
34019   unsigned char *temp;       /* Temp area for cell content */
34020
34021   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
34022   assert( pPage->pBt!=0 );
34023   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
34024   assert( pPage->nOverflow==0 );
34025   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34026   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
34027   data = pPage->aData;
34028   hdr = pPage->hdrOffset;
34029   cellOffset = pPage->cellOffset;
34030   nCell = pPage->nCell;
34031   assert( nCell==get2byte(&data[hdr+3]) );
34032   usableSize = pPage->pBt->usableSize;
34033   cbrk = get2byte(&data[hdr+5]);
34034   memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
34035   cbrk = usableSize;
34036   for(i=0; i<nCell; i++){
34037     u8 *pAddr;     /* The i-th cell pointer */
34038     pAddr = &data[cellOffset + i*2];
34039     pc = get2byte(pAddr);
34040     assert( pc<pPage->pBt->usableSize );
34041     size = cellSizePtr(pPage, &temp[pc]);
34042     cbrk -= size;
34043     memcpy(&data[cbrk], &temp[pc], size);
34044     put2byte(pAddr, cbrk);
34045   }
34046   assert( cbrk>=cellOffset+2*nCell );
34047   put2byte(&data[hdr+5], cbrk);
34048   data[hdr+1] = 0;
34049   data[hdr+2] = 0;
34050   data[hdr+7] = 0;
34051   addr = cellOffset+2*nCell;
34052   memset(&data[addr], 0, cbrk-addr);
34053 }
34054
34055 /*
34056 ** Allocate nByte bytes of space on a page.
34057 **
34058 ** Return the index into pPage->aData[] of the first byte of
34059 ** the new allocation.  The caller guarantees that there is enough
34060 ** space.  This routine will never fail.
34061 **
34062 ** If the page contains nBytes of free space but does not contain
34063 ** nBytes of contiguous free space, then this routine automatically
34064 ** calls defragementPage() to consolidate all free space before 
34065 ** allocating the new chunk.
34066 */
34067 static int allocateSpace(MemPage *pPage, int nByte){
34068   int addr, pc, hdr;
34069   int size;
34070   int nFrag;
34071   int top;
34072   int nCell;
34073   int cellOffset;
34074   unsigned char *data;
34075   
34076   data = pPage->aData;
34077   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
34078   assert( pPage->pBt );
34079   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34080   assert( nByte>=0 );  /* Minimum cell size is 4 */
34081   assert( pPage->nFree>=nByte );
34082   assert( pPage->nOverflow==0 );
34083   pPage->nFree -= nByte;
34084   hdr = pPage->hdrOffset;
34085
34086   nFrag = data[hdr+7];
34087   if( nFrag<60 ){
34088     /* Search the freelist looking for a slot big enough to satisfy the
34089     ** space request. */
34090     addr = hdr+1;
34091     while( (pc = get2byte(&data[addr]))>0 ){
34092       size = get2byte(&data[pc+2]);
34093       if( size>=nByte ){
34094         if( size<nByte+4 ){
34095           memcpy(&data[addr], &data[pc], 2);
34096           data[hdr+7] = nFrag + size - nByte;
34097           return pc;
34098         }else{
34099           put2byte(&data[pc+2], size-nByte);
34100           return pc + size - nByte;
34101         }
34102       }
34103       addr = pc;
34104     }
34105   }
34106
34107   /* Allocate memory from the gap in between the cell pointer array
34108   ** and the cell content area.
34109   */
34110   top = get2byte(&data[hdr+5]);
34111   nCell = get2byte(&data[hdr+3]);
34112   cellOffset = pPage->cellOffset;
34113   if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
34114     defragmentPage(pPage);
34115     top = get2byte(&data[hdr+5]);
34116   }
34117   top -= nByte;
34118   assert( cellOffset + 2*nCell <= top );
34119   put2byte(&data[hdr+5], top);
34120   return top;
34121 }
34122
34123 /*
34124 ** Return a section of the pPage->aData to the freelist.
34125 ** The first byte of the new free block is pPage->aDisk[start]
34126 ** and the size of the block is "size" bytes.
34127 **
34128 ** Most of the effort here is involved in coalesing adjacent
34129 ** free blocks into a single big free block.
34130 */
34131 static void freeSpace(MemPage *pPage, int start, int size){
34132   int addr, pbegin, hdr;
34133   unsigned char *data = pPage->aData;
34134
34135   assert( pPage->pBt!=0 );
34136   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
34137   assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
34138   assert( (start + size)<=pPage->pBt->usableSize );
34139   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34140   assert( size>=0 );   /* Minimum cell size is 4 */
34141
34142 #ifdef SQLITE_SECURE_DELETE
34143   /* Overwrite deleted information with zeros when the SECURE_DELETE 
34144   ** option is enabled at compile-time */
34145   memset(&data[start], 0, size);
34146 #endif
34147
34148   /* Add the space back into the linked list of freeblocks */
34149   hdr = pPage->hdrOffset;
34150   addr = hdr + 1;
34151   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
34152     assert( pbegin<=pPage->pBt->usableSize-4 );
34153     assert( pbegin>addr );
34154     addr = pbegin;
34155   }
34156   assert( pbegin<=pPage->pBt->usableSize-4 );
34157   assert( pbegin>addr || pbegin==0 );
34158   put2byte(&data[addr], start);
34159   put2byte(&data[start], pbegin);
34160   put2byte(&data[start+2], size);
34161   pPage->nFree += size;
34162
34163   /* Coalesce adjacent free blocks */
34164   addr = pPage->hdrOffset + 1;
34165   while( (pbegin = get2byte(&data[addr]))>0 ){
34166     int pnext, psize;
34167     assert( pbegin>addr );
34168     assert( pbegin<=pPage->pBt->usableSize-4 );
34169     pnext = get2byte(&data[pbegin]);
34170     psize = get2byte(&data[pbegin+2]);
34171     if( pbegin + psize + 3 >= pnext && pnext>0 ){
34172       int frag = pnext - (pbegin+psize);
34173       assert( frag<=data[pPage->hdrOffset+7] );
34174       data[pPage->hdrOffset+7] -= frag;
34175       put2byte(&data[pbegin], get2byte(&data[pnext]));
34176       put2byte(&data[pbegin+2], pnext+get2byte(&data[pnext+2])-pbegin);
34177     }else{
34178       addr = pbegin;
34179     }
34180   }
34181
34182   /* If the cell content area begins with a freeblock, remove it. */
34183   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
34184     int top;
34185     pbegin = get2byte(&data[hdr+1]);
34186     memcpy(&data[hdr+1], &data[pbegin], 2);
34187     top = get2byte(&data[hdr+5]);
34188     put2byte(&data[hdr+5], top + get2byte(&data[pbegin+2]));
34189   }
34190 }
34191
34192 /*
34193 ** Decode the flags byte (the first byte of the header) for a page
34194 ** and initialize fields of the MemPage structure accordingly.
34195 **
34196 ** Only the following combinations are supported.  Anything different
34197 ** indicates a corrupt database files:
34198 **
34199 **         PTF_ZERODATA
34200 **         PTF_ZERODATA | PTF_LEAF
34201 **         PTF_LEAFDATA | PTF_INTKEY
34202 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
34203 */
34204 static int decodeFlags(MemPage *pPage, int flagByte){
34205   BtShared *pBt;     /* A copy of pPage->pBt */
34206
34207   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
34208   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34209   pPage->leaf = flagByte>>3;  assert( PTF_LEAF == 1<<3 );
34210   flagByte &= ~PTF_LEAF;
34211   pPage->childPtrSize = 4-4*pPage->leaf;
34212   pBt = pPage->pBt;
34213   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
34214     pPage->intKey = 1;
34215     pPage->hasData = pPage->leaf;
34216     pPage->maxLocal = pBt->maxLeaf;
34217     pPage->minLocal = pBt->minLeaf;
34218   }else if( flagByte==PTF_ZERODATA ){
34219     pPage->intKey = 0;
34220     pPage->hasData = 0;
34221     pPage->maxLocal = pBt->maxLocal;
34222     pPage->minLocal = pBt->minLocal;
34223   }else{
34224     return SQLITE_CORRUPT_BKPT;
34225   }
34226   return SQLITE_OK;
34227 }
34228
34229 /*
34230 ** Initialize the auxiliary information for a disk block.
34231 **
34232 ** The pParent parameter must be a pointer to the MemPage which
34233 ** is the parent of the page being initialized.  The root of a
34234 ** BTree has no parent and so for that page, pParent==NULL.
34235 **
34236 ** Return SQLITE_OK on success.  If we see that the page does
34237 ** not contain a well-formed database page, then return 
34238 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
34239 ** guarantee that the page is well-formed.  It only shows that
34240 ** we failed to detect any corruption.
34241 */
34242 SQLITE_PRIVATE int sqlite3BtreeInitPage(
34243   MemPage *pPage,        /* The page to be initialized */
34244   MemPage *pParent       /* The parent.  Might be NULL */
34245 ){
34246   int pc;            /* Address of a freeblock within pPage->aData[] */
34247   int hdr;           /* Offset to beginning of page header */
34248   u8 *data;          /* Equal to pPage->aData */
34249   BtShared *pBt;        /* The main btree structure */
34250   int usableSize;    /* Amount of usable space on each page */
34251   int cellOffset;    /* Offset from start of page to first cell pointer */
34252   int nFree;         /* Number of unused bytes on the page */
34253   int top;           /* First byte of the cell content area */
34254
34255   pBt = pPage->pBt;
34256   assert( pBt!=0 );
34257   assert( pParent==0 || pParent->pBt==pBt );
34258   assert( sqlite3_mutex_held(pBt->mutex) );
34259   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
34260   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
34261   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
34262   if( pPage==pParent ){
34263     return SQLITE_CORRUPT_BKPT;
34264   }
34265   if( (pPage->pParent!=pParent)
34266    && (pPage->pParent!=0 || pPage->isInit==PAGE_ISINIT_FULL) ){
34267     /* The parent page should never change unless the file is corrupt */
34268     return SQLITE_CORRUPT_BKPT;
34269   }
34270   if( pPage->isInit==PAGE_ISINIT_FULL ) return SQLITE_OK;
34271   if( pParent!=0 ){
34272     pPage->pParent = pParent;
34273     sqlite3PagerRef(pParent->pDbPage);
34274   }
34275   if( pPage->isInit==PAGE_ISINIT_NONE ){
34276     hdr = pPage->hdrOffset;
34277     data = pPage->aData;
34278     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
34279     assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
34280     pPage->maskPage = pBt->pageSize - 1;
34281     pPage->nOverflow = 0;
34282     pPage->idxShift = 0;
34283     usableSize = pBt->usableSize;
34284     pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
34285     top = get2byte(&data[hdr+5]);
34286     pPage->nCell = get2byte(&data[hdr+3]);
34287     if( pPage->nCell>MX_CELL(pBt) ){
34288       /* To many cells for a single page.  The page must be corrupt */
34289       return SQLITE_CORRUPT_BKPT;
34290     }
34291     if( pPage->nCell==0 && pParent!=0 && pParent->pgno!=1 ){
34292       /* All pages must have at least one cell, except for root pages */
34293       return SQLITE_CORRUPT_BKPT;
34294     }
34295   
34296     /* Compute the total free space on the page */
34297     pc = get2byte(&data[hdr+1]);
34298     nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
34299     while( pc>0 ){
34300       int next, size;
34301       if( pc>usableSize-4 ){
34302         /* Free block is off the page */
34303         return SQLITE_CORRUPT_BKPT; 
34304       }
34305       next = get2byte(&data[pc]);
34306       size = get2byte(&data[pc+2]);
34307       if( next>0 && next<=pc+size+3 ){
34308         /* Free blocks must be in accending order */
34309         return SQLITE_CORRUPT_BKPT; 
34310       }
34311       nFree += size;
34312       pc = next;
34313     }
34314     pPage->nFree = nFree;
34315     if( nFree>=usableSize ){
34316       /* Free space cannot exceed total page size */
34317       return SQLITE_CORRUPT_BKPT; 
34318     }
34319   }
34320
34321 #if 0
34322   /* Check that all the offsets in the cell offset array are within range. 
34323   ** 
34324   ** Omitting this consistency check and using the pPage->maskPage mask
34325   ** to prevent overrunning the page buffer in findCell() results in a
34326   ** 2.5% performance gain.
34327   */
34328   {
34329     u8 *pOff;        /* Iterator used to check all cell offsets are in range */
34330     u8 *pEnd;        /* Pointer to end of cell offset array */
34331     u8 mask;         /* Mask of bits that must be zero in MSB of cell offsets */
34332     mask = ~(((u8)(pBt->pageSize>>8))-1);
34333     pEnd = &data[cellOffset + pPage->nCell*2];
34334     for(pOff=&data[cellOffset]; pOff!=pEnd && !((*pOff)&mask); pOff+=2);
34335     if( pOff!=pEnd ){
34336       return SQLITE_CORRUPT_BKPT;
34337     }
34338   }
34339 #endif
34340
34341   pPage->isInit = PAGE_ISINIT_FULL;
34342   return SQLITE_OK;
34343 }
34344
34345 /*
34346 ** Set up a raw page so that it looks like a database page holding
34347 ** no entries.
34348 */
34349 static void zeroPage(MemPage *pPage, int flags){
34350   unsigned char *data = pPage->aData;
34351   BtShared *pBt = pPage->pBt;
34352   int hdr = pPage->hdrOffset;
34353   int first;
34354
34355   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
34356   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
34357   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
34358   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
34359   assert( sqlite3_mutex_held(pBt->mutex) );
34360   /*memset(&data[hdr], 0, pBt->usableSize - hdr);*/
34361   data[hdr] = flags;
34362   first = hdr + 8 + 4*((flags&PTF_LEAF)==0);
34363   memset(&data[hdr+1], 0, 4);
34364   data[hdr+7] = 0;
34365   put2byte(&data[hdr+5], pBt->usableSize);
34366   pPage->nFree = pBt->usableSize - first;
34367   decodeFlags(pPage, flags);
34368   pPage->hdrOffset = hdr;
34369   pPage->cellOffset = first;
34370   pPage->nOverflow = 0;
34371   assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
34372   pPage->maskPage = pBt->pageSize - 1;
34373   pPage->idxShift = 0;
34374   pPage->nCell = 0;
34375   pPage->isInit = PAGE_ISINIT_FULL;
34376 }
34377
34378
34379 /*
34380 ** Convert a DbPage obtained from the pager into a MemPage used by
34381 ** the btree layer.
34382 */
34383 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
34384   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
34385   pPage->aData = sqlite3PagerGetData(pDbPage);
34386   pPage->pDbPage = pDbPage;
34387   pPage->pBt = pBt;
34388   pPage->pgno = pgno;
34389   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
34390   return pPage; 
34391 }
34392
34393 /*
34394 ** Get a page from the pager.  Initialize the MemPage.pBt and
34395 ** MemPage.aData elements if needed.
34396 **
34397 ** If the noContent flag is set, it means that we do not care about
34398 ** the content of the page at this time.  So do not go to the disk
34399 ** to fetch the content.  Just fill in the content with zeros for now.
34400 ** If in the future we call sqlite3PagerWrite() on this page, that
34401 ** means we have started to be concerned about content and the disk
34402 ** read should occur at that point.
34403 */
34404 SQLITE_PRIVATE int sqlite3BtreeGetPage(
34405   BtShared *pBt,       /* The btree */
34406   Pgno pgno,           /* Number of the page to fetch */
34407   MemPage **ppPage,    /* Return the page in this parameter */
34408   int noContent        /* Do not load page content if true */
34409 ){
34410   int rc;
34411   DbPage *pDbPage;
34412
34413   assert( sqlite3_mutex_held(pBt->mutex) );
34414   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
34415   if( rc ) return rc;
34416   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
34417   return SQLITE_OK;
34418 }
34419
34420 /*
34421 ** Return the size of the database file in pages.  Or return -1 if
34422 ** there is any kind of error.
34423 */
34424 static int pagerPagecount(Pager *pPager){
34425   int rc;
34426   int nPage;
34427   rc = sqlite3PagerPagecount(pPager, &nPage);
34428   return (rc==SQLITE_OK?nPage:-1);
34429 }
34430
34431 /*
34432 ** Get a page from the pager and initialize it.  This routine
34433 ** is just a convenience wrapper around separate calls to
34434 ** sqlite3BtreeGetPage() and sqlite3BtreeInitPage().
34435 */
34436 static int getAndInitPage(
34437   BtShared *pBt,          /* The database file */
34438   Pgno pgno,           /* Number of the page to get */
34439   MemPage **ppPage,    /* Write the page pointer here */
34440   MemPage *pParent     /* Parent of the page */
34441 ){
34442   int rc;
34443   DbPage *pDbPage;
34444   MemPage *pPage;
34445
34446   assert( sqlite3_mutex_held(pBt->mutex) );
34447   assert( !pParent || pParent->isInit==PAGE_ISINIT_FULL );
34448   if( pgno==0 ){
34449     return SQLITE_CORRUPT_BKPT; 
34450   }
34451
34452   /* It is often the case that the page we want is already in cache.
34453   ** If so, get it directly.  This saves us from having to call
34454   ** pagerPagecount() to make sure pgno is within limits, which results
34455   ** in a measureable performance improvements.
34456   */
34457   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
34458   if( pDbPage ){
34459     /* Page is already in cache */
34460     *ppPage = pPage = btreePageFromDbPage(pDbPage, pgno, pBt);
34461     rc = SQLITE_OK;
34462   }else{
34463     /* Page not in cache.  Acquire it. */
34464     if( pgno>pagerPagecount(pBt->pPager) ){
34465       return SQLITE_CORRUPT_BKPT; 
34466     }
34467     rc = sqlite3BtreeGetPage(pBt, pgno, ppPage, 0);
34468     if( rc ) return rc;
34469     pPage = *ppPage;
34470   }
34471   if( pPage->isInit!=PAGE_ISINIT_FULL ){
34472     rc = sqlite3BtreeInitPage(pPage, pParent);
34473   }else if( pParent && (pPage==pParent || pPage->pParent!=pParent) ){
34474     /* This condition indicates a loop in the b-tree structure (the scenario
34475     ** where database corruption has caused a page to be a direct or
34476     ** indirect descendant of itself).
34477     */ 
34478     rc = SQLITE_CORRUPT_BKPT;
34479   }
34480   if( rc!=SQLITE_OK ){
34481     releasePage(pPage);
34482     *ppPage = 0;
34483   }
34484   return rc;
34485 }
34486
34487 /*
34488 ** Release a MemPage.  This should be called once for each prior
34489 ** call to sqlite3BtreeGetPage.
34490 */
34491 static void releasePage(MemPage *pPage){
34492   if( pPage ){
34493     assert( pPage->aData );
34494     assert( pPage->pBt );
34495     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
34496     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
34497     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34498     sqlite3PagerUnref(pPage->pDbPage);
34499   }
34500 }
34501
34502 /*
34503 ** This routine is called when the reference count for a page
34504 ** reaches zero.  We need to unref the pParent pointer when that
34505 ** happens.
34506 */
34507 static void pageDestructor(DbPage *pData){
34508   MemPage *pPage;
34509   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
34510   if( pPage ){
34511     assert( pPage->isInit!=PAGE_ISINIT_FULL 
34512          || sqlite3_mutex_held(pPage->pBt->mutex) 
34513     );
34514     if( pPage->pParent ){
34515       MemPage *pParent = pPage->pParent;
34516       assert( pParent->pBt==pPage->pBt );
34517       pPage->pParent = 0;
34518       releasePage(pParent);
34519     }
34520     if( pPage->isInit==PAGE_ISINIT_FULL ){
34521       pPage->isInit = PAGE_ISINIT_DATA;
34522     }
34523   }
34524 }
34525
34526 /*
34527 ** During a rollback, when the pager reloads information into the cache
34528 ** so that the cache is restored to its original state at the start of
34529 ** the transaction, for each page restored this routine is called.
34530 **
34531 ** This routine needs to reset the extra data section at the end of the
34532 ** page to agree with the restored data.
34533 */
34534 static void pageReinit(DbPage *pData){
34535   MemPage *pPage;
34536   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
34537   if( pPage->isInit==PAGE_ISINIT_FULL ){
34538     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34539     pPage->isInit = 0;
34540     sqlite3BtreeInitPage(pPage, pPage->pParent);
34541   }else if( pPage->isInit==PAGE_ISINIT_DATA ){
34542     pPage->isInit = 0;
34543   }
34544 }
34545
34546 /*
34547 ** Invoke the busy handler for a btree.
34548 */
34549 static int sqlite3BtreeInvokeBusyHandler(void *pArg, int n){
34550   BtShared *pBt = (BtShared*)pArg;
34551   assert( pBt->db );
34552   assert( sqlite3_mutex_held(pBt->db->mutex) );
34553   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
34554 }
34555
34556 /*
34557 ** Open a database file.
34558 ** 
34559 ** zFilename is the name of the database file.  If zFilename is NULL
34560 ** a new database with a random name is created.  This randomly named
34561 ** database file will be deleted when sqlite3BtreeClose() is called.
34562 ** If zFilename is ":memory:" then an in-memory database is created
34563 ** that is automatically destroyed when it is closed.
34564 */
34565 SQLITE_PRIVATE int sqlite3BtreeOpen(
34566   const char *zFilename,  /* Name of the file containing the BTree database */
34567   sqlite3 *db,            /* Associated database handle */
34568   Btree **ppBtree,        /* Pointer to new Btree object written here */
34569   int flags,              /* Options */
34570   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
34571 ){
34572   sqlite3_vfs *pVfs;      /* The VFS to use for this btree */
34573   BtShared *pBt = 0;      /* Shared part of btree structure */
34574   Btree *p;               /* Handle to return */
34575   int rc = SQLITE_OK;
34576   int nReserve;
34577   unsigned char zDbHeader[100];
34578
34579   /* Set the variable isMemdb to true for an in-memory database, or 
34580   ** false for a file-based database. This symbol is only required if
34581   ** either of the shared-data or autovacuum features are compiled 
34582   ** into the library.
34583   */
34584 #if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
34585   #ifdef SQLITE_OMIT_MEMORYDB
34586     const int isMemdb = 0;
34587   #else
34588     const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
34589   #endif
34590 #endif
34591
34592   assert( db!=0 );
34593   assert( sqlite3_mutex_held(db->mutex) );
34594
34595   pVfs = db->pVfs;
34596   p = sqlite3MallocZero(sizeof(Btree));
34597   if( !p ){
34598     return SQLITE_NOMEM;
34599   }
34600   p->inTrans = TRANS_NONE;
34601   p->db = db;
34602
34603 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
34604   /*
34605   ** If this Btree is a candidate for shared cache, try to find an
34606   ** existing BtShared object that we can share with
34607   */
34608   if( isMemdb==0
34609    && (db->flags & SQLITE_Vtab)==0
34610    && zFilename && zFilename[0]
34611   ){
34612     if( sqlite3GlobalConfig.sharedCacheEnabled ){
34613       int nFullPathname = pVfs->mxPathname+1;
34614       char *zFullPathname = sqlite3Malloc(nFullPathname);
34615       sqlite3_mutex *mutexShared;
34616       p->sharable = 1;
34617       db->flags |= SQLITE_SharedCache;
34618       if( !zFullPathname ){
34619         sqlite3_free(p);
34620         return SQLITE_NOMEM;
34621       }
34622       sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
34623       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
34624       sqlite3_mutex_enter(mutexShared);
34625       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
34626         assert( pBt->nRef>0 );
34627         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
34628                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
34629           p->pBt = pBt;
34630           pBt->nRef++;
34631           break;
34632         }
34633       }
34634       sqlite3_mutex_leave(mutexShared);
34635       sqlite3_free(zFullPathname);
34636     }
34637 #ifdef SQLITE_DEBUG
34638     else{
34639       /* In debug mode, we mark all persistent databases as sharable
34640       ** even when they are not.  This exercises the locking code and
34641       ** gives more opportunity for asserts(sqlite3_mutex_held())
34642       ** statements to find locking problems.
34643       */
34644       p->sharable = 1;
34645     }
34646 #endif
34647   }
34648 #endif
34649   if( pBt==0 ){
34650     /*
34651     ** The following asserts make sure that structures used by the btree are
34652     ** the right size.  This is to guard against size changes that result
34653     ** when compiling on a different architecture.
34654     */
34655     assert( sizeof(i64)==8 || sizeof(i64)==4 );
34656     assert( sizeof(u64)==8 || sizeof(u64)==4 );
34657     assert( sizeof(u32)==4 );
34658     assert( sizeof(u16)==2 );
34659     assert( sizeof(Pgno)==4 );
34660   
34661     pBt = sqlite3MallocZero( sizeof(*pBt) );
34662     if( pBt==0 ){
34663       rc = SQLITE_NOMEM;
34664       goto btree_open_out;
34665     }
34666     pBt->busyHdr.xFunc = sqlite3BtreeInvokeBusyHandler;
34667     pBt->busyHdr.pArg = pBt;
34668     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename, pageDestructor,
34669                           EXTRA_SIZE, flags, vfsFlags);
34670     if( rc==SQLITE_OK ){
34671       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
34672     }
34673     if( rc!=SQLITE_OK ){
34674       goto btree_open_out;
34675     }
34676     sqlite3PagerSetBusyhandler(pBt->pPager, &pBt->busyHdr);
34677     p->pBt = pBt;
34678   
34679     sqlite3PagerSetReiniter(pBt->pPager, pageReinit);
34680     pBt->pCursor = 0;
34681     pBt->pPage1 = 0;
34682     pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
34683     pBt->pageSize = get2byte(&zDbHeader[16]);
34684     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
34685          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
34686       pBt->pageSize = 0;
34687       sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
34688 #ifndef SQLITE_OMIT_AUTOVACUUM
34689       /* If the magic name ":memory:" will create an in-memory database, then
34690       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
34691       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
34692       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
34693       ** regular file-name. In this case the auto-vacuum applies as per normal.
34694       */
34695       if( zFilename && !isMemdb ){
34696         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
34697         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
34698       }
34699 #endif
34700       nReserve = 0;
34701     }else{
34702       nReserve = zDbHeader[20];
34703       pBt->pageSizeFixed = 1;
34704 #ifndef SQLITE_OMIT_AUTOVACUUM
34705       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
34706       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
34707 #endif
34708     }
34709     pBt->usableSize = pBt->pageSize - nReserve;
34710     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
34711     sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
34712    
34713 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
34714     /* Add the new BtShared object to the linked list sharable BtShareds.
34715     */
34716     if( p->sharable ){
34717       sqlite3_mutex *mutexShared;
34718       pBt->nRef = 1;
34719       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
34720       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
34721         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
34722         if( pBt->mutex==0 ){
34723           rc = SQLITE_NOMEM;
34724           db->mallocFailed = 0;
34725           goto btree_open_out;
34726         }
34727       }
34728       sqlite3_mutex_enter(mutexShared);
34729       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
34730       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
34731       sqlite3_mutex_leave(mutexShared);
34732     }
34733 #endif
34734   }
34735
34736 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
34737   /* If the new Btree uses a sharable pBtShared, then link the new
34738   ** Btree into the list of all sharable Btrees for the same connection.
34739   ** The list is kept in ascending order by pBt address.
34740   */
34741   if( p->sharable ){
34742     int i;
34743     Btree *pSib;
34744     for(i=0; i<db->nDb; i++){
34745       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
34746         while( pSib->pPrev ){ pSib = pSib->pPrev; }
34747         if( p->pBt<pSib->pBt ){
34748           p->pNext = pSib;
34749           p->pPrev = 0;
34750           pSib->pPrev = p;
34751         }else{
34752           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
34753             pSib = pSib->pNext;
34754           }
34755           p->pNext = pSib->pNext;
34756           p->pPrev = pSib;
34757           if( p->pNext ){
34758             p->pNext->pPrev = p;
34759           }
34760           pSib->pNext = p;
34761         }
34762         break;
34763       }
34764     }
34765   }
34766 #endif
34767   *ppBtree = p;
34768
34769 btree_open_out:
34770   if( rc!=SQLITE_OK ){
34771     if( pBt && pBt->pPager ){
34772       sqlite3PagerClose(pBt->pPager);
34773     }
34774     sqlite3_free(pBt);
34775     sqlite3_free(p);
34776     *ppBtree = 0;
34777   }
34778   return rc;
34779 }
34780
34781 /*
34782 ** Decrement the BtShared.nRef counter.  When it reaches zero,
34783 ** remove the BtShared structure from the sharing list.  Return
34784 ** true if the BtShared.nRef counter reaches zero and return
34785 ** false if it is still positive.
34786 */
34787 static int removeFromSharingList(BtShared *pBt){
34788 #ifndef SQLITE_OMIT_SHARED_CACHE
34789   sqlite3_mutex *pMaster;
34790   BtShared *pList;
34791   int removed = 0;
34792
34793   assert( sqlite3_mutex_notheld(pBt->mutex) );
34794   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
34795   sqlite3_mutex_enter(pMaster);
34796   pBt->nRef--;
34797   if( pBt->nRef<=0 ){
34798     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
34799       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
34800     }else{
34801       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
34802       while( ALWAYS(pList) && pList->pNext!=pBt ){
34803         pList=pList->pNext;
34804       }
34805       if( ALWAYS(pList) ){
34806         pList->pNext = pBt->pNext;
34807       }
34808     }
34809     if( SQLITE_THREADSAFE ){
34810       sqlite3_mutex_free(pBt->mutex);
34811     }
34812     removed = 1;
34813   }
34814   sqlite3_mutex_leave(pMaster);
34815   return removed;
34816 #else
34817   return 1;
34818 #endif
34819 }
34820
34821 /*
34822 ** Make sure pBt->pTmpSpace points to an allocation of 
34823 ** MX_CELL_SIZE(pBt) bytes.
34824 */
34825 static void allocateTempSpace(BtShared *pBt){
34826   if( !pBt->pTmpSpace ){
34827     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
34828   }
34829 }
34830
34831 /*
34832 ** Free the pBt->pTmpSpace allocation
34833 */
34834 static void freeTempSpace(BtShared *pBt){
34835   sqlite3PageFree( pBt->pTmpSpace);
34836   pBt->pTmpSpace = 0;
34837 }
34838
34839 /*
34840 ** Close an open database and invalidate all cursors.
34841 */
34842 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
34843   BtShared *pBt = p->pBt;
34844   BtCursor *pCur;
34845
34846   /* Close all cursors opened via this handle.  */
34847   assert( sqlite3_mutex_held(p->db->mutex) );
34848   sqlite3BtreeEnter(p);
34849   pBt->db = p->db;
34850   pCur = pBt->pCursor;
34851   while( pCur ){
34852     BtCursor *pTmp = pCur;
34853     pCur = pCur->pNext;
34854     if( pTmp->pBtree==p ){
34855       sqlite3BtreeCloseCursor(pTmp);
34856     }
34857   }
34858
34859   /* Rollback any active transaction and free the handle structure.
34860   ** The call to sqlite3BtreeRollback() drops any table-locks held by
34861   ** this handle.
34862   */
34863   sqlite3BtreeRollback(p);
34864   sqlite3BtreeLeave(p);
34865
34866   /* If there are still other outstanding references to the shared-btree
34867   ** structure, return now. The remainder of this procedure cleans 
34868   ** up the shared-btree.
34869   */
34870   assert( p->wantToLock==0 && p->locked==0 );
34871   if( !p->sharable || removeFromSharingList(pBt) ){
34872     /* The pBt is no longer on the sharing list, so we can access
34873     ** it without having to hold the mutex.
34874     **
34875     ** Clean out and delete the BtShared object.
34876     */
34877     assert( !pBt->pCursor );
34878     sqlite3PagerClose(pBt->pPager);
34879     if( pBt->xFreeSchema && pBt->pSchema ){
34880       pBt->xFreeSchema(pBt->pSchema);
34881     }
34882     sqlite3_free(pBt->pSchema);
34883     freeTempSpace(pBt);
34884     sqlite3_free(pBt);
34885   }
34886
34887 #ifndef SQLITE_OMIT_SHARED_CACHE
34888   assert( p->wantToLock==0 );
34889   assert( p->locked==0 );
34890   if( p->pPrev ) p->pPrev->pNext = p->pNext;
34891   if( p->pNext ) p->pNext->pPrev = p->pPrev;
34892 #endif
34893
34894   sqlite3_free(p);
34895   return SQLITE_OK;
34896 }
34897
34898 /*
34899 ** Change the limit on the number of pages allowed in the cache.
34900 **
34901 ** The maximum number of cache pages is set to the absolute
34902 ** value of mxPage.  If mxPage is negative, the pager will
34903 ** operate asynchronously - it will not stop to do fsync()s
34904 ** to insure data is written to the disk surface before
34905 ** continuing.  Transactions still work if synchronous is off,
34906 ** and the database cannot be corrupted if this program
34907 ** crashes.  But if the operating system crashes or there is
34908 ** an abrupt power failure when synchronous is off, the database
34909 ** could be left in an inconsistent and unrecoverable state.
34910 ** Synchronous is on by default so database corruption is not
34911 ** normally a worry.
34912 */
34913 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
34914   BtShared *pBt = p->pBt;
34915   assert( sqlite3_mutex_held(p->db->mutex) );
34916   sqlite3BtreeEnter(p);
34917   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
34918   sqlite3BtreeLeave(p);
34919   return SQLITE_OK;
34920 }
34921
34922 /*
34923 ** Change the way data is synced to disk in order to increase or decrease
34924 ** how well the database resists damage due to OS crashes and power
34925 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
34926 ** there is a high probability of damage)  Level 2 is the default.  There
34927 ** is a very low but non-zero probability of damage.  Level 3 reduces the
34928 ** probability of damage to near zero but with a write performance reduction.
34929 */
34930 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
34931 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
34932   BtShared *pBt = p->pBt;
34933   assert( sqlite3_mutex_held(p->db->mutex) );
34934   sqlite3BtreeEnter(p);
34935   sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
34936   sqlite3BtreeLeave(p);
34937   return SQLITE_OK;
34938 }
34939 #endif
34940
34941 /*
34942 ** Return TRUE if the given btree is set to safety level 1.  In other
34943 ** words, return TRUE if no sync() occurs on the disk files.
34944 */
34945 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
34946   BtShared *pBt = p->pBt;
34947   int rc;
34948   assert( sqlite3_mutex_held(p->db->mutex) );  
34949   sqlite3BtreeEnter(p);
34950   assert( pBt && pBt->pPager );
34951   rc = sqlite3PagerNosync(pBt->pPager);
34952   sqlite3BtreeLeave(p);
34953   return rc;
34954 }
34955
34956 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
34957 /*
34958 ** Change the default pages size and the number of reserved bytes per page.
34959 **
34960 ** The page size must be a power of 2 between 512 and 65536.  If the page
34961 ** size supplied does not meet this constraint then the page size is not
34962 ** changed.
34963 **
34964 ** Page sizes are constrained to be a power of two so that the region
34965 ** of the database file used for locking (beginning at PENDING_BYTE,
34966 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
34967 ** at the beginning of a page.
34968 **
34969 ** If parameter nReserve is less than zero, then the number of reserved
34970 ** bytes per page is left unchanged.
34971 */
34972 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve){
34973   int rc = SQLITE_OK;
34974   BtShared *pBt = p->pBt;
34975   sqlite3BtreeEnter(p);
34976   if( pBt->pageSizeFixed ){
34977     sqlite3BtreeLeave(p);
34978     return SQLITE_READONLY;
34979   }
34980   if( nReserve<0 ){
34981     nReserve = pBt->pageSize - pBt->usableSize;
34982   }
34983   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
34984         ((pageSize-1)&pageSize)==0 ){
34985     assert( (pageSize & 7)==0 );
34986     assert( !pBt->pPage1 && !pBt->pCursor );
34987     pBt->pageSize = pageSize;
34988     freeTempSpace(pBt);
34989     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
34990   }
34991   pBt->usableSize = pBt->pageSize - nReserve;
34992   sqlite3BtreeLeave(p);
34993   return rc;
34994 }
34995
34996 /*
34997 ** Return the currently defined page size
34998 */
34999 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
35000   return p->pBt->pageSize;
35001 }
35002 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
35003   int n;
35004   sqlite3BtreeEnter(p);
35005   n = p->pBt->pageSize - p->pBt->usableSize;
35006   sqlite3BtreeLeave(p);
35007   return n;
35008 }
35009
35010 /*
35011 ** Set the maximum page count for a database if mxPage is positive.
35012 ** No changes are made if mxPage is 0 or negative.
35013 ** Regardless of the value of mxPage, return the maximum page count.
35014 */
35015 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
35016   int n;
35017   sqlite3BtreeEnter(p);
35018   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
35019   sqlite3BtreeLeave(p);
35020   return n;
35021 }
35022 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
35023
35024 /*
35025 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
35026 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
35027 ** is disabled. The default value for the auto-vacuum property is 
35028 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
35029 */
35030 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
35031 #ifdef SQLITE_OMIT_AUTOVACUUM
35032   return SQLITE_READONLY;
35033 #else
35034   BtShared *pBt = p->pBt;
35035   int rc = SQLITE_OK;
35036   int av = (autoVacuum?1:0);
35037
35038   sqlite3BtreeEnter(p);
35039   if( pBt->pageSizeFixed && av!=pBt->autoVacuum ){
35040     rc = SQLITE_READONLY;
35041   }else{
35042     pBt->autoVacuum = av;
35043   }
35044   sqlite3BtreeLeave(p);
35045   return rc;
35046 #endif
35047 }
35048
35049 /*
35050 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
35051 ** enabled 1 is returned. Otherwise 0.
35052 */
35053 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
35054 #ifdef SQLITE_OMIT_AUTOVACUUM
35055   return BTREE_AUTOVACUUM_NONE;
35056 #else
35057   int rc;
35058   sqlite3BtreeEnter(p);
35059   rc = (
35060     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
35061     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
35062     BTREE_AUTOVACUUM_INCR
35063   );
35064   sqlite3BtreeLeave(p);
35065   return rc;
35066 #endif
35067 }
35068
35069
35070 /*
35071 ** Get a reference to pPage1 of the database file.  This will
35072 ** also acquire a readlock on that file.
35073 **
35074 ** SQLITE_OK is returned on success.  If the file is not a
35075 ** well-formed database file, then SQLITE_CORRUPT is returned.
35076 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
35077 ** is returned if we run out of memory. 
35078 */
35079 static int lockBtree(BtShared *pBt){
35080   int rc;
35081   MemPage *pPage1;
35082   int nPage;
35083
35084   assert( sqlite3_mutex_held(pBt->mutex) );
35085   if( pBt->pPage1 ) return SQLITE_OK;
35086   rc = sqlite3BtreeGetPage(pBt, 1, &pPage1, 0);
35087   if( rc!=SQLITE_OK ) return rc;
35088
35089   /* Do some checking to help insure the file we opened really is
35090   ** a valid database file. 
35091   */
35092   rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
35093   if( rc!=SQLITE_OK ){
35094     goto page1_init_failed;
35095   }else if( nPage>0 ){
35096     int pageSize;
35097     int usableSize;
35098     u8 *page1 = pPage1->aData;
35099     rc = SQLITE_NOTADB;
35100     if( memcmp(page1, zMagicHeader, 16)!=0 ){
35101       goto page1_init_failed;
35102     }
35103     if( page1[18]>1 ){
35104       pBt->readOnly = 1;
35105     }
35106     if( page1[19]>1 ){
35107       goto page1_init_failed;
35108     }
35109
35110     /* The maximum embedded fraction must be exactly 25%.  And the minimum
35111     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
35112     ** The original design allowed these amounts to vary, but as of
35113     ** version 3.6.0, we require them to be fixed.
35114     */
35115     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
35116       goto page1_init_failed;
35117     }
35118     pageSize = get2byte(&page1[16]);
35119     if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
35120         (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
35121     ){
35122       goto page1_init_failed;
35123     }
35124     assert( (pageSize & 7)==0 );
35125     usableSize = pageSize - page1[20];
35126     if( pageSize!=pBt->pageSize ){
35127       /* After reading the first page of the database assuming a page size
35128       ** of BtShared.pageSize, we have discovered that the page-size is
35129       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
35130       ** zero and return SQLITE_OK. The caller will call this function
35131       ** again with the correct page-size.
35132       */
35133       releasePage(pPage1);
35134       pBt->usableSize = usableSize;
35135       pBt->pageSize = pageSize;
35136       freeTempSpace(pBt);
35137       sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
35138       return SQLITE_OK;
35139     }
35140     if( usableSize<500 ){
35141       goto page1_init_failed;
35142     }
35143     pBt->pageSize = pageSize;
35144     pBt->usableSize = usableSize;
35145 #ifndef SQLITE_OMIT_AUTOVACUUM
35146     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
35147     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
35148 #endif
35149   }
35150
35151   /* maxLocal is the maximum amount of payload to store locally for
35152   ** a cell.  Make sure it is small enough so that at least minFanout
35153   ** cells can will fit on one page.  We assume a 10-byte page header.
35154   ** Besides the payload, the cell must store:
35155   **     2-byte pointer to the cell
35156   **     4-byte child pointer
35157   **     9-byte nKey value
35158   **     4-byte nData value
35159   **     4-byte overflow page pointer
35160   ** So a cell consists of a 2-byte poiner, a header which is as much as
35161   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
35162   ** page pointer.
35163   */
35164   pBt->maxLocal = (pBt->usableSize-12)*64/255 - 23;
35165   pBt->minLocal = (pBt->usableSize-12)*32/255 - 23;
35166   pBt->maxLeaf = pBt->usableSize - 35;
35167   pBt->minLeaf = (pBt->usableSize-12)*32/255 - 23;
35168   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
35169   pBt->pPage1 = pPage1;
35170   return SQLITE_OK;
35171
35172 page1_init_failed:
35173   releasePage(pPage1);
35174   pBt->pPage1 = 0;
35175   return rc;
35176 }
35177
35178 /*
35179 ** This routine works like lockBtree() except that it also invokes the
35180 ** busy callback if there is lock contention.
35181 */
35182 static int lockBtreeWithRetry(Btree *pRef){
35183   int rc = SQLITE_OK;
35184
35185   assert( sqlite3BtreeHoldsMutex(pRef) );
35186   if( pRef->inTrans==TRANS_NONE ){
35187     u8 inTransaction = pRef->pBt->inTransaction;
35188     btreeIntegrity(pRef);
35189     rc = sqlite3BtreeBeginTrans(pRef, 0);
35190     pRef->pBt->inTransaction = inTransaction;
35191     pRef->inTrans = TRANS_NONE;
35192     if( rc==SQLITE_OK ){
35193       pRef->pBt->nTransaction--;
35194     }
35195     btreeIntegrity(pRef);
35196   }
35197   return rc;
35198 }
35199        
35200
35201 /*
35202 ** If there are no outstanding cursors and we are not in the middle
35203 ** of a transaction but there is a read lock on the database, then
35204 ** this routine unrefs the first page of the database file which 
35205 ** has the effect of releasing the read lock.
35206 **
35207 ** If there are any outstanding cursors, this routine is a no-op.
35208 **
35209 ** If there is a transaction in progress, this routine is a no-op.
35210 */
35211 static void unlockBtreeIfUnused(BtShared *pBt){
35212   assert( sqlite3_mutex_held(pBt->mutex) );
35213   if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
35214     if( sqlite3PagerRefcount(pBt->pPager)>=1 ){
35215       assert( pBt->pPage1->aData );
35216 #if 0
35217       if( pBt->pPage1->aData==0 ){
35218         MemPage *pPage = pBt->pPage1;
35219         pPage->aData = sqlite3PagerGetData(pPage->pDbPage);
35220         pPage->pBt = pBt;
35221         pPage->pgno = 1;
35222       }
35223 #endif
35224       releasePage(pBt->pPage1);
35225     }
35226     pBt->pPage1 = 0;
35227     pBt->inStmt = 0;
35228   }
35229 }
35230
35231 /*
35232 ** Create a new database by initializing the first page of the
35233 ** file.
35234 */
35235 static int newDatabase(BtShared *pBt){
35236   MemPage *pP1;
35237   unsigned char *data;
35238   int rc;
35239   int nPage;
35240
35241   assert( sqlite3_mutex_held(pBt->mutex) );
35242   rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
35243   if( rc!=SQLITE_OK || nPage>0 ){
35244     return rc;
35245   }
35246   pP1 = pBt->pPage1;
35247   assert( pP1!=0 );
35248   data = pP1->aData;
35249   rc = sqlite3PagerWrite(pP1->pDbPage);
35250   if( rc ) return rc;
35251   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
35252   assert( sizeof(zMagicHeader)==16 );
35253   put2byte(&data[16], pBt->pageSize);
35254   data[18] = 1;
35255   data[19] = 1;
35256   data[20] = pBt->pageSize - pBt->usableSize;
35257   data[21] = 64;
35258   data[22] = 32;
35259   data[23] = 32;
35260   memset(&data[24], 0, 100-24);
35261   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
35262   pBt->pageSizeFixed = 1;
35263 #ifndef SQLITE_OMIT_AUTOVACUUM
35264   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
35265   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
35266   put4byte(&data[36 + 4*4], pBt->autoVacuum);
35267   put4byte(&data[36 + 7*4], pBt->incrVacuum);
35268 #endif
35269   return SQLITE_OK;
35270 }
35271
35272 /*
35273 ** Attempt to start a new transaction. A write-transaction
35274 ** is started if the second argument is nonzero, otherwise a read-
35275 ** transaction.  If the second argument is 2 or more and exclusive
35276 ** transaction is started, meaning that no other process is allowed
35277 ** to access the database.  A preexisting transaction may not be
35278 ** upgraded to exclusive by calling this routine a second time - the
35279 ** exclusivity flag only works for a new transaction.
35280 **
35281 ** A write-transaction must be started before attempting any 
35282 ** changes to the database.  None of the following routines 
35283 ** will work unless a transaction is started first:
35284 **
35285 **      sqlite3BtreeCreateTable()
35286 **      sqlite3BtreeCreateIndex()
35287 **      sqlite3BtreeClearTable()
35288 **      sqlite3BtreeDropTable()
35289 **      sqlite3BtreeInsert()
35290 **      sqlite3BtreeDelete()
35291 **      sqlite3BtreeUpdateMeta()
35292 **
35293 ** If an initial attempt to acquire the lock fails because of lock contention
35294 ** and the database was previously unlocked, then invoke the busy handler
35295 ** if there is one.  But if there was previously a read-lock, do not
35296 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
35297 ** returned when there is already a read-lock in order to avoid a deadlock.
35298 **
35299 ** Suppose there are two processes A and B.  A has a read lock and B has
35300 ** a reserved lock.  B tries to promote to exclusive but is blocked because
35301 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
35302 ** One or the other of the two processes must give way or there can be
35303 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
35304 ** when A already has a read lock, we encourage A to give up and let B
35305 ** proceed.
35306 */
35307 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
35308   BtShared *pBt = p->pBt;
35309   int rc = SQLITE_OK;
35310
35311   sqlite3BtreeEnter(p);
35312   pBt->db = p->db;
35313   btreeIntegrity(p);
35314
35315   /* If the btree is already in a write-transaction, or it
35316   ** is already in a read-transaction and a read-transaction
35317   ** is requested, this is a no-op.
35318   */
35319   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
35320     goto trans_begun;
35321   }
35322
35323   /* Write transactions are not possible on a read-only database */
35324   if( pBt->readOnly && wrflag ){
35325     rc = SQLITE_READONLY;
35326     goto trans_begun;
35327   }
35328
35329   /* If another database handle has already opened a write transaction 
35330   ** on this shared-btree structure and a second write transaction is
35331   ** requested, return SQLITE_BUSY.
35332   */
35333   if( pBt->inTransaction==TRANS_WRITE && wrflag ){
35334     rc = SQLITE_BUSY;
35335     goto trans_begun;
35336   }
35337
35338 #ifndef SQLITE_OMIT_SHARED_CACHE
35339   if( wrflag>1 ){
35340     BtLock *pIter;
35341     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
35342       if( pIter->pBtree!=p ){
35343         rc = SQLITE_BUSY;
35344         goto trans_begun;
35345       }
35346     }
35347   }
35348 #endif
35349
35350   do {
35351     if( pBt->pPage1==0 ){
35352       do{
35353         rc = lockBtree(pBt);
35354       }while( pBt->pPage1==0 && rc==SQLITE_OK );
35355     }
35356
35357     if( rc==SQLITE_OK && wrflag ){
35358       if( pBt->readOnly ){
35359         rc = SQLITE_READONLY;
35360       }else{
35361         rc = sqlite3PagerBegin(pBt->pPage1->pDbPage, wrflag>1);
35362         if( rc==SQLITE_OK ){
35363           rc = newDatabase(pBt);
35364         }
35365       }
35366     }
35367   
35368     if( rc==SQLITE_OK ){
35369       if( wrflag ) pBt->inStmt = 0;
35370     }else{
35371       unlockBtreeIfUnused(pBt);
35372     }
35373   }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
35374           sqlite3BtreeInvokeBusyHandler(pBt, 0) );
35375
35376   if( rc==SQLITE_OK ){
35377     if( p->inTrans==TRANS_NONE ){
35378       pBt->nTransaction++;
35379     }
35380     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
35381     if( p->inTrans>pBt->inTransaction ){
35382       pBt->inTransaction = p->inTrans;
35383     }
35384 #ifndef SQLITE_OMIT_SHARED_CACHE
35385     if( wrflag>1 ){
35386       assert( !pBt->pExclusive );
35387       pBt->pExclusive = p;
35388     }
35389 #endif
35390   }
35391
35392
35393 trans_begun:
35394   btreeIntegrity(p);
35395   sqlite3BtreeLeave(p);
35396   return rc;
35397 }
35398
35399
35400 #ifndef SQLITE_OMIT_AUTOVACUUM
35401
35402 /*
35403 ** Set the pointer-map entries for all children of page pPage. Also, if
35404 ** pPage contains cells that point to overflow pages, set the pointer
35405 ** map entries for the overflow pages as well.
35406 */
35407 static int setChildPtrmaps(MemPage *pPage){
35408   int i;                             /* Counter variable */
35409   int nCell;                         /* Number of cells in page pPage */
35410   int rc;                            /* Return code */
35411   BtShared *pBt = pPage->pBt;
35412   int isInitOrig = pPage->isInit;
35413   Pgno pgno = pPage->pgno;
35414
35415   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
35416   rc = sqlite3BtreeInitPage(pPage, pPage->pParent);
35417   if( rc!=SQLITE_OK ){
35418     goto set_child_ptrmaps_out;
35419   }
35420   nCell = pPage->nCell;
35421
35422   for(i=0; i<nCell; i++){
35423     u8 *pCell = findCell(pPage, i);
35424
35425     rc = ptrmapPutOvflPtr(pPage, pCell);
35426     if( rc!=SQLITE_OK ){
35427       goto set_child_ptrmaps_out;
35428     }
35429
35430     if( !pPage->leaf ){
35431       Pgno childPgno = get4byte(pCell);
35432       rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
35433        if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
35434     }
35435   }
35436
35437   if( !pPage->leaf ){
35438     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
35439     rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
35440   }
35441
35442 set_child_ptrmaps_out:
35443   pPage->isInit = isInitOrig;
35444   return rc;
35445 }
35446
35447 /*
35448 ** Somewhere on pPage, which is guarenteed to be a btree page, not an overflow
35449 ** page, is a pointer to page iFrom. Modify this pointer so that it points to
35450 ** iTo. Parameter eType describes the type of pointer to be modified, as 
35451 ** follows:
35452 **
35453 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
35454 **                   page of pPage.
35455 **
35456 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
35457 **                   page pointed to by one of the cells on pPage.
35458 **
35459 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
35460 **                   overflow page in the list.
35461 */
35462 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
35463   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
35464   if( eType==PTRMAP_OVERFLOW2 ){
35465     /* The pointer is always the first 4 bytes of the page in this case.  */
35466     if( get4byte(pPage->aData)!=iFrom ){
35467       return SQLITE_CORRUPT_BKPT;
35468     }
35469     put4byte(pPage->aData, iTo);
35470   }else{
35471     int isInitOrig = pPage->isInit;
35472     int i;
35473     int nCell;
35474
35475     sqlite3BtreeInitPage(pPage, 0);
35476     nCell = pPage->nCell;
35477
35478     for(i=0; i<nCell; i++){
35479       u8 *pCell = findCell(pPage, i);
35480       if( eType==PTRMAP_OVERFLOW1 ){
35481         CellInfo info;
35482         sqlite3BtreeParseCellPtr(pPage, pCell, &info);
35483         if( info.iOverflow ){
35484           if( iFrom==get4byte(&pCell[info.iOverflow]) ){
35485             put4byte(&pCell[info.iOverflow], iTo);
35486             break;
35487           }
35488         }
35489       }else{
35490         if( get4byte(pCell)==iFrom ){
35491           put4byte(pCell, iTo);
35492           break;
35493         }
35494       }
35495     }
35496   
35497     if( i==nCell ){
35498       if( eType!=PTRMAP_BTREE || 
35499           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
35500         return SQLITE_CORRUPT_BKPT;
35501       }
35502       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
35503     }
35504
35505     pPage->isInit = isInitOrig;
35506   }
35507   return SQLITE_OK;
35508 }
35509
35510
35511 /*
35512 ** Move the open database page pDbPage to location iFreePage in the 
35513 ** database. The pDbPage reference remains valid.
35514 */
35515 static int relocatePage(
35516   BtShared *pBt,           /* Btree */
35517   MemPage *pDbPage,        /* Open page to move */
35518   u8 eType,                /* Pointer map 'type' entry for pDbPage */
35519   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
35520   Pgno iFreePage,          /* The location to move pDbPage to */
35521   int isCommit
35522 ){
35523   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
35524   Pgno iDbPage = pDbPage->pgno;
35525   Pager *pPager = pBt->pPager;
35526   int rc;
35527
35528   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
35529       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
35530   assert( sqlite3_mutex_held(pBt->mutex) );
35531   assert( pDbPage->pBt==pBt );
35532
35533   /* Move page iDbPage from its current location to page number iFreePage */
35534   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
35535       iDbPage, iFreePage, iPtrPage, eType));
35536   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
35537   if( rc!=SQLITE_OK ){
35538     return rc;
35539   }
35540   pDbPage->pgno = iFreePage;
35541
35542   /* If pDbPage was a btree-page, then it may have child pages and/or cells
35543   ** that point to overflow pages. The pointer map entries for all these
35544   ** pages need to be changed.
35545   **
35546   ** If pDbPage is an overflow page, then the first 4 bytes may store a
35547   ** pointer to a subsequent overflow page. If this is the case, then
35548   ** the pointer map needs to be updated for the subsequent overflow page.
35549   */
35550   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
35551     rc = setChildPtrmaps(pDbPage);
35552     if( rc!=SQLITE_OK ){
35553       return rc;
35554     }
35555   }else{
35556     Pgno nextOvfl = get4byte(pDbPage->aData);
35557     if( nextOvfl!=0 ){
35558       rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
35559       if( rc!=SQLITE_OK ){
35560         return rc;
35561       }
35562     }
35563   }
35564
35565   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
35566   ** that it points at iFreePage. Also fix the pointer map entry for
35567   ** iPtrPage.
35568   */
35569   if( eType!=PTRMAP_ROOTPAGE ){
35570     rc = sqlite3BtreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
35571     if( rc!=SQLITE_OK ){
35572       return rc;
35573     }
35574     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
35575     if( rc!=SQLITE_OK ){
35576       releasePage(pPtrPage);
35577       return rc;
35578     }
35579     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
35580     releasePage(pPtrPage);
35581     if( rc==SQLITE_OK ){
35582       rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
35583     }
35584   }
35585   return rc;
35586 }
35587
35588 /* Forward declaration required by incrVacuumStep(). */
35589 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
35590
35591 /*
35592 ** Perform a single step of an incremental-vacuum. If successful,
35593 ** return SQLITE_OK. If there is no work to do (and therefore no
35594 ** point in calling this function again), return SQLITE_DONE.
35595 **
35596 ** More specificly, this function attempts to re-organize the 
35597 ** database so that the last page of the file currently in use
35598 ** is no longer in use.
35599 **
35600 ** If the nFin parameter is non-zero, the implementation assumes
35601 ** that the caller will keep calling incrVacuumStep() until
35602 ** it returns SQLITE_DONE or an error, and that nFin is the
35603 ** number of pages the database file will contain after this 
35604 ** process is complete.
35605 */
35606 static int incrVacuumStep(BtShared *pBt, Pgno nFin){
35607   Pgno iLastPg;             /* Last page in the database */
35608   Pgno nFreeList;           /* Number of pages still on the free-list */
35609
35610   assert( sqlite3_mutex_held(pBt->mutex) );
35611   iLastPg = pBt->nTrunc;
35612   if( iLastPg==0 ){
35613     iLastPg = pagerPagecount(pBt->pPager);
35614   }
35615
35616   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
35617     int rc;
35618     u8 eType;
35619     Pgno iPtrPage;
35620
35621     nFreeList = get4byte(&pBt->pPage1->aData[36]);
35622     if( nFreeList==0 || nFin==iLastPg ){
35623       return SQLITE_DONE;
35624     }
35625
35626     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
35627     if( rc!=SQLITE_OK ){
35628       return rc;
35629     }
35630     if( eType==PTRMAP_ROOTPAGE ){
35631       return SQLITE_CORRUPT_BKPT;
35632     }
35633
35634     if( eType==PTRMAP_FREEPAGE ){
35635       if( nFin==0 ){
35636         /* Remove the page from the files free-list. This is not required
35637         ** if nFin is non-zero. In that case, the free-list will be
35638         ** truncated to zero after this function returns, so it doesn't 
35639         ** matter if it still contains some garbage entries.
35640         */
35641         Pgno iFreePg;
35642         MemPage *pFreePg;
35643         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
35644         if( rc!=SQLITE_OK ){
35645           return rc;
35646         }
35647         assert( iFreePg==iLastPg );
35648         releasePage(pFreePg);
35649       }
35650     } else {
35651       Pgno iFreePg;             /* Index of free page to move pLastPg to */
35652       MemPage *pLastPg;
35653
35654       rc = sqlite3BtreeGetPage(pBt, iLastPg, &pLastPg, 0);
35655       if( rc!=SQLITE_OK ){
35656         return rc;
35657       }
35658
35659       /* If nFin is zero, this loop runs exactly once and page pLastPg
35660       ** is swapped with the first free page pulled off the free list.
35661       **
35662       ** On the other hand, if nFin is greater than zero, then keep
35663       ** looping until a free-page located within the first nFin pages
35664       ** of the file is found.
35665       */
35666       do {
35667         MemPage *pFreePg;
35668         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
35669         if( rc!=SQLITE_OK ){
35670           releasePage(pLastPg);
35671           return rc;
35672         }
35673         releasePage(pFreePg);
35674       }while( nFin!=0 && iFreePg>nFin );
35675       assert( iFreePg<iLastPg );
35676       
35677       rc = sqlite3PagerWrite(pLastPg->pDbPage);
35678       if( rc==SQLITE_OK ){
35679         rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
35680       }
35681       releasePage(pLastPg);
35682       if( rc!=SQLITE_OK ){
35683         return rc;
35684       }
35685     }
35686   }
35687
35688   pBt->nTrunc = iLastPg - 1;
35689   while( pBt->nTrunc==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, pBt->nTrunc) ){
35690     pBt->nTrunc--;
35691   }
35692   return SQLITE_OK;
35693 }
35694
35695 /*
35696 ** A write-transaction must be opened before calling this function.
35697 ** It performs a single unit of work towards an incremental vacuum.
35698 **
35699 ** If the incremental vacuum is finished after this function has run,
35700 ** SQLITE_DONE is returned. If it is not finished, but no error occured,
35701 ** SQLITE_OK is returned. Otherwise an SQLite error code. 
35702 */
35703 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
35704   int rc;
35705   BtShared *pBt = p->pBt;
35706
35707   sqlite3BtreeEnter(p);
35708   pBt->db = p->db;
35709   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
35710   if( !pBt->autoVacuum ){
35711     rc = SQLITE_DONE;
35712   }else{
35713     invalidateAllOverflowCache(pBt);
35714     rc = incrVacuumStep(pBt, 0);
35715   }
35716   sqlite3BtreeLeave(p);
35717   return rc;
35718 }
35719
35720 /*
35721 ** This routine is called prior to sqlite3PagerCommit when a transaction
35722 ** is commited for an auto-vacuum database.
35723 **
35724 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
35725 ** the database file should be truncated to during the commit process. 
35726 ** i.e. the database has been reorganized so that only the first *pnTrunc
35727 ** pages are in use.
35728 */
35729 static int autoVacuumCommit(BtShared *pBt, Pgno *pnTrunc){
35730   int rc = SQLITE_OK;
35731   Pager *pPager = pBt->pPager;
35732 #ifndef NDEBUG
35733   int nRef = sqlite3PagerRefcount(pPager);
35734 #endif
35735
35736   assert( sqlite3_mutex_held(pBt->mutex) );
35737   invalidateAllOverflowCache(pBt);
35738   assert(pBt->autoVacuum);
35739   if( !pBt->incrVacuum ){
35740     Pgno nFin = 0;
35741
35742     if( pBt->nTrunc==0 ){
35743       Pgno nFree;
35744       Pgno nPtrmap;
35745       const int pgsz = pBt->pageSize;
35746       int nOrig = pagerPagecount(pBt->pPager);
35747
35748       if( PTRMAP_ISPAGE(pBt, nOrig) ){
35749         return SQLITE_CORRUPT_BKPT;
35750       }
35751       if( nOrig==PENDING_BYTE_PAGE(pBt) ){
35752         nOrig--;
35753       }
35754       nFree = get4byte(&pBt->pPage1->aData[36]);
35755       nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+pgsz/5)/(pgsz/5);
35756       nFin = nOrig - nFree - nPtrmap;
35757       if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<=PENDING_BYTE_PAGE(pBt) ){
35758         nFin--;
35759       }
35760       while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
35761         nFin--;
35762       }
35763     }
35764
35765     while( rc==SQLITE_OK ){
35766       rc = incrVacuumStep(pBt, nFin);
35767     }
35768     if( rc==SQLITE_DONE ){
35769       assert(nFin==0 || pBt->nTrunc==0 || nFin<=pBt->nTrunc);
35770       rc = SQLITE_OK;
35771       if( pBt->nTrunc && nFin ){
35772         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
35773         put4byte(&pBt->pPage1->aData[32], 0);
35774         put4byte(&pBt->pPage1->aData[36], 0);
35775         pBt->nTrunc = nFin;
35776       }
35777     }
35778     if( rc!=SQLITE_OK ){
35779       sqlite3PagerRollback(pPager);
35780     }
35781   }
35782
35783   if( rc==SQLITE_OK ){
35784     *pnTrunc = pBt->nTrunc;
35785     pBt->nTrunc = 0;
35786   }
35787   assert( nRef==sqlite3PagerRefcount(pPager) );
35788   return rc;
35789 }
35790
35791 #endif
35792
35793 /*
35794 ** This routine does the first phase of a two-phase commit.  This routine
35795 ** causes a rollback journal to be created (if it does not already exist)
35796 ** and populated with enough information so that if a power loss occurs
35797 ** the database can be restored to its original state by playing back
35798 ** the journal.  Then the contents of the journal are flushed out to
35799 ** the disk.  After the journal is safely on oxide, the changes to the
35800 ** database are written into the database file and flushed to oxide.
35801 ** At the end of this call, the rollback journal still exists on the
35802 ** disk and we are still holding all locks, so the transaction has not
35803 ** committed.  See sqlite3BtreeCommit() for the second phase of the
35804 ** commit process.
35805 **
35806 ** This call is a no-op if no write-transaction is currently active on pBt.
35807 **
35808 ** Otherwise, sync the database file for the btree pBt. zMaster points to
35809 ** the name of a master journal file that should be written into the
35810 ** individual journal file, or is NULL, indicating no master journal file 
35811 ** (single database transaction).
35812 **
35813 ** When this is called, the master journal should already have been
35814 ** created, populated with this journal pointer and synced to disk.
35815 **
35816 ** Once this is routine has returned, the only thing required to commit
35817 ** the write-transaction for this database file is to delete the journal.
35818 */
35819 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
35820   int rc = SQLITE_OK;
35821   if( p->inTrans==TRANS_WRITE ){
35822     BtShared *pBt = p->pBt;
35823     Pgno nTrunc = 0;
35824     sqlite3BtreeEnter(p);
35825     pBt->db = p->db;
35826 #ifndef SQLITE_OMIT_AUTOVACUUM
35827     if( pBt->autoVacuum ){
35828       rc = autoVacuumCommit(pBt, &nTrunc); 
35829       if( rc!=SQLITE_OK ){
35830         sqlite3BtreeLeave(p);
35831         return rc;
35832       }
35833     }
35834 #endif
35835     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, nTrunc, 0);
35836     sqlite3BtreeLeave(p);
35837   }
35838   return rc;
35839 }
35840
35841 /*
35842 ** Commit the transaction currently in progress.
35843 **
35844 ** This routine implements the second phase of a 2-phase commit.  The
35845 ** sqlite3BtreeSync() routine does the first phase and should be invoked
35846 ** prior to calling this routine.  The sqlite3BtreeSync() routine did
35847 ** all the work of writing information out to disk and flushing the
35848 ** contents so that they are written onto the disk platter.  All this
35849 ** routine has to do is delete or truncate the rollback journal
35850 ** (which causes the transaction to commit) and drop locks.
35851 **
35852 ** This will release the write lock on the database file.  If there
35853 ** are no active cursors, it also releases the read lock.
35854 */
35855 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p){
35856   BtShared *pBt = p->pBt;
35857
35858   sqlite3BtreeEnter(p);
35859   pBt->db = p->db;
35860   btreeIntegrity(p);
35861
35862   /* If the handle has a write-transaction open, commit the shared-btrees 
35863   ** transaction and set the shared state to TRANS_READ.
35864   */
35865   if( p->inTrans==TRANS_WRITE ){
35866     int rc;
35867     assert( pBt->inTransaction==TRANS_WRITE );
35868     assert( pBt->nTransaction>0 );
35869     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
35870     if( rc!=SQLITE_OK ){
35871       sqlite3BtreeLeave(p);
35872       return rc;
35873     }
35874     pBt->inTransaction = TRANS_READ;
35875     pBt->inStmt = 0;
35876   }
35877   unlockAllTables(p);
35878
35879   /* If the handle has any kind of transaction open, decrement the transaction
35880   ** count of the shared btree. If the transaction count reaches 0, set
35881   ** the shared state to TRANS_NONE. The unlockBtreeIfUnused() call below
35882   ** will unlock the pager.
35883   */
35884   if( p->inTrans!=TRANS_NONE ){
35885     pBt->nTransaction--;
35886     if( 0==pBt->nTransaction ){
35887       pBt->inTransaction = TRANS_NONE;
35888     }
35889   }
35890
35891   /* Set the handles current transaction state to TRANS_NONE and unlock
35892   ** the pager if this call closed the only read or write transaction.
35893   */
35894   p->inTrans = TRANS_NONE;
35895   unlockBtreeIfUnused(pBt);
35896
35897   btreeIntegrity(p);
35898   sqlite3BtreeLeave(p);
35899   return SQLITE_OK;
35900 }
35901
35902 /*
35903 ** Do both phases of a commit.
35904 */
35905 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
35906   int rc;
35907   sqlite3BtreeEnter(p);
35908   rc = sqlite3BtreeCommitPhaseOne(p, 0);
35909   if( rc==SQLITE_OK ){
35910     rc = sqlite3BtreeCommitPhaseTwo(p);
35911   }
35912   sqlite3BtreeLeave(p);
35913   return rc;
35914 }
35915
35916 #ifndef NDEBUG
35917 /*
35918 ** Return the number of write-cursors open on this handle. This is for use
35919 ** in assert() expressions, so it is only compiled if NDEBUG is not
35920 ** defined.
35921 **
35922 ** For the purposes of this routine, a write-cursor is any cursor that
35923 ** is capable of writing to the databse.  That means the cursor was
35924 ** originally opened for writing and the cursor has not be disabled
35925 ** by having its state changed to CURSOR_FAULT.
35926 */
35927 static int countWriteCursors(BtShared *pBt){
35928   BtCursor *pCur;
35929   int r = 0;
35930   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
35931     if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++; 
35932   }
35933   return r;
35934 }
35935 #endif
35936
35937 /*
35938 ** This routine sets the state to CURSOR_FAULT and the error
35939 ** code to errCode for every cursor on BtShared that pBtree
35940 ** references.
35941 **
35942 ** Every cursor is tripped, including cursors that belong
35943 ** to other database connections that happen to be sharing
35944 ** the cache with pBtree.
35945 **
35946 ** This routine gets called when a rollback occurs.
35947 ** All cursors using the same cache must be tripped
35948 ** to prevent them from trying to use the btree after
35949 ** the rollback.  The rollback may have deleted tables
35950 ** or moved root pages, so it is not sufficient to
35951 ** save the state of the cursor.  The cursor must be
35952 ** invalidated.
35953 */
35954 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
35955   BtCursor *p;
35956   sqlite3BtreeEnter(pBtree);
35957   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
35958     clearCursorPosition(p);
35959     p->eState = CURSOR_FAULT;
35960     p->skip = errCode;
35961   }
35962   sqlite3BtreeLeave(pBtree);
35963 }
35964
35965 /*
35966 ** Rollback the transaction in progress.  All cursors will be
35967 ** invalided by this operation.  Any attempt to use a cursor
35968 ** that was open at the beginning of this operation will result
35969 ** in an error.
35970 **
35971 ** This will release the write lock on the database file.  If there
35972 ** are no active cursors, it also releases the read lock.
35973 */
35974 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
35975   int rc;
35976   BtShared *pBt = p->pBt;
35977   MemPage *pPage1;
35978
35979   sqlite3BtreeEnter(p);
35980   pBt->db = p->db;
35981   rc = saveAllCursors(pBt, 0, 0);
35982 #ifndef SQLITE_OMIT_SHARED_CACHE
35983   if( rc!=SQLITE_OK ){
35984     /* This is a horrible situation. An IO or malloc() error occured whilst
35985     ** trying to save cursor positions. If this is an automatic rollback (as
35986     ** the result of a constraint, malloc() failure or IO error) then 
35987     ** the cache may be internally inconsistent (not contain valid trees) so
35988     ** we cannot simply return the error to the caller. Instead, abort 
35989     ** all queries that may be using any of the cursors that failed to save.
35990     */
35991     sqlite3BtreeTripAllCursors(p, rc);
35992   }
35993 #endif
35994   btreeIntegrity(p);
35995   unlockAllTables(p);
35996
35997   if( p->inTrans==TRANS_WRITE ){
35998     int rc2;
35999
36000 #ifndef SQLITE_OMIT_AUTOVACUUM
36001     pBt->nTrunc = 0;
36002 #endif
36003
36004     assert( TRANS_WRITE==pBt->inTransaction );
36005     rc2 = sqlite3PagerRollback(pBt->pPager);
36006     if( rc2!=SQLITE_OK ){
36007       rc = rc2;
36008     }
36009
36010     /* The rollback may have destroyed the pPage1->aData value.  So
36011     ** call sqlite3BtreeGetPage() on page 1 again to make
36012     ** sure pPage1->aData is set correctly. */
36013     if( sqlite3BtreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
36014       releasePage(pPage1);
36015     }
36016     assert( countWriteCursors(pBt)==0 );
36017     pBt->inTransaction = TRANS_READ;
36018   }
36019
36020   if( p->inTrans!=TRANS_NONE ){
36021     assert( pBt->nTransaction>0 );
36022     pBt->nTransaction--;
36023     if( 0==pBt->nTransaction ){
36024       pBt->inTransaction = TRANS_NONE;
36025     }
36026   }
36027
36028   p->inTrans = TRANS_NONE;
36029   pBt->inStmt = 0;
36030   unlockBtreeIfUnused(pBt);
36031
36032   btreeIntegrity(p);
36033   sqlite3BtreeLeave(p);
36034   return rc;
36035 }
36036
36037 /*
36038 ** Start a statement subtransaction.  The subtransaction can
36039 ** can be rolled back independently of the main transaction.
36040 ** You must start a transaction before starting a subtransaction.
36041 ** The subtransaction is ended automatically if the main transaction
36042 ** commits or rolls back.
36043 **
36044 ** Only one subtransaction may be active at a time.  It is an error to try
36045 ** to start a new subtransaction if another subtransaction is already active.
36046 **
36047 ** Statement subtransactions are used around individual SQL statements
36048 ** that are contained within a BEGIN...COMMIT block.  If a constraint
36049 ** error occurs within the statement, the effect of that one statement
36050 ** can be rolled back without having to rollback the entire transaction.
36051 */
36052 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p){
36053   int rc;
36054   BtShared *pBt = p->pBt;
36055   sqlite3BtreeEnter(p);
36056   pBt->db = p->db;
36057   if( (p->inTrans!=TRANS_WRITE) || pBt->inStmt ){
36058     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
36059   }else{
36060     assert( pBt->inTransaction==TRANS_WRITE );
36061     rc = pBt->readOnly ? SQLITE_OK : sqlite3PagerStmtBegin(pBt->pPager);
36062     pBt->inStmt = 1;
36063   }
36064   sqlite3BtreeLeave(p);
36065   return rc;
36066 }
36067
36068
36069 /*
36070 ** Commit the statment subtransaction currently in progress.  If no
36071 ** subtransaction is active, this is a no-op.
36072 */
36073 SQLITE_PRIVATE int sqlite3BtreeCommitStmt(Btree *p){
36074   int rc;
36075   BtShared *pBt = p->pBt;
36076   sqlite3BtreeEnter(p);
36077   pBt->db = p->db;
36078   if( pBt->inStmt && !pBt->readOnly ){
36079     rc = sqlite3PagerStmtCommit(pBt->pPager);
36080   }else{
36081     rc = SQLITE_OK;
36082   }
36083   pBt->inStmt = 0;
36084   sqlite3BtreeLeave(p);
36085   return rc;
36086 }
36087
36088 /*
36089 ** Rollback the active statement subtransaction.  If no subtransaction
36090 ** is active this routine is a no-op.
36091 **
36092 ** All cursors will be invalidated by this operation.  Any attempt
36093 ** to use a cursor that was open at the beginning of this operation
36094 ** will result in an error.
36095 */
36096 SQLITE_PRIVATE int sqlite3BtreeRollbackStmt(Btree *p){
36097   int rc = SQLITE_OK;
36098   BtShared *pBt = p->pBt;
36099   sqlite3BtreeEnter(p);
36100   pBt->db = p->db;
36101   if( pBt->inStmt && !pBt->readOnly ){
36102     rc = sqlite3PagerStmtRollback(pBt->pPager);
36103     pBt->inStmt = 0;
36104   }
36105   sqlite3BtreeLeave(p);
36106   return rc;
36107 }
36108
36109 /*
36110 ** Create a new cursor for the BTree whose root is on the page
36111 ** iTable.  The act of acquiring a cursor gets a read lock on 
36112 ** the database file.
36113 **
36114 ** If wrFlag==0, then the cursor can only be used for reading.
36115 ** If wrFlag==1, then the cursor can be used for reading or for
36116 ** writing if other conditions for writing are also met.  These
36117 ** are the conditions that must be met in order for writing to
36118 ** be allowed:
36119 **
36120 ** 1:  The cursor must have been opened with wrFlag==1
36121 **
36122 ** 2:  Other database connections that share the same pager cache
36123 **     but which are not in the READ_UNCOMMITTED state may not have
36124 **     cursors open with wrFlag==0 on the same table.  Otherwise
36125 **     the changes made by this write cursor would be visible to
36126 **     the read cursors in the other database connection.
36127 **
36128 ** 3:  The database must be writable (not on read-only media)
36129 **
36130 ** 4:  There must be an active transaction.
36131 **
36132 ** No checking is done to make sure that page iTable really is the
36133 ** root page of a b-tree.  If it is not, then the cursor acquired
36134 ** will not work correctly.
36135 */
36136 static int btreeCursor(
36137   Btree *p,                              /* The btree */
36138   int iTable,                            /* Root page of table to open */
36139   int wrFlag,                            /* 1 to write. 0 read-only */
36140   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
36141   BtCursor *pCur                         /* Space for new cursor */
36142 ){
36143   int rc;
36144   BtShared *pBt = p->pBt;
36145
36146   assert( sqlite3BtreeHoldsMutex(p) );
36147   if( wrFlag ){
36148     if( pBt->readOnly ){
36149       return SQLITE_READONLY;
36150     }
36151     if( checkReadLocks(p, iTable, 0, 0) ){
36152       return SQLITE_LOCKED;
36153     }
36154   }
36155
36156   if( pBt->pPage1==0 ){
36157     rc = lockBtreeWithRetry(p);
36158     if( rc!=SQLITE_OK ){
36159       return rc;
36160     }
36161     if( pBt->readOnly && wrFlag ){
36162       return SQLITE_READONLY;
36163     }
36164   }
36165   pCur->pgnoRoot = (Pgno)iTable;
36166   if( iTable==1 && pagerPagecount(pBt->pPager)==0 ){
36167     rc = SQLITE_EMPTY;
36168     goto create_cursor_exception;
36169   }
36170   rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->pPage, 0);
36171   if( rc!=SQLITE_OK ){
36172     goto create_cursor_exception;
36173   }
36174
36175   /* Now that no other errors can occur, finish filling in the BtCursor
36176   ** variables, link the cursor into the BtShared list and set *ppCur (the
36177   ** output argument to this function).
36178   */
36179   pCur->pKeyInfo = pKeyInfo;
36180   pCur->pBtree = p;
36181   pCur->pBt = pBt;
36182   pCur->wrFlag = wrFlag;
36183   pCur->pNext = pBt->pCursor;
36184   if( pCur->pNext ){
36185     pCur->pNext->pPrev = pCur;
36186   }
36187   pBt->pCursor = pCur;
36188   pCur->eState = CURSOR_INVALID;
36189
36190   return SQLITE_OK;
36191
36192 create_cursor_exception:
36193   releasePage(pCur->pPage);
36194   unlockBtreeIfUnused(pBt);
36195   return rc;
36196 }
36197 SQLITE_PRIVATE int sqlite3BtreeCursor(
36198   Btree *p,                                   /* The btree */
36199   int iTable,                                 /* Root page of table to open */
36200   int wrFlag,                                 /* 1 to write. 0 read-only */
36201   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
36202   BtCursor *pCur                              /* Write new cursor here */
36203 ){
36204   int rc;
36205   sqlite3BtreeEnter(p);
36206   p->pBt->db = p->db;
36207   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
36208   sqlite3BtreeLeave(p);
36209   return rc;
36210 }
36211 SQLITE_PRIVATE int sqlite3BtreeCursorSize(){
36212   return sizeof(BtCursor);
36213 }
36214
36215
36216
36217 /*
36218 ** Close a cursor.  The read lock on the database file is released
36219 ** when the last cursor is closed.
36220 */
36221 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
36222   Btree *pBtree = pCur->pBtree;
36223   if( pBtree ){
36224     BtShared *pBt = pCur->pBt;
36225     sqlite3BtreeEnter(pBtree);
36226     pBt->db = pBtree->db;
36227     clearCursorPosition(pCur);
36228     if( pCur->pPrev ){
36229       pCur->pPrev->pNext = pCur->pNext;
36230     }else{
36231       pBt->pCursor = pCur->pNext;
36232     }
36233     if( pCur->pNext ){
36234       pCur->pNext->pPrev = pCur->pPrev;
36235     }
36236     releasePage(pCur->pPage);
36237     unlockBtreeIfUnused(pBt);
36238     invalidateOverflowCache(pCur);
36239     /* sqlite3_free(pCur); */
36240     sqlite3BtreeLeave(pBtree);
36241   }
36242   return SQLITE_OK;
36243 }
36244
36245 /*
36246 ** Make a temporary cursor by filling in the fields of pTempCur.
36247 ** The temporary cursor is not on the cursor list for the Btree.
36248 */
36249 SQLITE_PRIVATE void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur){
36250   assert( cursorHoldsMutex(pCur) );
36251   memcpy(pTempCur, pCur, sizeof(*pCur));
36252   pTempCur->pNext = 0;
36253   pTempCur->pPrev = 0;
36254   if( pTempCur->pPage ){
36255     sqlite3PagerRef(pTempCur->pPage->pDbPage);
36256   }
36257 }
36258
36259 /*
36260 ** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
36261 ** function above.
36262 */
36263 SQLITE_PRIVATE void sqlite3BtreeReleaseTempCursor(BtCursor *pCur){
36264   assert( cursorHoldsMutex(pCur) );
36265   if( pCur->pPage ){
36266     sqlite3PagerUnref(pCur->pPage->pDbPage);
36267   }
36268 }
36269
36270 /*
36271 ** Make sure the BtCursor* given in the argument has a valid
36272 ** BtCursor.info structure.  If it is not already valid, call
36273 ** sqlite3BtreeParseCell() to fill it in.
36274 **
36275 ** BtCursor.info is a cache of the information in the current cell.
36276 ** Using this cache reduces the number of calls to sqlite3BtreeParseCell().
36277 **
36278 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
36279 ** compiler to crash when getCellInfo() is implemented as a macro.
36280 ** But there is a measureable speed advantage to using the macro on gcc
36281 ** (when less compiler optimizations like -Os or -O0 are used and the
36282 ** compiler is not doing agressive inlining.)  So we use a real function
36283 ** for MSVC and a macro for everything else.  Ticket #2457.
36284 */
36285 #ifndef NDEBUG
36286   static void assertCellInfo(BtCursor *pCur){
36287     CellInfo info;
36288     memset(&info, 0, sizeof(info));
36289     sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &info);
36290     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
36291   }
36292 #else
36293   #define assertCellInfo(x)
36294 #endif
36295 #ifdef _MSC_VER
36296   /* Use a real function in MSVC to work around bugs in that compiler. */
36297   static void getCellInfo(BtCursor *pCur){
36298     if( pCur->info.nSize==0 ){
36299       sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &pCur->info);
36300       pCur->validNKey = 1;
36301     }else{
36302       assertCellInfo(pCur);
36303     }
36304   }
36305 #else /* if not _MSC_VER */
36306   /* Use a macro in all other compilers so that the function is inlined */
36307 #define getCellInfo(pCur)                                               \
36308   if( pCur->info.nSize==0 ){                                            \
36309     sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &pCur->info);         \
36310     pCur->validNKey = 1;                                                \
36311   }else{                                                                \
36312     assertCellInfo(pCur);                                               \
36313   }
36314 #endif /* _MSC_VER */
36315
36316 /*
36317 ** Set *pSize to the size of the buffer needed to hold the value of
36318 ** the key for the current entry.  If the cursor is not pointing
36319 ** to a valid entry, *pSize is set to 0. 
36320 **
36321 ** For a table with the INTKEY flag set, this routine returns the key
36322 ** itself, not the number of bytes in the key.
36323 */
36324 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
36325   int rc;
36326
36327   assert( cursorHoldsMutex(pCur) );
36328   rc = restoreCursorPosition(pCur);
36329   if( rc==SQLITE_OK ){
36330     assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
36331     if( pCur->eState==CURSOR_INVALID ){
36332       *pSize = 0;
36333     }else{
36334       getCellInfo(pCur);
36335       *pSize = pCur->info.nKey;
36336     }
36337   }
36338   return rc;
36339 }
36340
36341 /*
36342 ** Set *pSize to the number of bytes of data in the entry the
36343 ** cursor currently points to.  Always return SQLITE_OK.
36344 ** Failure is not possible.  If the cursor is not currently
36345 ** pointing to an entry (which can happen, for example, if
36346 ** the database is empty) then *pSize is set to 0.
36347 */
36348 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
36349   int rc;
36350
36351   assert( cursorHoldsMutex(pCur) );
36352   rc = restoreCursorPosition(pCur);
36353   if( rc==SQLITE_OK ){
36354     assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
36355     if( pCur->eState==CURSOR_INVALID ){
36356       /* Not pointing at a valid entry - set *pSize to 0. */
36357       *pSize = 0;
36358     }else{
36359       getCellInfo(pCur);
36360       *pSize = pCur->info.nData;
36361     }
36362   }
36363   return rc;
36364 }
36365
36366 /*
36367 ** Given the page number of an overflow page in the database (parameter
36368 ** ovfl), this function finds the page number of the next page in the 
36369 ** linked list of overflow pages. If possible, it uses the auto-vacuum
36370 ** pointer-map data instead of reading the content of page ovfl to do so. 
36371 **
36372 ** If an error occurs an SQLite error code is returned. Otherwise:
36373 **
36374 ** Unless pPgnoNext is NULL, the page number of the next overflow 
36375 ** page in the linked list is written to *pPgnoNext. If page ovfl
36376 ** is the last page in its linked list, *pPgnoNext is set to zero. 
36377 **
36378 ** If ppPage is not NULL, *ppPage is set to the MemPage* handle
36379 ** for page ovfl. The underlying pager page may have been requested
36380 ** with the noContent flag set, so the page data accessable via
36381 ** this handle may not be trusted.
36382 */
36383 static int getOverflowPage(
36384   BtShared *pBt, 
36385   Pgno ovfl,                   /* Overflow page */
36386   MemPage **ppPage,            /* OUT: MemPage handle */
36387   Pgno *pPgnoNext              /* OUT: Next overflow page number */
36388 ){
36389   Pgno next = 0;
36390   int rc;
36391
36392   assert( sqlite3_mutex_held(pBt->mutex) );
36393   /* One of these must not be NULL. Otherwise, why call this function? */
36394   assert(ppPage || pPgnoNext);
36395
36396   /* If pPgnoNext is NULL, then this function is being called to obtain
36397   ** a MemPage* reference only. No page-data is required in this case.
36398   */
36399   if( !pPgnoNext ){
36400     return sqlite3BtreeGetPage(pBt, ovfl, ppPage, 1);
36401   }
36402
36403 #ifndef SQLITE_OMIT_AUTOVACUUM
36404   /* Try to find the next page in the overflow list using the
36405   ** autovacuum pointer-map pages. Guess that the next page in 
36406   ** the overflow list is page number (ovfl+1). If that guess turns 
36407   ** out to be wrong, fall back to loading the data of page 
36408   ** number ovfl to determine the next page number.
36409   */
36410   if( pBt->autoVacuum ){
36411     Pgno pgno;
36412     Pgno iGuess = ovfl+1;
36413     u8 eType;
36414
36415     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
36416       iGuess++;
36417     }
36418
36419     if( iGuess<=pagerPagecount(pBt->pPager) ){
36420       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
36421       if( rc!=SQLITE_OK ){
36422         return rc;
36423       }
36424       if( eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
36425         next = iGuess;
36426       }
36427     }
36428   }
36429 #endif
36430
36431   if( next==0 || ppPage ){
36432     MemPage *pPage = 0;
36433
36434     rc = sqlite3BtreeGetPage(pBt, ovfl, &pPage, next!=0);
36435     assert(rc==SQLITE_OK || pPage==0);
36436     if( next==0 && rc==SQLITE_OK ){
36437       next = get4byte(pPage->aData);
36438     }
36439
36440     if( ppPage ){
36441       *ppPage = pPage;
36442     }else{
36443       releasePage(pPage);
36444     }
36445   }
36446   *pPgnoNext = next;
36447
36448   return rc;
36449 }
36450
36451 /*
36452 ** Copy data from a buffer to a page, or from a page to a buffer.
36453 **
36454 ** pPayload is a pointer to data stored on database page pDbPage.
36455 ** If argument eOp is false, then nByte bytes of data are copied
36456 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
36457 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
36458 ** of data are copied from the buffer pBuf to pPayload.
36459 **
36460 ** SQLITE_OK is returned on success, otherwise an error code.
36461 */
36462 static int copyPayload(
36463   void *pPayload,           /* Pointer to page data */
36464   void *pBuf,               /* Pointer to buffer */
36465   int nByte,                /* Number of bytes to copy */
36466   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
36467   DbPage *pDbPage           /* Page containing pPayload */
36468 ){
36469   if( eOp ){
36470     /* Copy data from buffer to page (a write operation) */
36471     int rc = sqlite3PagerWrite(pDbPage);
36472     if( rc!=SQLITE_OK ){
36473       return rc;
36474     }
36475     memcpy(pPayload, pBuf, nByte);
36476   }else{
36477     /* Copy data from page to buffer (a read operation) */
36478     memcpy(pBuf, pPayload, nByte);
36479   }
36480   return SQLITE_OK;
36481 }
36482
36483 /*
36484 ** This function is used to read or overwrite payload information
36485 ** for the entry that the pCur cursor is pointing to. If the eOp
36486 ** parameter is 0, this is a read operation (data copied into
36487 ** buffer pBuf). If it is non-zero, a write (data copied from
36488 ** buffer pBuf).
36489 **
36490 ** A total of "amt" bytes are read or written beginning at "offset".
36491 ** Data is read to or from the buffer pBuf.
36492 **
36493 ** This routine does not make a distinction between key and data.
36494 ** It just reads or writes bytes from the payload area.  Data might 
36495 ** appear on the main page or be scattered out on multiple overflow 
36496 ** pages.
36497 **
36498 ** If the BtCursor.isIncrblobHandle flag is set, and the current
36499 ** cursor entry uses one or more overflow pages, this function
36500 ** allocates space for and lazily popluates the overflow page-list 
36501 ** cache array (BtCursor.aOverflow). Subsequent calls use this
36502 ** cache to make seeking to the supplied offset more efficient.
36503 **
36504 ** Once an overflow page-list cache has been allocated, it may be
36505 ** invalidated if some other cursor writes to the same table, or if
36506 ** the cursor is moved to a different row. Additionally, in auto-vacuum
36507 ** mode, the following events may invalidate an overflow page-list cache.
36508 **
36509 **   * An incremental vacuum,
36510 **   * A commit in auto_vacuum="full" mode,
36511 **   * Creating a table (may require moving an overflow page).
36512 */
36513 static int accessPayload(
36514   BtCursor *pCur,      /* Cursor pointing to entry to read from */
36515   int offset,          /* Begin reading this far into payload */
36516   int amt,             /* Read this many bytes */
36517   unsigned char *pBuf, /* Write the bytes into this buffer */ 
36518   int skipKey,         /* offset begins at data if this is true */
36519   int eOp              /* zero to read. non-zero to write. */
36520 ){
36521   unsigned char *aPayload;
36522   int rc = SQLITE_OK;
36523   u32 nKey;
36524   int iIdx = 0;
36525   MemPage *pPage = pCur->pPage;     /* Btree page of current cursor entry */
36526   BtShared *pBt;                   /* Btree this cursor belongs to */
36527
36528   assert( pPage );
36529   assert( pCur->eState==CURSOR_VALID );
36530   assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
36531   assert( offset>=0 );
36532   assert( cursorHoldsMutex(pCur) );
36533
36534   getCellInfo(pCur);
36535   aPayload = pCur->info.pCell + pCur->info.nHeader;
36536   nKey = (pPage->intKey ? 0 : pCur->info.nKey);
36537
36538   if( skipKey ){
36539     offset += nKey;
36540   }
36541   if( offset+amt > nKey+pCur->info.nData ){
36542     /* Trying to read or write past the end of the data is an error */
36543     return SQLITE_CORRUPT_BKPT;
36544   }
36545
36546   /* Check if data must be read/written to/from the btree page itself. */
36547   if( offset<pCur->info.nLocal ){
36548     int a = amt;
36549     if( a+offset>pCur->info.nLocal ){
36550       a = pCur->info.nLocal - offset;
36551     }
36552     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
36553     offset = 0;
36554     pBuf += a;
36555     amt -= a;
36556   }else{
36557     offset -= pCur->info.nLocal;
36558   }
36559
36560   pBt = pCur->pBt;
36561   if( rc==SQLITE_OK && amt>0 ){
36562     const int ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
36563     Pgno nextPage;
36564
36565     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
36566
36567 #ifndef SQLITE_OMIT_INCRBLOB
36568     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
36569     ** has not been allocated, allocate it now. The array is sized at
36570     ** one entry for each overflow page in the overflow chain. The
36571     ** page number of the first overflow page is stored in aOverflow[0],
36572     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
36573     ** (the cache is lazily populated).
36574     */
36575     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
36576       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
36577       pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
36578       if( nOvfl && !pCur->aOverflow ){
36579         rc = SQLITE_NOMEM;
36580       }
36581     }
36582
36583     /* If the overflow page-list cache has been allocated and the
36584     ** entry for the first required overflow page is valid, skip
36585     ** directly to it.
36586     */
36587     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
36588       iIdx = (offset/ovflSize);
36589       nextPage = pCur->aOverflow[iIdx];
36590       offset = (offset%ovflSize);
36591     }
36592 #endif
36593
36594     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
36595
36596 #ifndef SQLITE_OMIT_INCRBLOB
36597       /* If required, populate the overflow page-list cache. */
36598       if( pCur->aOverflow ){
36599         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
36600         pCur->aOverflow[iIdx] = nextPage;
36601       }
36602 #endif
36603
36604       if( offset>=ovflSize ){
36605         /* The only reason to read this page is to obtain the page
36606         ** number for the next page in the overflow chain. The page
36607         ** data is not required. So first try to lookup the overflow
36608         ** page-list cache, if any, then fall back to the getOverflowPage()
36609         ** function.
36610         */
36611 #ifndef SQLITE_OMIT_INCRBLOB
36612         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
36613           nextPage = pCur->aOverflow[iIdx+1];
36614         } else 
36615 #endif
36616           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
36617         offset -= ovflSize;
36618       }else{
36619         /* Need to read this page properly. It contains some of the
36620         ** range of data that is being read (eOp==0) or written (eOp!=0).
36621         */
36622         DbPage *pDbPage;
36623         int a = amt;
36624         rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
36625         if( rc==SQLITE_OK ){
36626           aPayload = sqlite3PagerGetData(pDbPage);
36627           nextPage = get4byte(aPayload);
36628           if( a + offset > ovflSize ){
36629             a = ovflSize - offset;
36630           }
36631           rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
36632           sqlite3PagerUnref(pDbPage);
36633           offset = 0;
36634           amt -= a;
36635           pBuf += a;
36636         }
36637       }
36638     }
36639   }
36640
36641   if( rc==SQLITE_OK && amt>0 ){
36642     return SQLITE_CORRUPT_BKPT;
36643   }
36644   return rc;
36645 }
36646
36647 /*
36648 ** Read part of the key associated with cursor pCur.  Exactly
36649 ** "amt" bytes will be transfered into pBuf[].  The transfer
36650 ** begins at "offset".
36651 **
36652 ** Return SQLITE_OK on success or an error code if anything goes
36653 ** wrong.  An error is returned if "offset+amt" is larger than
36654 ** the available payload.
36655 */
36656 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
36657   int rc;
36658
36659   assert( cursorHoldsMutex(pCur) );
36660   rc = restoreCursorPosition(pCur);
36661   if( rc==SQLITE_OK ){
36662     assert( pCur->eState==CURSOR_VALID );
36663     assert( pCur->pPage!=0 );
36664     if( pCur->pPage->intKey ){
36665       return SQLITE_CORRUPT_BKPT;
36666     }
36667     assert( pCur->pPage->intKey==0 );
36668     assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
36669     rc = accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0, 0);
36670   }
36671   return rc;
36672 }
36673
36674 /*
36675 ** Read part of the data associated with cursor pCur.  Exactly
36676 ** "amt" bytes will be transfered into pBuf[].  The transfer
36677 ** begins at "offset".
36678 **
36679 ** Return SQLITE_OK on success or an error code if anything goes
36680 ** wrong.  An error is returned if "offset+amt" is larger than
36681 ** the available payload.
36682 */
36683 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
36684   int rc;
36685
36686 #ifndef SQLITE_OMIT_INCRBLOB
36687   if ( pCur->eState==CURSOR_INVALID ){
36688     return SQLITE_ABORT;
36689   }
36690 #endif
36691
36692   assert( cursorHoldsMutex(pCur) );
36693   rc = restoreCursorPosition(pCur);
36694   if( rc==SQLITE_OK ){
36695     assert( pCur->eState==CURSOR_VALID );
36696     assert( pCur->pPage!=0 );
36697     assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
36698     rc = accessPayload(pCur, offset, amt, pBuf, 1, 0);
36699   }
36700   return rc;
36701 }
36702
36703 /*
36704 ** Return a pointer to payload information from the entry that the 
36705 ** pCur cursor is pointing to.  The pointer is to the beginning of
36706 ** the key if skipKey==0 and it points to the beginning of data if
36707 ** skipKey==1.  The number of bytes of available key/data is written
36708 ** into *pAmt.  If *pAmt==0, then the value returned will not be
36709 ** a valid pointer.
36710 **
36711 ** This routine is an optimization.  It is common for the entire key
36712 ** and data to fit on the local page and for there to be no overflow
36713 ** pages.  When that is so, this routine can be used to access the
36714 ** key and data without making a copy.  If the key and/or data spills
36715 ** onto overflow pages, then accessPayload() must be used to reassembly
36716 ** the key/data and copy it into a preallocated buffer.
36717 **
36718 ** The pointer returned by this routine looks directly into the cached
36719 ** page of the database.  The data might change or move the next time
36720 ** any btree routine is called.
36721 */
36722 static const unsigned char *fetchPayload(
36723   BtCursor *pCur,      /* Cursor pointing to entry to read from */
36724   int *pAmt,           /* Write the number of available bytes here */
36725   int skipKey          /* read beginning at data if this is true */
36726 ){
36727   unsigned char *aPayload;
36728   MemPage *pPage;
36729   u32 nKey;
36730   int nLocal;
36731
36732   assert( pCur!=0 && pCur->pPage!=0 );
36733   assert( pCur->eState==CURSOR_VALID );
36734   assert( cursorHoldsMutex(pCur) );
36735   pPage = pCur->pPage;
36736   assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
36737   getCellInfo(pCur);
36738   aPayload = pCur->info.pCell;
36739   aPayload += pCur->info.nHeader;
36740   if( pPage->intKey ){
36741     nKey = 0;
36742   }else{
36743     nKey = pCur->info.nKey;
36744   }
36745   if( skipKey ){
36746     aPayload += nKey;
36747     nLocal = pCur->info.nLocal - nKey;
36748   }else{
36749     nLocal = pCur->info.nLocal;
36750     if( nLocal>nKey ){
36751       nLocal = nKey;
36752     }
36753   }
36754   *pAmt = nLocal;
36755   return aPayload;
36756 }
36757
36758
36759 /*
36760 ** For the entry that cursor pCur is point to, return as
36761 ** many bytes of the key or data as are available on the local
36762 ** b-tree page.  Write the number of available bytes into *pAmt.
36763 **
36764 ** The pointer returned is ephemeral.  The key/data may move
36765 ** or be destroyed on the next call to any Btree routine,
36766 ** including calls from other threads against the same cache.
36767 ** Hence, a mutex on the BtShared should be held prior to calling
36768 ** this routine.
36769 **
36770 ** These routines is used to get quick access to key and data
36771 ** in the common case where no overflow pages are used.
36772 */
36773 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
36774   assert( cursorHoldsMutex(pCur) );
36775   if( pCur->eState==CURSOR_VALID ){
36776     return (const void*)fetchPayload(pCur, pAmt, 0);
36777   }
36778   return 0;
36779 }
36780 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
36781   assert( cursorHoldsMutex(pCur) );
36782   if( pCur->eState==CURSOR_VALID ){
36783     return (const void*)fetchPayload(pCur, pAmt, 1);
36784   }
36785   return 0;
36786 }
36787
36788
36789 /*
36790 ** Move the cursor down to a new child page.  The newPgno argument is the
36791 ** page number of the child page to move to.
36792 */
36793 static int moveToChild(BtCursor *pCur, u32 newPgno){
36794   int rc;
36795   MemPage *pNewPage;
36796   MemPage *pOldPage;
36797   BtShared *pBt = pCur->pBt;
36798
36799   assert( cursorHoldsMutex(pCur) );
36800   assert( pCur->eState==CURSOR_VALID );
36801   rc = getAndInitPage(pBt, newPgno, &pNewPage, pCur->pPage);
36802   if( rc ) return rc;
36803   pNewPage->idxParent = pCur->idx;
36804   pOldPage = pCur->pPage;
36805   pOldPage->idxShift = 0;
36806   releasePage(pOldPage);
36807   pCur->pPage = pNewPage;
36808   pCur->idx = 0;
36809   pCur->info.nSize = 0;
36810   pCur->validNKey = 0;
36811   if( pNewPage->nCell<1 ){
36812     return SQLITE_CORRUPT_BKPT;
36813   }
36814   return SQLITE_OK;
36815 }
36816
36817 /*
36818 ** Return true if the page is the virtual root of its table.
36819 **
36820 ** The virtual root page is the root page for most tables.  But
36821 ** for the table rooted on page 1, sometime the real root page
36822 ** is empty except for the right-pointer.  In such cases the
36823 ** virtual root page is the page that the right-pointer of page
36824 ** 1 is pointing to.
36825 */
36826 SQLITE_PRIVATE int sqlite3BtreeIsRootPage(MemPage *pPage){
36827   MemPage *pParent;
36828
36829   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
36830   pParent = pPage->pParent;
36831   if( pParent==0 ) return 1;
36832   if( pParent->pgno>1 ) return 0;
36833   if( get2byte(&pParent->aData[pParent->hdrOffset+3])==0 ) return 1;
36834   return 0;
36835 }
36836
36837 /*
36838 ** Move the cursor up to the parent page.
36839 **
36840 ** pCur->idx is set to the cell index that contains the pointer
36841 ** to the page we are coming from.  If we are coming from the
36842 ** right-most child page then pCur->idx is set to one more than
36843 ** the largest cell index.
36844 */
36845 SQLITE_PRIVATE void sqlite3BtreeMoveToParent(BtCursor *pCur){
36846   MemPage *pParent;
36847   MemPage *pPage;
36848   int idxParent;
36849
36850   assert( cursorHoldsMutex(pCur) );
36851   assert( pCur->eState==CURSOR_VALID );
36852   pPage = pCur->pPage;
36853   assert( pPage!=0 );
36854   assert( !sqlite3BtreeIsRootPage(pPage) );
36855   pParent = pPage->pParent;
36856   assert( pParent!=0 );
36857   assert( pPage->pDbPage->nRef>0 );
36858   idxParent = pPage->idxParent;
36859   sqlite3PagerRef(pParent->pDbPage);
36860   releasePage(pPage);
36861   pCur->pPage = pParent;
36862   pCur->info.nSize = 0;
36863   pCur->validNKey = 0;
36864   assert( pParent->idxShift==0 );
36865   pCur->idx = idxParent;
36866 }
36867
36868 /*
36869 ** Move the cursor to the root page
36870 */
36871 static int moveToRoot(BtCursor *pCur){
36872   MemPage *pRoot;
36873   int rc = SQLITE_OK;
36874   Btree *p = pCur->pBtree;
36875   BtShared *pBt = p->pBt;
36876
36877   assert( cursorHoldsMutex(pCur) );
36878   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
36879   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
36880   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
36881   if( pCur->eState>=CURSOR_REQUIRESEEK ){
36882     if( pCur->eState==CURSOR_FAULT ){
36883       return pCur->skip;
36884     }
36885     clearCursorPosition(pCur);
36886   }
36887   pRoot = pCur->pPage;
36888   if( pRoot && pRoot->isInit ){
36889     /* If the page the cursor is currently pointing to is fully initialized,
36890     ** then the root page can be found by following the MemPage.pParent
36891     ** pointers. This is faster than requesting a reference to the root
36892     ** page from the pager layer.
36893     */
36894     while( pRoot->pParent ){
36895       assert( pRoot->isInit==PAGE_ISINIT_FULL );
36896       pRoot = pRoot->pParent;
36897     }
36898     assert( pRoot->isInit==PAGE_ISINIT_FULL );
36899     if( pRoot!=pCur->pPage ){
36900       sqlite3PagerRef(pRoot->pDbPage);
36901       releasePage(pCur->pPage);
36902       pCur->pPage = pRoot;
36903     }
36904   }else{
36905     if( 
36906       SQLITE_OK!=(rc = getAndInitPage(pBt, pCur->pgnoRoot, &pRoot, 0))
36907     ){
36908       pCur->eState = CURSOR_INVALID;
36909       return rc;
36910     }
36911     releasePage(pCur->pPage);
36912     pCur->pPage = pRoot;
36913   }
36914   assert( pCur->pPage->pgno==pCur->pgnoRoot );
36915   pCur->idx = 0;
36916   pCur->info.nSize = 0;
36917   pCur->atLast = 0;
36918   pCur->validNKey = 0;
36919   if( pRoot->nCell==0 && !pRoot->leaf ){
36920     Pgno subpage;
36921     assert( pRoot->pgno==1 );
36922     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
36923     assert( subpage>0 );
36924     pCur->eState = CURSOR_VALID;
36925     rc = moveToChild(pCur, subpage);
36926   }
36927   pCur->eState = ((pCur->pPage->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
36928   return rc;
36929 }
36930
36931 /*
36932 ** Move the cursor down to the left-most leaf entry beneath the
36933 ** entry to which it is currently pointing.
36934 **
36935 ** The left-most leaf is the one with the smallest key - the first
36936 ** in ascending order.
36937 */
36938 static int moveToLeftmost(BtCursor *pCur){
36939   Pgno pgno;
36940   int rc = SQLITE_OK;
36941   MemPage *pPage;
36942
36943   assert( cursorHoldsMutex(pCur) );
36944   assert( pCur->eState==CURSOR_VALID );
36945   while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
36946     assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
36947     pgno = get4byte(findCell(pPage, pCur->idx));
36948     rc = moveToChild(pCur, pgno);
36949   }
36950   return rc;
36951 }
36952
36953 /*
36954 ** Move the cursor down to the right-most leaf entry beneath the
36955 ** page to which it is currently pointing.  Notice the difference
36956 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
36957 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
36958 ** finds the right-most entry beneath the *page*.
36959 **
36960 ** The right-most entry is the one with the largest key - the last
36961 ** key in ascending order.
36962 */
36963 static int moveToRightmost(BtCursor *pCur){
36964   Pgno pgno;
36965   int rc = SQLITE_OK;
36966   MemPage *pPage;
36967
36968   assert( cursorHoldsMutex(pCur) );
36969   assert( pCur->eState==CURSOR_VALID );
36970   while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
36971     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
36972     pCur->idx = pPage->nCell;
36973     rc = moveToChild(pCur, pgno);
36974   }
36975   if( rc==SQLITE_OK ){
36976     pCur->idx = pPage->nCell - 1;
36977     pCur->info.nSize = 0;
36978     pCur->validNKey = 0;
36979   }
36980   return rc;
36981 }
36982
36983 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
36984 ** on success.  Set *pRes to 0 if the cursor actually points to something
36985 ** or set *pRes to 1 if the table is empty.
36986 */
36987 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
36988   int rc;
36989
36990   assert( cursorHoldsMutex(pCur) );
36991   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
36992   rc = moveToRoot(pCur);
36993   if( rc==SQLITE_OK ){
36994     if( pCur->eState==CURSOR_INVALID ){
36995       assert( pCur->pPage->nCell==0 );
36996       *pRes = 1;
36997       rc = SQLITE_OK;
36998     }else{
36999       assert( pCur->pPage->nCell>0 );
37000       *pRes = 0;
37001       rc = moveToLeftmost(pCur);
37002     }
37003   }
37004   return rc;
37005 }
37006
37007 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
37008 ** on success.  Set *pRes to 0 if the cursor actually points to something
37009 ** or set *pRes to 1 if the table is empty.
37010 */
37011 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
37012   int rc;
37013  
37014   assert( cursorHoldsMutex(pCur) );
37015   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
37016   rc = moveToRoot(pCur);
37017   if( rc==SQLITE_OK ){
37018     if( CURSOR_INVALID==pCur->eState ){
37019       assert( pCur->pPage->nCell==0 );
37020       *pRes = 1;
37021     }else{
37022       assert( pCur->eState==CURSOR_VALID );
37023       *pRes = 0;
37024       rc = moveToRightmost(pCur);
37025       getCellInfo(pCur);
37026       pCur->atLast = rc==SQLITE_OK;
37027     }
37028   }
37029   return rc;
37030 }
37031
37032 /* Move the cursor so that it points to an entry near the key 
37033 ** specified by pIdxKey or intKey.   Return a success code.
37034 **
37035 ** For INTKEY tables, the intKey parameter is used.  pIdxKey 
37036 ** must be NULL.  For index tables, pIdxKey is used and intKey
37037 ** is ignored.
37038 **
37039 ** If an exact match is not found, then the cursor is always
37040 ** left pointing at a leaf page which would hold the entry if it
37041 ** were present.  The cursor might point to an entry that comes
37042 ** before or after the key.
37043 **
37044 ** The result of comparing the key with the entry to which the
37045 ** cursor is written to *pRes if pRes!=NULL.  The meaning of
37046 ** this value is as follows:
37047 **
37048 **     *pRes<0      The cursor is left pointing at an entry that
37049 **                  is smaller than pKey or if the table is empty
37050 **                  and the cursor is therefore left point to nothing.
37051 **
37052 **     *pRes==0     The cursor is left pointing at an entry that
37053 **                  exactly matches pKey.
37054 **
37055 **     *pRes>0      The cursor is left pointing at an entry that
37056 **                  is larger than pKey.
37057 **
37058 */
37059 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
37060   BtCursor *pCur,          /* The cursor to be moved */
37061   UnpackedRecord *pIdxKey, /* Unpacked index key */
37062   i64 intKey,              /* The table key */
37063   int biasRight,           /* If true, bias the search to the high end */
37064   int *pRes                /* Write search results here */
37065 ){
37066   int rc;
37067
37068   assert( cursorHoldsMutex(pCur) );
37069   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
37070
37071   /* If the cursor is already positioned at the point we are trying
37072   ** to move to, then just return without doing any work */
37073   if( pCur->eState==CURSOR_VALID && pCur->validNKey && pCur->pPage->intKey ){
37074     if( pCur->info.nKey==intKey ){
37075       *pRes = 0;
37076       return SQLITE_OK;
37077     }
37078     if( pCur->atLast && pCur->info.nKey<intKey ){
37079       *pRes = -1;
37080       return SQLITE_OK;
37081     }
37082   }
37083
37084   rc = moveToRoot(pCur);
37085   if( rc ){
37086     return rc;
37087   }
37088   assert( pCur->pPage );
37089   assert( pCur->pPage->isInit==PAGE_ISINIT_FULL );
37090   if( pCur->eState==CURSOR_INVALID ){
37091     *pRes = -1;
37092     assert( pCur->pPage->nCell==0 );
37093     return SQLITE_OK;
37094   }
37095   assert( pCur->pPage->intKey || pIdxKey );
37096   for(;;){
37097     int lwr, upr;
37098     Pgno chldPg;
37099     MemPage *pPage = pCur->pPage;
37100     int c = -1;  /* pRes return if table is empty must be -1 */
37101     lwr = 0;
37102     upr = pPage->nCell-1;
37103     if( !pPage->intKey && pIdxKey==0 ){
37104       rc = SQLITE_CORRUPT_BKPT;
37105       goto moveto_finish;
37106     }
37107     if( biasRight ){
37108       pCur->idx = upr;
37109     }else{
37110       pCur->idx = (upr+lwr)/2;
37111     }
37112     if( lwr<=upr ) for(;;){
37113       void *pCellKey;
37114       i64 nCellKey;
37115       pCur->info.nSize = 0;
37116       pCur->validNKey = 1;
37117       if( pPage->intKey ){
37118         u8 *pCell;
37119         pCell = findCell(pPage, pCur->idx) + pPage->childPtrSize;
37120         if( pPage->hasData ){
37121           u32 dummy;
37122           pCell += getVarint32(pCell, dummy);
37123         }
37124         getVarint(pCell, (u64*)&nCellKey);
37125         if( nCellKey==intKey ){
37126           c = 0;
37127         }else if( nCellKey<intKey ){
37128           c = -1;
37129         }else{
37130           assert( nCellKey>intKey );
37131           c = +1;
37132         }
37133       }else{
37134         int available;
37135         pCellKey = (void *)fetchPayload(pCur, &available, 0);
37136         nCellKey = pCur->info.nKey;
37137         if( available>=nCellKey ){
37138           c = sqlite3VdbeRecordCompare(nCellKey, pCellKey, pIdxKey);
37139         }else{
37140           pCellKey = sqlite3Malloc( nCellKey );
37141           if( pCellKey==0 ){
37142             rc = SQLITE_NOMEM;
37143             goto moveto_finish;
37144           }
37145           rc = sqlite3BtreeKey(pCur, 0, nCellKey, (void *)pCellKey);
37146           c = sqlite3VdbeRecordCompare(nCellKey, pCellKey, pIdxKey);
37147           sqlite3_free(pCellKey);
37148           if( rc ) goto moveto_finish;
37149         }
37150       }
37151       if( c==0 ){
37152         pCur->info.nKey = nCellKey;
37153         if( pPage->intKey && !pPage->leaf ){
37154           lwr = pCur->idx;
37155           upr = lwr - 1;
37156           break;
37157         }else{
37158           if( pRes ) *pRes = 0;
37159           rc = SQLITE_OK;
37160           goto moveto_finish;
37161         }
37162       }
37163       if( c<0 ){
37164         lwr = pCur->idx+1;
37165       }else{
37166         upr = pCur->idx-1;
37167       }
37168       if( lwr>upr ){
37169         pCur->info.nKey = nCellKey;
37170         break;
37171       }
37172       pCur->idx = (lwr+upr)/2;
37173     }
37174     assert( lwr==upr+1 );
37175     assert( pPage->isInit==PAGE_ISINIT_FULL );
37176     if( pPage->leaf ){
37177       chldPg = 0;
37178     }else if( lwr>=pPage->nCell ){
37179       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
37180     }else{
37181       chldPg = get4byte(findCell(pPage, lwr));
37182     }
37183     if( chldPg==0 ){
37184       assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
37185       if( pRes ) *pRes = c;
37186       rc = SQLITE_OK;
37187       goto moveto_finish;
37188     }
37189     pCur->idx = lwr;
37190     pCur->info.nSize = 0;
37191     pCur->validNKey = 0;
37192     rc = moveToChild(pCur, chldPg);
37193     if( rc ) goto moveto_finish;
37194   }
37195 moveto_finish:
37196   return rc;
37197 }
37198
37199 /*
37200 ** In this version of BtreeMoveto, pKey is a packed index record
37201 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
37202 ** record and then call BtreeMovetoUnpacked() to do the work.
37203 */
37204 SQLITE_PRIVATE int sqlite3BtreeMoveto(
37205   BtCursor *pCur,     /* Cursor open on the btree to be searched */
37206   const void *pKey,   /* Packed key if the btree is an index */
37207   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
37208   int bias,           /* Bias search to the high end */
37209   int *pRes           /* Write search results here */
37210 ){
37211   int rc;                    /* Status code */
37212   UnpackedRecord *pIdxKey;   /* Unpacked index key */
37213   UnpackedRecord aSpace[16]; /* Temp space for pIdxKey - to avoid a malloc */
37214
37215   if( pKey ){
37216     pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, nKey, pKey,
37217                                       aSpace, sizeof(aSpace));
37218     if( pIdxKey==0 ) return SQLITE_NOMEM;
37219   }else{
37220     pIdxKey = 0;
37221   }
37222   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
37223   if( pKey ){
37224     sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
37225   }
37226   return rc;
37227 }
37228
37229
37230 /*
37231 ** Return TRUE if the cursor is not pointing at an entry of the table.
37232 **
37233 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
37234 ** past the last entry in the table or sqlite3BtreePrev() moves past
37235 ** the first entry.  TRUE is also returned if the table is empty.
37236 */
37237 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
37238   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
37239   ** have been deleted? This API will need to change to return an error code
37240   ** as well as the boolean result value.
37241   */
37242   return (CURSOR_VALID!=pCur->eState);
37243 }
37244
37245 /*
37246 ** Return the database connection handle for a cursor.
37247 */
37248 SQLITE_PRIVATE sqlite3 *sqlite3BtreeCursorDb(const BtCursor *pCur){
37249   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
37250   return pCur->pBtree->db;
37251 }
37252
37253 /*
37254 ** Advance the cursor to the next entry in the database.  If
37255 ** successful then set *pRes=0.  If the cursor
37256 ** was already pointing to the last entry in the database before
37257 ** this routine was called, then set *pRes=1.
37258 */
37259 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
37260   int rc;
37261   MemPage *pPage;
37262
37263   assert( cursorHoldsMutex(pCur) );
37264   rc = restoreCursorPosition(pCur);
37265   if( rc!=SQLITE_OK ){
37266     return rc;
37267   }
37268   assert( pRes!=0 );
37269   pPage = pCur->pPage;
37270   if( CURSOR_INVALID==pCur->eState ){
37271     *pRes = 1;
37272     return SQLITE_OK;
37273   }
37274   if( pCur->skip>0 ){
37275     pCur->skip = 0;
37276     *pRes = 0;
37277     return SQLITE_OK;
37278   }
37279   pCur->skip = 0;
37280
37281   assert( pPage->isInit==PAGE_ISINIT_FULL );
37282   assert( pCur->idx<pPage->nCell );
37283
37284   pCur->idx++;
37285   pCur->info.nSize = 0;
37286   pCur->validNKey = 0;
37287   if( pCur->idx>=pPage->nCell ){
37288     if( !pPage->leaf ){
37289       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
37290       if( rc ) return rc;
37291       rc = moveToLeftmost(pCur);
37292       *pRes = 0;
37293       return rc;
37294     }
37295     do{
37296       if( sqlite3BtreeIsRootPage(pPage) ){
37297         *pRes = 1;
37298         pCur->eState = CURSOR_INVALID;
37299         return SQLITE_OK;
37300       }
37301       sqlite3BtreeMoveToParent(pCur);
37302       pPage = pCur->pPage;
37303     }while( pCur->idx>=pPage->nCell );
37304     *pRes = 0;
37305     if( pPage->intKey ){
37306       rc = sqlite3BtreeNext(pCur, pRes);
37307     }else{
37308       rc = SQLITE_OK;
37309     }
37310     return rc;
37311   }
37312   *pRes = 0;
37313   if( pPage->leaf ){
37314     return SQLITE_OK;
37315   }
37316   rc = moveToLeftmost(pCur);
37317   return rc;
37318 }
37319
37320
37321 /*
37322 ** Step the cursor to the back to the previous entry in the database.  If
37323 ** successful then set *pRes=0.  If the cursor
37324 ** was already pointing to the first entry in the database before
37325 ** this routine was called, then set *pRes=1.
37326 */
37327 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
37328   int rc;
37329   Pgno pgno;
37330   MemPage *pPage;
37331
37332   assert( cursorHoldsMutex(pCur) );
37333   rc = restoreCursorPosition(pCur);
37334   if( rc!=SQLITE_OK ){
37335     return rc;
37336   }
37337   pCur->atLast = 0;
37338   if( CURSOR_INVALID==pCur->eState ){
37339     *pRes = 1;
37340     return SQLITE_OK;
37341   }
37342   if( pCur->skip<0 ){
37343     pCur->skip = 0;
37344     *pRes = 0;
37345     return SQLITE_OK;
37346   }
37347   pCur->skip = 0;
37348
37349   pPage = pCur->pPage;
37350   assert( pPage->isInit==PAGE_ISINIT_FULL );
37351   assert( pCur->idx>=0 );
37352   if( !pPage->leaf ){
37353     pgno = get4byte( findCell(pPage, pCur->idx) );
37354     rc = moveToChild(pCur, pgno);
37355     if( rc ){
37356       return rc;
37357     }
37358     rc = moveToRightmost(pCur);
37359   }else{
37360     while( pCur->idx==0 ){
37361       if( sqlite3BtreeIsRootPage(pPage) ){
37362         pCur->eState = CURSOR_INVALID;
37363         *pRes = 1;
37364         return SQLITE_OK;
37365       }
37366       sqlite3BtreeMoveToParent(pCur);
37367       pPage = pCur->pPage;
37368     }
37369     pCur->idx--;
37370     pCur->info.nSize = 0;
37371     pCur->validNKey = 0;
37372     if( pPage->intKey && !pPage->leaf ){
37373       rc = sqlite3BtreePrevious(pCur, pRes);
37374     }else{
37375       rc = SQLITE_OK;
37376     }
37377   }
37378   *pRes = 0;
37379   return rc;
37380 }
37381
37382 /*
37383 ** Allocate a new page from the database file.
37384 **
37385 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
37386 ** has already been called on the new page.)  The new page has also
37387 ** been referenced and the calling routine is responsible for calling
37388 ** sqlite3PagerUnref() on the new page when it is done.
37389 **
37390 ** SQLITE_OK is returned on success.  Any other return value indicates
37391 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
37392 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
37393 **
37394 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to 
37395 ** locate a page close to the page number "nearby".  This can be used in an
37396 ** attempt to keep related pages close to each other in the database file,
37397 ** which in turn can make database access faster.
37398 **
37399 ** If the "exact" parameter is not 0, and the page-number nearby exists 
37400 ** anywhere on the free-list, then it is guarenteed to be returned. This
37401 ** is only used by auto-vacuum databases when allocating a new table.
37402 */
37403 static int allocateBtreePage(
37404   BtShared *pBt, 
37405   MemPage **ppPage, 
37406   Pgno *pPgno, 
37407   Pgno nearby,
37408   u8 exact
37409 ){
37410   MemPage *pPage1;
37411   int rc;
37412   int n;     /* Number of pages on the freelist */
37413   int k;     /* Number of leaves on the trunk of the freelist */
37414   MemPage *pTrunk = 0;
37415   MemPage *pPrevTrunk = 0;
37416
37417   assert( sqlite3_mutex_held(pBt->mutex) );
37418   pPage1 = pBt->pPage1;
37419   n = get4byte(&pPage1->aData[36]);
37420   if( n>0 ){
37421     /* There are pages on the freelist.  Reuse one of those pages. */
37422     Pgno iTrunk;
37423     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
37424     
37425     /* If the 'exact' parameter was true and a query of the pointer-map
37426     ** shows that the page 'nearby' is somewhere on the free-list, then
37427     ** the entire-list will be searched for that page.
37428     */
37429 #ifndef SQLITE_OMIT_AUTOVACUUM
37430     if( exact && nearby<=pagerPagecount(pBt->pPager) ){
37431       u8 eType;
37432       assert( nearby>0 );
37433       assert( pBt->autoVacuum );
37434       rc = ptrmapGet(pBt, nearby, &eType, 0);
37435       if( rc ) return rc;
37436       if( eType==PTRMAP_FREEPAGE ){
37437         searchList = 1;
37438       }
37439       *pPgno = nearby;
37440     }
37441 #endif
37442
37443     /* Decrement the free-list count by 1. Set iTrunk to the index of the
37444     ** first free-list trunk page. iPrevTrunk is initially 1.
37445     */
37446     rc = sqlite3PagerWrite(pPage1->pDbPage);
37447     if( rc ) return rc;
37448     put4byte(&pPage1->aData[36], n-1);
37449
37450     /* The code within this loop is run only once if the 'searchList' variable
37451     ** is not true. Otherwise, it runs once for each trunk-page on the
37452     ** free-list until the page 'nearby' is located.
37453     */
37454     do {
37455       pPrevTrunk = pTrunk;
37456       if( pPrevTrunk ){
37457         iTrunk = get4byte(&pPrevTrunk->aData[0]);
37458       }else{
37459         iTrunk = get4byte(&pPage1->aData[32]);
37460       }
37461       rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
37462       if( rc ){
37463         pTrunk = 0;
37464         goto end_allocate_page;
37465       }
37466
37467       k = get4byte(&pTrunk->aData[4]);
37468       if( k==0 && !searchList ){
37469         /* The trunk has no leaves and the list is not being searched. 
37470         ** So extract the trunk page itself and use it as the newly 
37471         ** allocated page */
37472         assert( pPrevTrunk==0 );
37473         rc = sqlite3PagerWrite(pTrunk->pDbPage);
37474         if( rc ){
37475           goto end_allocate_page;
37476         }
37477         *pPgno = iTrunk;
37478         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
37479         *ppPage = pTrunk;
37480         pTrunk = 0;
37481         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
37482       }else if( k>pBt->usableSize/4 - 2 ){
37483         /* Value of k is out of range.  Database corruption */
37484         rc = SQLITE_CORRUPT_BKPT;
37485         goto end_allocate_page;
37486 #ifndef SQLITE_OMIT_AUTOVACUUM
37487       }else if( searchList && nearby==iTrunk ){
37488         /* The list is being searched and this trunk page is the page
37489         ** to allocate, regardless of whether it has leaves.
37490         */
37491         assert( *pPgno==iTrunk );
37492         *ppPage = pTrunk;
37493         searchList = 0;
37494         rc = sqlite3PagerWrite(pTrunk->pDbPage);
37495         if( rc ){
37496           goto end_allocate_page;
37497         }
37498         if( k==0 ){
37499           if( !pPrevTrunk ){
37500             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
37501           }else{
37502             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
37503           }
37504         }else{
37505           /* The trunk page is required by the caller but it contains 
37506           ** pointers to free-list leaves. The first leaf becomes a trunk
37507           ** page in this case.
37508           */
37509           MemPage *pNewTrunk;
37510           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
37511           rc = sqlite3BtreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
37512           if( rc!=SQLITE_OK ){
37513             goto end_allocate_page;
37514           }
37515           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
37516           if( rc!=SQLITE_OK ){
37517             releasePage(pNewTrunk);
37518             goto end_allocate_page;
37519           }
37520           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
37521           put4byte(&pNewTrunk->aData[4], k-1);
37522           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
37523           releasePage(pNewTrunk);
37524           if( !pPrevTrunk ){
37525             put4byte(&pPage1->aData[32], iNewTrunk);
37526           }else{
37527             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
37528             if( rc ){
37529               goto end_allocate_page;
37530             }
37531             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
37532           }
37533         }
37534         pTrunk = 0;
37535         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
37536 #endif
37537       }else{
37538         /* Extract a leaf from the trunk */
37539         int closest;
37540         Pgno iPage;
37541         unsigned char *aData = pTrunk->aData;
37542         rc = sqlite3PagerWrite(pTrunk->pDbPage);
37543         if( rc ){
37544           goto end_allocate_page;
37545         }
37546         if( nearby>0 ){
37547           int i, dist;
37548           closest = 0;
37549           dist = get4byte(&aData[8]) - nearby;
37550           if( dist<0 ) dist = -dist;
37551           for(i=1; i<k; i++){
37552             int d2 = get4byte(&aData[8+i*4]) - nearby;
37553             if( d2<0 ) d2 = -d2;
37554             if( d2<dist ){
37555               closest = i;
37556               dist = d2;
37557             }
37558           }
37559         }else{
37560           closest = 0;
37561         }
37562
37563         iPage = get4byte(&aData[8+closest*4]);
37564         if( !searchList || iPage==nearby ){
37565           int nPage;
37566           *pPgno = iPage;
37567           nPage = pagerPagecount(pBt->pPager);
37568           if( *pPgno>nPage ){
37569             /* Free page off the end of the file */
37570             rc = SQLITE_CORRUPT_BKPT;
37571             goto end_allocate_page;
37572           }
37573           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
37574                  ": %d more free pages\n",
37575                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
37576           if( closest<k-1 ){
37577             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
37578           }
37579           put4byte(&aData[4], k-1);
37580           rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 1);
37581           if( rc==SQLITE_OK ){
37582             sqlite3PagerDontRollback((*ppPage)->pDbPage);
37583             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
37584             if( rc!=SQLITE_OK ){
37585               releasePage(*ppPage);
37586             }
37587           }
37588           searchList = 0;
37589         }
37590       }
37591       releasePage(pPrevTrunk);
37592       pPrevTrunk = 0;
37593     }while( searchList );
37594   }else{
37595     /* There are no pages on the freelist, so create a new page at the
37596     ** end of the file */
37597     int nPage = pagerPagecount(pBt->pPager);
37598     *pPgno = nPage + 1;
37599
37600 #ifndef SQLITE_OMIT_AUTOVACUUM
37601     if( pBt->nTrunc ){
37602       /* An incr-vacuum has already run within this transaction. So the
37603       ** page to allocate is not from the physical end of the file, but
37604       ** at pBt->nTrunc. 
37605       */
37606       *pPgno = pBt->nTrunc+1;
37607       if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
37608         (*pPgno)++;
37609       }
37610     }
37611     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
37612       /* If *pPgno refers to a pointer-map page, allocate two new pages
37613       ** at the end of the file instead of one. The first allocated page
37614       ** becomes a new pointer-map page, the second is used by the caller.
37615       */
37616       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
37617       assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
37618       (*pPgno)++;
37619       if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ (*pPgno)++; }
37620     }
37621     if( pBt->nTrunc ){
37622       pBt->nTrunc = *pPgno;
37623     }
37624 #endif
37625
37626     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
37627     rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 0);
37628     if( rc ) return rc;
37629     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
37630     if( rc!=SQLITE_OK ){
37631       releasePage(*ppPage);
37632     }
37633     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
37634   }
37635
37636   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
37637
37638 end_allocate_page:
37639   releasePage(pTrunk);
37640   releasePage(pPrevTrunk);
37641   if( rc==SQLITE_OK ){
37642     if( (*ppPage)->isInit==PAGE_ISINIT_FULL ){
37643       releasePage(*ppPage);
37644       return SQLITE_CORRUPT_BKPT;
37645     }
37646     (*ppPage)->isInit = 0;
37647   }
37648   return rc;
37649 }
37650
37651 /*
37652 ** Add a page of the database file to the freelist.
37653 **
37654 ** sqlite3PagerUnref() is NOT called for pPage.
37655 */
37656 static int freePage(MemPage *pPage){
37657   BtShared *pBt = pPage->pBt;
37658   MemPage *pPage1 = pBt->pPage1;
37659   int rc, n, k;
37660
37661   /* Prepare the page for freeing */
37662   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
37663   assert( pPage->pgno>1 );
37664   pPage->isInit = 0;
37665   releasePage(pPage->pParent);
37666   pPage->pParent = 0;
37667
37668   /* Increment the free page count on pPage1 */
37669   rc = sqlite3PagerWrite(pPage1->pDbPage);
37670   if( rc ) return rc;
37671   n = get4byte(&pPage1->aData[36]);
37672   put4byte(&pPage1->aData[36], n+1);
37673
37674 #ifdef SQLITE_SECURE_DELETE
37675   /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
37676   ** always fully overwrite deleted information with zeros.
37677   */
37678   rc = sqlite3PagerWrite(pPage->pDbPage);
37679   if( rc ) return rc;
37680   memset(pPage->aData, 0, pPage->pBt->pageSize);
37681 #endif
37682
37683   /* If the database supports auto-vacuum, write an entry in the pointer-map
37684   ** to indicate that the page is free.
37685   */
37686   if( ISAUTOVACUUM ){
37687     rc = ptrmapPut(pBt, pPage->pgno, PTRMAP_FREEPAGE, 0);
37688     if( rc ) return rc;
37689   }
37690
37691   if( n==0 ){
37692     /* This is the first free page */
37693     rc = sqlite3PagerWrite(pPage->pDbPage);
37694     if( rc ) return rc;
37695     memset(pPage->aData, 0, 8);
37696     put4byte(&pPage1->aData[32], pPage->pgno);
37697     TRACE(("FREE-PAGE: %d first\n", pPage->pgno));
37698   }else{
37699     /* Other free pages already exist.  Retrive the first trunk page
37700     ** of the freelist and find out how many leaves it has. */
37701     MemPage *pTrunk;
37702     rc = sqlite3BtreeGetPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk, 0);
37703     if( rc ) return rc;
37704     k = get4byte(&pTrunk->aData[4]);
37705     if( k>=pBt->usableSize/4 - 8 ){
37706       /* The trunk is full.  Turn the page being freed into a new
37707       ** trunk page with no leaves.
37708       **
37709       ** Note that the trunk page is not really full until it contains
37710       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
37711       ** coded.  But due to a coding error in versions of SQLite prior to
37712       ** 3.6.0, databases with freelist trunk pages holding more than
37713       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
37714       ** to maintain backwards compatibility with older versions of SQLite,
37715       ** we will contain to restrict the number of entries to usableSize/4 - 8
37716       ** for now.  At some point in the future (once everyone has upgraded
37717       ** to 3.6.0 or later) we should consider fixing the conditional above
37718       ** to read "usableSize/4-2" instead of "usableSize/4-8".
37719       */
37720       rc = sqlite3PagerWrite(pPage->pDbPage);
37721       if( rc==SQLITE_OK ){
37722         put4byte(pPage->aData, pTrunk->pgno);
37723         put4byte(&pPage->aData[4], 0);
37724         put4byte(&pPage1->aData[32], pPage->pgno);
37725         TRACE(("FREE-PAGE: %d new trunk page replacing %d\n",
37726                 pPage->pgno, pTrunk->pgno));
37727       }
37728     }else if( k<0 ){
37729       rc = SQLITE_CORRUPT;
37730     }else{
37731       /* Add the newly freed page as a leaf on the current trunk */
37732       rc = sqlite3PagerWrite(pTrunk->pDbPage);
37733       if( rc==SQLITE_OK ){
37734         put4byte(&pTrunk->aData[4], k+1);
37735         put4byte(&pTrunk->aData[8+k*4], pPage->pgno);
37736 #ifndef SQLITE_SECURE_DELETE
37737         rc = sqlite3PagerDontWrite(pPage->pDbPage);
37738 #endif
37739       }
37740       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
37741     }
37742     releasePage(pTrunk);
37743   }
37744   return rc;
37745 }
37746
37747 /*
37748 ** Free any overflow pages associated with the given Cell.
37749 */
37750 static int clearCell(MemPage *pPage, unsigned char *pCell){
37751   BtShared *pBt = pPage->pBt;
37752   CellInfo info;
37753   Pgno ovflPgno;
37754   int rc;
37755   int nOvfl;
37756   int ovflPageSize;
37757
37758   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
37759   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
37760   if( info.iOverflow==0 ){
37761     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
37762   }
37763   ovflPgno = get4byte(&pCell[info.iOverflow]);
37764   ovflPageSize = pBt->usableSize - 4;
37765   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
37766   assert( ovflPgno==0 || nOvfl>0 );
37767   while( nOvfl-- ){
37768     MemPage *pOvfl;
37769     if( ovflPgno==0 || ovflPgno>pagerPagecount(pBt->pPager) ){
37770       return SQLITE_CORRUPT_BKPT;
37771     }
37772
37773     rc = getOverflowPage(pBt, ovflPgno, &pOvfl, (nOvfl==0)?0:&ovflPgno);
37774     if( rc ) return rc;
37775     rc = freePage(pOvfl);
37776     sqlite3PagerUnref(pOvfl->pDbPage);
37777     if( rc ) return rc;
37778   }
37779   return SQLITE_OK;
37780 }
37781
37782 /*
37783 ** Create the byte sequence used to represent a cell on page pPage
37784 ** and write that byte sequence into pCell[].  Overflow pages are
37785 ** allocated and filled in as necessary.  The calling procedure
37786 ** is responsible for making sure sufficient space has been allocated
37787 ** for pCell[].
37788 **
37789 ** Note that pCell does not necessary need to point to the pPage->aData
37790 ** area.  pCell might point to some temporary storage.  The cell will
37791 ** be constructed in this temporary area then copied into pPage->aData
37792 ** later.
37793 */
37794 static int fillInCell(
37795   MemPage *pPage,                /* The page that contains the cell */
37796   unsigned char *pCell,          /* Complete text of the cell */
37797   const void *pKey, i64 nKey,    /* The key */
37798   const void *pData,int nData,   /* The data */
37799   int nZero,                     /* Extra zero bytes to append to pData */
37800   int *pnSize                    /* Write cell size here */
37801 ){
37802   int nPayload;
37803   const u8 *pSrc;
37804   int nSrc, n, rc;
37805   int spaceLeft;
37806   MemPage *pOvfl = 0;
37807   MemPage *pToRelease = 0;
37808   unsigned char *pPrior;
37809   unsigned char *pPayload;
37810   BtShared *pBt = pPage->pBt;
37811   Pgno pgnoOvfl = 0;
37812   int nHeader;
37813   CellInfo info;
37814
37815   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
37816
37817   /* Fill in the header. */
37818   nHeader = 0;
37819   if( !pPage->leaf ){
37820     nHeader += 4;
37821   }
37822   if( pPage->hasData ){
37823     nHeader += putVarint(&pCell[nHeader], nData+nZero);
37824   }else{
37825     nData = nZero = 0;
37826   }
37827   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
37828   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
37829   assert( info.nHeader==nHeader );
37830   assert( info.nKey==nKey );
37831   assert( info.nData==nData+nZero );
37832   
37833   /* Fill in the payload */
37834   nPayload = nData + nZero;
37835   if( pPage->intKey ){
37836     pSrc = pData;
37837     nSrc = nData;
37838     nData = 0;
37839   }else{
37840     nPayload += nKey;
37841     pSrc = pKey;
37842     nSrc = nKey;
37843   }
37844   *pnSize = info.nSize;
37845   spaceLeft = info.nLocal;
37846   pPayload = &pCell[nHeader];
37847   pPrior = &pCell[info.iOverflow];
37848
37849   while( nPayload>0 ){
37850     if( spaceLeft==0 ){
37851       int isExact = 0;
37852 #ifndef SQLITE_OMIT_AUTOVACUUM
37853       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
37854       if( pBt->autoVacuum ){
37855         do{
37856           pgnoOvfl++;
37857         } while( 
37858           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
37859         );
37860         if( pgnoOvfl>1 ){
37861           /* isExact = 1; */
37862         }
37863       }
37864 #endif
37865       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, isExact);
37866 #ifndef SQLITE_OMIT_AUTOVACUUM
37867       /* If the database supports auto-vacuum, and the second or subsequent
37868       ** overflow page is being allocated, add an entry to the pointer-map
37869       ** for that page now. 
37870       **
37871       ** If this is the first overflow page, then write a partial entry 
37872       ** to the pointer-map. If we write nothing to this pointer-map slot,
37873       ** then the optimistic overflow chain processing in clearCell()
37874       ** may misinterpret the uninitialised values and delete the
37875       ** wrong pages from the database.
37876       */
37877       if( pBt->autoVacuum && rc==SQLITE_OK ){
37878         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
37879         rc = ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap);
37880         if( rc ){
37881           releasePage(pOvfl);
37882         }
37883       }
37884 #endif
37885       if( rc ){
37886         releasePage(pToRelease);
37887         return rc;
37888       }
37889       put4byte(pPrior, pgnoOvfl);
37890       releasePage(pToRelease);
37891       pToRelease = pOvfl;
37892       pPrior = pOvfl->aData;
37893       put4byte(pPrior, 0);
37894       pPayload = &pOvfl->aData[4];
37895       spaceLeft = pBt->usableSize - 4;
37896     }
37897     n = nPayload;
37898     if( n>spaceLeft ) n = spaceLeft;
37899     if( nSrc>0 ){
37900       if( n>nSrc ) n = nSrc;
37901       assert( pSrc );
37902       memcpy(pPayload, pSrc, n);
37903     }else{
37904       memset(pPayload, 0, n);
37905     }
37906     nPayload -= n;
37907     pPayload += n;
37908     pSrc += n;
37909     nSrc -= n;
37910     spaceLeft -= n;
37911     if( nSrc==0 ){
37912       nSrc = nData;
37913       pSrc = pData;
37914     }
37915   }
37916   releasePage(pToRelease);
37917   return SQLITE_OK;
37918 }
37919
37920
37921 /*
37922 ** Change the MemPage.pParent pointer on the page whose number is
37923 ** given in the second argument so that MemPage.pParent holds the
37924 ** pointer in the third argument.
37925 **
37926 ** If the final argument, updatePtrmap, is non-zero and the database
37927 ** is an auto-vacuum database, then the pointer-map entry for pgno
37928 ** is updated.
37929 */
37930 static int reparentPage(
37931   BtShared *pBt,                /* B-Tree structure */
37932   Pgno pgno,                    /* Page number of child being adopted */
37933   MemPage *pNewParent,          /* New parent of pgno */
37934   int idx,                      /* Index of child page pgno in pNewParent */
37935   int updatePtrmap              /* If true, update pointer-map for pgno */
37936 ){
37937   MemPage *pThis;
37938   DbPage *pDbPage;
37939
37940   assert( sqlite3_mutex_held(pBt->mutex) );
37941   assert( pNewParent!=0 );
37942   if( pgno==0 ) return SQLITE_OK;
37943   assert( pBt->pPager!=0 );
37944   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
37945   if( pDbPage ){
37946     pThis = (MemPage *)sqlite3PagerGetExtra(pDbPage);
37947     if( pThis->isInit==PAGE_ISINIT_FULL ){
37948       assert( pThis->aData==sqlite3PagerGetData(pDbPage) );
37949       if( pThis->pParent!=pNewParent ){
37950         if( pThis->pParent ) sqlite3PagerUnref(pThis->pParent->pDbPage);
37951         pThis->pParent = pNewParent;
37952         sqlite3PagerRef(pNewParent->pDbPage);
37953       }
37954       pThis->idxParent = idx;
37955     }
37956     sqlite3PagerUnref(pDbPage);
37957   }
37958
37959   if( ISAUTOVACUUM && updatePtrmap ){
37960     return ptrmapPut(pBt, pgno, PTRMAP_BTREE, pNewParent->pgno);
37961   }
37962
37963 #ifndef NDEBUG
37964   /* If the updatePtrmap flag was clear, assert that the entry in the
37965   ** pointer-map is already correct.
37966   */
37967   if( ISAUTOVACUUM ){
37968     pDbPage = sqlite3PagerLookup(pBt->pPager,PTRMAP_PAGENO(pBt,pgno));
37969     if( pDbPage ){
37970       u8 eType;
37971       Pgno ii;
37972       int rc = ptrmapGet(pBt, pgno, &eType, &ii);
37973       assert( rc==SQLITE_OK && ii==pNewParent->pgno && eType==PTRMAP_BTREE );
37974       sqlite3PagerUnref(pDbPage);
37975     }
37976   }
37977 #endif
37978
37979   return SQLITE_OK;
37980 }
37981
37982
37983
37984 /*
37985 ** Change the pParent pointer of all children of pPage to point back
37986 ** to pPage.
37987 **
37988 ** In other words, for every child of pPage, invoke reparentPage()
37989 ** to make sure that each child knows that pPage is its parent.
37990 **
37991 ** This routine gets called after you memcpy() one page into
37992 ** another.
37993 **
37994 ** If updatePtrmap is true, then the pointer-map entries for all child
37995 ** pages of pPage are updated.
37996 */
37997 static int reparentChildPages(MemPage *pPage, int updatePtrmap){
37998   int rc = SQLITE_OK;
37999   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38000   if( !pPage->leaf ){
38001     int i;
38002     BtShared *pBt = pPage->pBt;
38003     Pgno iRight = get4byte(&pPage->aData[pPage->hdrOffset+8]);
38004
38005     for(i=0; i<pPage->nCell; i++){
38006       u8 *pCell = findCell(pPage, i);
38007       rc = reparentPage(pBt, get4byte(pCell), pPage, i, updatePtrmap);
38008       if( rc!=SQLITE_OK ) return rc;
38009     }
38010     rc = reparentPage(pBt, iRight, pPage, i, updatePtrmap);
38011     pPage->idxShift = 0;
38012   }
38013   return rc;
38014 }
38015
38016 /*
38017 ** Remove the i-th cell from pPage.  This routine effects pPage only.
38018 ** The cell content is not freed or deallocated.  It is assumed that
38019 ** the cell content has been copied someplace else.  This routine just
38020 ** removes the reference to the cell from pPage.
38021 **
38022 ** "sz" must be the number of bytes in the cell.
38023 */
38024 static void dropCell(MemPage *pPage, int idx, int sz){
38025   int i;          /* Loop counter */
38026   int pc;         /* Offset to cell content of cell being deleted */
38027   u8 *data;       /* pPage->aData */
38028   u8 *ptr;        /* Used to move bytes around within data[] */
38029
38030   assert( idx>=0 && idx<pPage->nCell );
38031   assert( sz==cellSize(pPage, idx) );
38032   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38033   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38034   data = pPage->aData;
38035   ptr = &data[pPage->cellOffset + 2*idx];
38036   pc = get2byte(ptr);
38037   assert( pc>10 && pc+sz<=pPage->pBt->usableSize );
38038   freeSpace(pPage, pc, sz);
38039   for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
38040     ptr[0] = ptr[2];
38041     ptr[1] = ptr[3];
38042   }
38043   pPage->nCell--;
38044   put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
38045   pPage->nFree += 2;
38046   pPage->idxShift = 1;
38047 }
38048
38049 /*
38050 ** Insert a new cell on pPage at cell index "i".  pCell points to the
38051 ** content of the cell.
38052 **
38053 ** If the cell content will fit on the page, then put it there.  If it
38054 ** will not fit, then make a copy of the cell content into pTemp if
38055 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
38056 ** in pPage->aOvfl[] and make it point to the cell content (either
38057 ** in pTemp or the original pCell) and also record its index. 
38058 ** Allocating a new entry in pPage->aCell[] implies that 
38059 ** pPage->nOverflow is incremented.
38060 **
38061 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
38062 ** cell. The caller will overwrite them after this function returns. If
38063 ** nSkip is non-zero, then pCell may not point to an invalid memory location 
38064 ** (but pCell+nSkip is always valid).
38065 */
38066 static int insertCell(
38067   MemPage *pPage,   /* Page into which we are copying */
38068   int i,            /* New cell becomes the i-th cell of the page */
38069   u8 *pCell,        /* Content of the new cell */
38070   int sz,           /* Bytes of content in pCell */
38071   u8 *pTemp,        /* Temp storage space for pCell, if needed */
38072   u8 nSkip          /* Do not write the first nSkip bytes of the cell */
38073 ){
38074   int idx;          /* Where to write new cell content in data[] */
38075   int j;            /* Loop counter */
38076   int top;          /* First byte of content for any cell in data[] */
38077   int end;          /* First byte past the last cell pointer in data[] */
38078   int ins;          /* Index in data[] where new cell pointer is inserted */
38079   int hdr;          /* Offset into data[] of the page header */
38080   int cellOffset;   /* Address of first cell pointer in data[] */
38081   u8 *data;         /* The content of the whole page */
38082   u8 *ptr;          /* Used for moving information around in data[] */
38083
38084   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
38085   assert( sz==cellSizePtr(pPage, pCell) );
38086   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38087   if( pPage->nOverflow || sz+2>pPage->nFree ){
38088     if( pTemp ){
38089       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
38090       pCell = pTemp;
38091     }
38092     j = pPage->nOverflow++;
38093     assert( j<sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0]) );
38094     pPage->aOvfl[j].pCell = pCell;
38095     pPage->aOvfl[j].idx = i;
38096     pPage->nFree = 0;
38097   }else{
38098     int rc = sqlite3PagerWrite(pPage->pDbPage);
38099     if( rc!=SQLITE_OK ){
38100       return rc;
38101     }
38102     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38103     data = pPage->aData;
38104     hdr = pPage->hdrOffset;
38105     top = get2byte(&data[hdr+5]);
38106     cellOffset = pPage->cellOffset;
38107     end = cellOffset + 2*pPage->nCell + 2;
38108     ins = cellOffset + 2*i;
38109     if( end > top - sz ){
38110       defragmentPage(pPage);
38111       top = get2byte(&data[hdr+5]);
38112       assert( end + sz <= top );
38113     }
38114     idx = allocateSpace(pPage, sz);
38115     assert( idx>0 );
38116     assert( end <= get2byte(&data[hdr+5]) );
38117     pPage->nCell++;
38118     pPage->nFree -= 2;
38119     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
38120     for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
38121       ptr[0] = ptr[-2];
38122       ptr[1] = ptr[-1];
38123     }
38124     put2byte(&data[ins], idx);
38125     put2byte(&data[hdr+3], pPage->nCell);
38126     pPage->idxShift = 1;
38127 #ifndef SQLITE_OMIT_AUTOVACUUM
38128     if( pPage->pBt->autoVacuum ){
38129       /* The cell may contain a pointer to an overflow page. If so, write
38130       ** the entry for the overflow page into the pointer map.
38131       */
38132       CellInfo info;
38133       sqlite3BtreeParseCellPtr(pPage, pCell, &info);
38134       assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
38135       if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
38136         Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
38137         rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
38138         if( rc!=SQLITE_OK ) return rc;
38139       }
38140     }
38141 #endif
38142   }
38143
38144   return SQLITE_OK;
38145 }
38146
38147 /*
38148 ** Add a list of cells to a page.  The page should be initially empty.
38149 ** The cells are guaranteed to fit on the page.
38150 */
38151 static void assemblePage(
38152   MemPage *pPage,   /* The page to be assemblied */
38153   int nCell,        /* The number of cells to add to this page */
38154   u8 **apCell,      /* Pointers to cell bodies */
38155   u16 *aSize        /* Sizes of the cells */
38156 ){
38157   int i;            /* Loop counter */
38158   int totalSize;    /* Total size of all cells */
38159   int hdr;          /* Index of page header */
38160   int cellptr;      /* Address of next cell pointer */
38161   int cellbody;     /* Address of next cell body */
38162   u8 *data;         /* Data for the page */
38163
38164   assert( pPage->nOverflow==0 );
38165   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38166   totalSize = 0;
38167   for(i=0; i<nCell; i++){
38168     totalSize += aSize[i];
38169   }
38170   assert( totalSize+2*nCell<=pPage->nFree );
38171   assert( pPage->nCell==0 );
38172   cellptr = pPage->cellOffset;
38173   data = pPage->aData;
38174   hdr = pPage->hdrOffset;
38175   put2byte(&data[hdr+3], nCell);
38176   if( nCell ){
38177     cellbody = allocateSpace(pPage, totalSize);
38178     assert( cellbody>0 );
38179     assert( pPage->nFree >= 2*nCell );
38180     pPage->nFree -= 2*nCell;
38181     for(i=0; i<nCell; i++){
38182       put2byte(&data[cellptr], cellbody);
38183       memcpy(&data[cellbody], apCell[i], aSize[i]);
38184       cellptr += 2;
38185       cellbody += aSize[i];
38186     }
38187     assert( cellbody==pPage->pBt->usableSize );
38188   }
38189   pPage->nCell = nCell;
38190 }
38191
38192 /*
38193 ** The following parameters determine how many adjacent pages get involved
38194 ** in a balancing operation.  NN is the number of neighbors on either side
38195 ** of the page that participate in the balancing operation.  NB is the
38196 ** total number of pages that participate, including the target page and
38197 ** NN neighbors on either side.
38198 **
38199 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
38200 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
38201 ** in exchange for a larger degradation in INSERT and UPDATE performance.
38202 ** The value of NN appears to give the best results overall.
38203 */
38204 #define NN 1             /* Number of neighbors on either side of pPage */
38205 #define NB (NN*2+1)      /* Total pages involved in the balance */
38206
38207 /* Forward reference */
38208 static int balance(MemPage*, int);
38209
38210 #ifndef SQLITE_OMIT_QUICKBALANCE
38211 /*
38212 ** This version of balance() handles the common special case where
38213 ** a new entry is being inserted on the extreme right-end of the
38214 ** tree, in other words, when the new entry will become the largest
38215 ** entry in the tree.
38216 **
38217 ** Instead of trying balance the 3 right-most leaf pages, just add
38218 ** a new page to the right-hand side and put the one new entry in
38219 ** that page.  This leaves the right side of the tree somewhat
38220 ** unbalanced.  But odds are that we will be inserting new entries
38221 ** at the end soon afterwards so the nearly empty page will quickly
38222 ** fill up.  On average.
38223 **
38224 ** pPage is the leaf page which is the right-most page in the tree.
38225 ** pParent is its parent.  pPage must have a single overflow entry
38226 ** which is also the right-most entry on the page.
38227 */
38228 static int balance_quick(MemPage *pPage, MemPage *pParent){
38229   int rc;
38230   MemPage *pNew = 0;
38231   Pgno pgnoNew;
38232   u8 *pCell;
38233   u16 szCell;
38234   CellInfo info;
38235   BtShared *pBt = pPage->pBt;
38236   int parentIdx = pParent->nCell;   /* pParent new divider cell index */
38237   int parentSize;                   /* Size of new divider cell */
38238   u8 parentCell[64];                /* Space for the new divider cell */
38239
38240   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38241
38242   /* Allocate a new page. Insert the overflow cell from pPage
38243   ** into it. Then remove the overflow cell from pPage.
38244   */
38245   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
38246   if( rc==SQLITE_OK ){
38247     pCell = pPage->aOvfl[0].pCell;
38248     szCell = cellSizePtr(pPage, pCell);
38249     zeroPage(pNew, pPage->aData[0]);
38250     assemblePage(pNew, 1, &pCell, &szCell);
38251     pPage->nOverflow = 0;
38252   
38253     /* Set the parent of the newly allocated page to pParent. */
38254     pNew->pParent = pParent;
38255     sqlite3PagerRef(pParent->pDbPage);
38256   
38257     /* pPage is currently the right-child of pParent. Change this
38258     ** so that the right-child is the new page allocated above and
38259     ** pPage is the next-to-right child. 
38260     **
38261     ** Ignore the return value of the call to fillInCell(). fillInCell()
38262     ** may only return other than SQLITE_OK if it is required to allocate
38263     ** one or more overflow pages. Since an internal table B-Tree cell 
38264     ** may never spill over onto an overflow page (it is a maximum of 
38265     ** 13 bytes in size), it is not neccessary to check the return code.
38266     **
38267     ** Similarly, the insertCell() function cannot fail if the page
38268     ** being inserted into is already writable and the cell does not 
38269     ** contain an overflow pointer. So ignore this return code too.
38270     */
38271     assert( pPage->nCell>0 );
38272     pCell = findCell(pPage, pPage->nCell-1);
38273     sqlite3BtreeParseCellPtr(pPage, pCell, &info);
38274     fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, 0, &parentSize);
38275     assert( parentSize<64 );
38276     assert( sqlite3PagerIswriteable(pParent->pDbPage) );
38277     insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4);
38278     put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno);
38279     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
38280   
38281     /* If this is an auto-vacuum database, update the pointer map
38282     ** with entries for the new page, and any pointer from the 
38283     ** cell on the page to an overflow page.
38284     */
38285     if( ISAUTOVACUUM ){
38286       rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
38287       if( rc==SQLITE_OK ){
38288         rc = ptrmapPutOvfl(pNew, 0);
38289       }
38290     }
38291
38292     /* Release the reference to the new page. */
38293     releasePage(pNew);
38294   }
38295
38296   /* At this point the pPage->nFree variable is not set correctly with
38297   ** respect to the content of the page (because it was set to 0 by 
38298   ** insertCell). So call sqlite3BtreeInitPage() to make sure it is
38299   ** correct.
38300   **
38301   ** This has to be done even if an error will be returned. Normally, if
38302   ** an error occurs during tree balancing, the contents of MemPage are
38303   ** not important, as they will be recalculated when the page is rolled
38304   ** back. But here, in balance_quick(), it is possible that pPage has 
38305   ** not yet been marked dirty or written into the journal file. Therefore
38306   ** it will not be rolled back and so it is important to make sure that
38307   ** the page data and contents of MemPage are consistent.
38308   */
38309   pPage->isInit = 0;
38310   sqlite3BtreeInitPage(pPage, pPage->pParent);
38311   sqlite3PagerUnref(pPage->pParent->pDbPage);
38312
38313   /* If everything else succeeded, balance the parent page, in 
38314   ** case the divider cell inserted caused it to become overfull.
38315   */
38316   if( rc==SQLITE_OK ){
38317     rc = balance(pParent, 0);
38318   }
38319   return rc;
38320 }
38321 #endif /* SQLITE_OMIT_QUICKBALANCE */
38322
38323 /*
38324 ** This routine redistributes Cells on pPage and up to NN*2 siblings
38325 ** of pPage so that all pages have about the same amount of free space.
38326 ** Usually NN siblings on either side of pPage is used in the balancing,
38327 ** though more siblings might come from one side if pPage is the first
38328 ** or last child of its parent.  If pPage has fewer than 2*NN siblings
38329 ** (something which can only happen if pPage is the root page or a 
38330 ** child of root) then all available siblings participate in the balancing.
38331 **
38332 ** The number of siblings of pPage might be increased or decreased by one or
38333 ** two in an effort to keep pages nearly full but not over full. The root page
38334 ** is special and is allowed to be nearly empty. If pPage is 
38335 ** the root page, then the depth of the tree might be increased
38336 ** or decreased by one, as necessary, to keep the root page from being
38337 ** overfull or completely empty.
38338 **
38339 ** Note that when this routine is called, some of the Cells on pPage
38340 ** might not actually be stored in pPage->aData[].  This can happen
38341 ** if the page is overfull.  Part of the job of this routine is to
38342 ** make sure all Cells for pPage once again fit in pPage->aData[].
38343 **
38344 ** In the course of balancing the siblings of pPage, the parent of pPage
38345 ** might become overfull or underfull.  If that happens, then this routine
38346 ** is called recursively on the parent.
38347 **
38348 ** If this routine fails for any reason, it might leave the database
38349 ** in a corrupted state.  So if this routine fails, the database should
38350 ** be rolled back.
38351 */
38352 static int balance_nonroot(MemPage *pPage){
38353   MemPage *pParent;            /* The parent of pPage */
38354   BtShared *pBt;               /* The whole database */
38355   int nCell = 0;               /* Number of cells in apCell[] */
38356   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
38357   int nOld;                    /* Number of pages in apOld[] */
38358   int nNew;                    /* Number of pages in apNew[] */
38359   int nDiv;                    /* Number of cells in apDiv[] */
38360   int i, j, k;                 /* Loop counters */
38361   int idx;                     /* Index of pPage in pParent->aCell[] */
38362   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
38363   int rc;                      /* The return code */
38364   int leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
38365   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
38366   int usableSpace;             /* Bytes in pPage beyond the header */
38367   int pageFlags;               /* Value of pPage->aData[0] */
38368   int subtotal;                /* Subtotal of bytes in cells on one page */
38369   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
38370   int iSpace2 = 0;             /* First unused byte of aSpace2[] */
38371   int szScratch;               /* Size of scratch memory requested */
38372   MemPage *apOld[NB];          /* pPage and up to two siblings */
38373   Pgno pgnoOld[NB];            /* Page numbers for each page in apOld[] */
38374   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
38375   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
38376   Pgno pgnoNew[NB+2];          /* Page numbers for each page in apNew[] */
38377   u8 *apDiv[NB];               /* Divider cells in pParent */
38378   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
38379   int szNew[NB+2];             /* Combined size of cells place on i-th page */
38380   u8 **apCell = 0;             /* All cells begin balanced */
38381   u16 *szCell;                 /* Local size of all cells in apCell[] */
38382   u8 *aCopy[NB];         /* Space for holding data of apCopy[] */
38383   u8 *aSpace1;           /* Space for copies of dividers cells before balance */
38384   u8 *aSpace2 = 0;       /* Space for overflow dividers cells after balance */
38385   u8 *aFrom = 0;
38386
38387   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38388
38389   /* 
38390   ** Find the parent page.
38391   */
38392   assert( pPage->isInit==PAGE_ISINIT_FULL );
38393   assert( sqlite3PagerIswriteable(pPage->pDbPage) || pPage->nOverflow==1 );
38394   pBt = pPage->pBt;
38395   pParent = pPage->pParent;
38396   assert( pParent );
38397   if( SQLITE_OK!=(rc = sqlite3PagerWrite(pParent->pDbPage)) ){
38398     return rc;
38399   }
38400
38401   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
38402
38403 #ifndef SQLITE_OMIT_QUICKBALANCE
38404   /*
38405   ** A special case:  If a new entry has just been inserted into a
38406   ** table (that is, a btree with integer keys and all data at the leaves)
38407   ** and the new entry is the right-most entry in the tree (it has the
38408   ** largest key) then use the special balance_quick() routine for
38409   ** balancing.  balance_quick() is much faster and results in a tighter
38410   ** packing of data in the common case.
38411   */
38412   if( pPage->leaf &&
38413       pPage->intKey &&
38414       pPage->nOverflow==1 &&
38415       pPage->aOvfl[0].idx==pPage->nCell &&
38416       pPage->pParent->pgno!=1 &&
38417       get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno
38418   ){
38419     assert( pPage->intKey );
38420     /*
38421     ** TODO: Check the siblings to the left of pPage. It may be that
38422     ** they are not full and no new page is required.
38423     */
38424     return balance_quick(pPage, pParent);
38425   }
38426 #endif
38427
38428   if( SQLITE_OK!=(rc = sqlite3PagerWrite(pPage->pDbPage)) ){
38429     return rc;
38430   }
38431
38432   /*
38433   ** Find the cell in the parent page whose left child points back
38434   ** to pPage.  The "idx" variable is the index of that cell.  If pPage
38435   ** is the rightmost child of pParent then set idx to pParent->nCell 
38436   */
38437   if( pParent->idxShift ){
38438     Pgno pgno;
38439     pgno = pPage->pgno;
38440     assert( pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
38441     for(idx=0; idx<pParent->nCell; idx++){
38442       if( get4byte(findCell(pParent, idx))==pgno ){
38443         break;
38444       }
38445     }
38446     assert( idx<pParent->nCell
38447              || get4byte(&pParent->aData[pParent->hdrOffset+8])==pgno );
38448   }else{
38449     idx = pPage->idxParent;
38450   }
38451
38452   /*
38453   ** Initialize variables so that it will be safe to jump
38454   ** directly to balance_cleanup at any moment.
38455   */
38456   nOld = nNew = 0;
38457   sqlite3PagerRef(pParent->pDbPage);
38458
38459   /*
38460   ** Find sibling pages to pPage and the cells in pParent that divide
38461   ** the siblings.  An attempt is made to find NN siblings on either
38462   ** side of pPage.  More siblings are taken from one side, however, if
38463   ** pPage there are fewer than NN siblings on the other side.  If pParent
38464   ** has NB or fewer children then all children of pParent are taken.
38465   */
38466   nxDiv = idx - NN;
38467   if( nxDiv + NB > pParent->nCell ){
38468     nxDiv = pParent->nCell - NB + 1;
38469   }
38470   if( nxDiv<0 ){
38471     nxDiv = 0;
38472   }
38473   nDiv = 0;
38474   for(i=0, k=nxDiv; i<NB; i++, k++){
38475     if( k<pParent->nCell ){
38476       apDiv[i] = findCell(pParent, k);
38477       nDiv++;
38478       assert( !pParent->leaf );
38479       pgnoOld[i] = get4byte(apDiv[i]);
38480     }else if( k==pParent->nCell ){
38481       pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
38482     }else{
38483       break;
38484     }
38485     rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i], pParent);
38486     if( rc ) goto balance_cleanup;
38487     apOld[i]->idxParent = k;
38488     apCopy[i] = 0;
38489     assert( i==nOld );
38490     nOld++;
38491     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
38492   }
38493
38494   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
38495   ** alignment */
38496   nMaxCells = (nMaxCells + 3)&~3;
38497
38498   /*
38499   ** Allocate space for memory structures
38500   */
38501   szScratch =
38502        nMaxCells*sizeof(u8*)                       /* apCell */
38503      + nMaxCells*sizeof(u16)                       /* szCell */
38504      + (ROUND8(sizeof(MemPage))+pBt->pageSize)*NB  /* aCopy */
38505      + pBt->pageSize                               /* aSpace1 */
38506      + (ISAUTOVACUUM ? nMaxCells : 0);             /* aFrom */
38507   apCell = sqlite3ScratchMalloc( szScratch ); 
38508   if( apCell==0 ){
38509     rc = SQLITE_NOMEM;
38510     goto balance_cleanup;
38511   }
38512   szCell = (u16*)&apCell[nMaxCells];
38513   aCopy[0] = (u8*)&szCell[nMaxCells];
38514   assert( ((aCopy[0] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
38515   for(i=1; i<NB; i++){
38516     aCopy[i] = &aCopy[i-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
38517     assert( ((aCopy[i] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
38518   }
38519   aSpace1 = &aCopy[NB-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
38520   assert( ((aSpace1 - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
38521   if( ISAUTOVACUUM ){
38522     aFrom = &aSpace1[pBt->pageSize];
38523   }
38524   aSpace2 = sqlite3PageMalloc(pBt->pageSize);
38525   if( aSpace2==0 ){
38526     rc = SQLITE_NOMEM;
38527     goto balance_cleanup;
38528   }
38529   
38530   /*
38531   ** Make copies of the content of pPage and its siblings into aOld[].
38532   ** The rest of this function will use data from the copies rather
38533   ** that the original pages since the original pages will be in the
38534   ** process of being overwritten.
38535   */
38536   for(i=0; i<nOld; i++){
38537     MemPage *p = apCopy[i] = (MemPage*)aCopy[i];
38538     memcpy(p, apOld[i], sizeof(MemPage));
38539     p->aData = (void*)&p[1];
38540     memcpy(p->aData, apOld[i]->aData, pBt->pageSize);
38541   }
38542
38543   /*
38544   ** Load pointers to all cells on sibling pages and the divider cells
38545   ** into the local apCell[] array.  Make copies of the divider cells
38546   ** into space obtained form aSpace1[] and remove the the divider Cells
38547   ** from pParent.
38548   **
38549   ** If the siblings are on leaf pages, then the child pointers of the
38550   ** divider cells are stripped from the cells before they are copied
38551   ** into aSpace1[].  In this way, all cells in apCell[] are without
38552   ** child pointers.  If siblings are not leaves, then all cell in
38553   ** apCell[] include child pointers.  Either way, all cells in apCell[]
38554   ** are alike.
38555   **
38556   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
38557   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
38558   */
38559   nCell = 0;
38560   leafCorrection = pPage->leaf*4;
38561   leafData = pPage->hasData;
38562   for(i=0; i<nOld; i++){
38563     MemPage *pOld = apCopy[i];
38564     int limit = pOld->nCell+pOld->nOverflow;
38565     for(j=0; j<limit; j++){
38566       assert( nCell<nMaxCells );
38567       apCell[nCell] = findOverflowCell(pOld, j);
38568       szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
38569       if( ISAUTOVACUUM ){
38570         int a;
38571         aFrom[nCell] = i;
38572         for(a=0; a<pOld->nOverflow; a++){
38573           if( pOld->aOvfl[a].pCell==apCell[nCell] ){
38574             aFrom[nCell] = 0xFF;
38575             break;
38576           }
38577         }
38578       }
38579       nCell++;
38580     }
38581     if( i<nOld-1 ){
38582       u16 sz = cellSizePtr(pParent, apDiv[i]);
38583       if( leafData ){
38584         /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
38585         ** are duplicates of keys on the child pages.  We need to remove
38586         ** the divider cells from pParent, but the dividers cells are not
38587         ** added to apCell[] because they are duplicates of child cells.
38588         */
38589         dropCell(pParent, nxDiv, sz);
38590       }else{
38591         u8 *pTemp;
38592         assert( nCell<nMaxCells );
38593         szCell[nCell] = sz;
38594         pTemp = &aSpace1[iSpace1];
38595         iSpace1 += sz;
38596         assert( sz<=pBt->pageSize/4 );
38597         assert( iSpace1<=pBt->pageSize );
38598         memcpy(pTemp, apDiv[i], sz);
38599         apCell[nCell] = pTemp+leafCorrection;
38600         if( ISAUTOVACUUM ){
38601           aFrom[nCell] = 0xFF;
38602         }
38603         dropCell(pParent, nxDiv, sz);
38604         szCell[nCell] -= leafCorrection;
38605         assert( get4byte(pTemp)==pgnoOld[i] );
38606         if( !pOld->leaf ){
38607           assert( leafCorrection==0 );
38608           /* The right pointer of the child page pOld becomes the left
38609           ** pointer of the divider cell */
38610           memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
38611         }else{
38612           assert( leafCorrection==4 );
38613           if( szCell[nCell]<4 ){
38614             /* Do not allow any cells smaller than 4 bytes. */
38615             szCell[nCell] = 4;
38616           }
38617         }
38618         nCell++;
38619       }
38620     }
38621   }
38622
38623   /*
38624   ** Figure out the number of pages needed to hold all nCell cells.
38625   ** Store this number in "k".  Also compute szNew[] which is the total
38626   ** size of all cells on the i-th page and cntNew[] which is the index
38627   ** in apCell[] of the cell that divides page i from page i+1.  
38628   ** cntNew[k] should equal nCell.
38629   **
38630   ** Values computed by this block:
38631   **
38632   **           k: The total number of sibling pages
38633   **    szNew[i]: Spaced used on the i-th sibling page.
38634   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
38635   **              the right of the i-th sibling page.
38636   ** usableSpace: Number of bytes of space available on each sibling.
38637   ** 
38638   */
38639   usableSpace = pBt->usableSize - 12 + leafCorrection;
38640   for(subtotal=k=i=0; i<nCell; i++){
38641     assert( i<nMaxCells );
38642     subtotal += szCell[i] + 2;
38643     if( subtotal > usableSpace ){
38644       szNew[k] = subtotal - szCell[i];
38645       cntNew[k] = i;
38646       if( leafData ){ i--; }
38647       subtotal = 0;
38648       k++;
38649     }
38650   }
38651   szNew[k] = subtotal;
38652   cntNew[k] = nCell;
38653   k++;
38654
38655   /*
38656   ** The packing computed by the previous block is biased toward the siblings
38657   ** on the left side.  The left siblings are always nearly full, while the
38658   ** right-most sibling might be nearly empty.  This block of code attempts
38659   ** to adjust the packing of siblings to get a better balance.
38660   **
38661   ** This adjustment is more than an optimization.  The packing above might
38662   ** be so out of balance as to be illegal.  For example, the right-most
38663   ** sibling might be completely empty.  This adjustment is not optional.
38664   */
38665   for(i=k-1; i>0; i--){
38666     int szRight = szNew[i];  /* Size of sibling on the right */
38667     int szLeft = szNew[i-1]; /* Size of sibling on the left */
38668     int r;              /* Index of right-most cell in left sibling */
38669     int d;              /* Index of first cell to the left of right sibling */
38670
38671     r = cntNew[i-1] - 1;
38672     d = r + 1 - leafData;
38673     assert( d<nMaxCells );
38674     assert( r<nMaxCells );
38675     while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
38676       szRight += szCell[d] + 2;
38677       szLeft -= szCell[r] + 2;
38678       cntNew[i-1]--;
38679       r = cntNew[i-1] - 1;
38680       d = r + 1 - leafData;
38681     }
38682     szNew[i] = szRight;
38683     szNew[i-1] = szLeft;
38684   }
38685
38686   /* Either we found one or more cells (cntnew[0])>0) or we are the
38687   ** a virtual root page.  A virtual root page is when the real root
38688   ** page is page 1 and we are the only child of that page.
38689   */
38690   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
38691
38692   /*
38693   ** Allocate k new pages.  Reuse old pages where possible.
38694   */
38695   assert( pPage->pgno>1 );
38696   pageFlags = pPage->aData[0];
38697   for(i=0; i<k; i++){
38698     MemPage *pNew;
38699     if( i<nOld ){
38700       pNew = apNew[i] = apOld[i];
38701       pgnoNew[i] = pgnoOld[i];
38702       apOld[i] = 0;
38703       rc = sqlite3PagerWrite(pNew->pDbPage);
38704       nNew++;
38705       if( rc ) goto balance_cleanup;
38706     }else{
38707       assert( i>0 );
38708       rc = allocateBtreePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0);
38709       if( rc ) goto balance_cleanup;
38710       apNew[i] = pNew;
38711       nNew++;
38712     }
38713   }
38714
38715   /* Free any old pages that were not reused as new pages.
38716   */
38717   while( i<nOld ){
38718     rc = freePage(apOld[i]);
38719     if( rc ) goto balance_cleanup;
38720     releasePage(apOld[i]);
38721     apOld[i] = 0;
38722     i++;
38723   }
38724
38725   /*
38726   ** Put the new pages in accending order.  This helps to
38727   ** keep entries in the disk file in order so that a scan
38728   ** of the table is a linear scan through the file.  That
38729   ** in turn helps the operating system to deliver pages
38730   ** from the disk more rapidly.
38731   **
38732   ** An O(n^2) insertion sort algorithm is used, but since
38733   ** n is never more than NB (a small constant), that should
38734   ** not be a problem.
38735   **
38736   ** When NB==3, this one optimization makes the database
38737   ** about 25% faster for large insertions and deletions.
38738   */
38739   for(i=0; i<k-1; i++){
38740     int minV = pgnoNew[i];
38741     int minI = i;
38742     for(j=i+1; j<k; j++){
38743       if( pgnoNew[j]<(unsigned)minV ){
38744         minI = j;
38745         minV = pgnoNew[j];
38746       }
38747     }
38748     if( minI>i ){
38749       int t;
38750       MemPage *pT;
38751       t = pgnoNew[i];
38752       pT = apNew[i];
38753       pgnoNew[i] = pgnoNew[minI];
38754       apNew[i] = apNew[minI];
38755       pgnoNew[minI] = t;
38756       apNew[minI] = pT;
38757     }
38758   }
38759   TRACE(("BALANCE: old: %d %d %d  new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
38760     pgnoOld[0], 
38761     nOld>=2 ? pgnoOld[1] : 0,
38762     nOld>=3 ? pgnoOld[2] : 0,
38763     pgnoNew[0], szNew[0],
38764     nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
38765     nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
38766     nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
38767     nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
38768
38769   /*
38770   ** Evenly distribute the data in apCell[] across the new pages.
38771   ** Insert divider cells into pParent as necessary.
38772   */
38773   j = 0;
38774   for(i=0; i<nNew; i++){
38775     /* Assemble the new sibling page. */
38776     MemPage *pNew = apNew[i];
38777     assert( j<nMaxCells );
38778     assert( pNew->pgno==pgnoNew[i] );
38779     zeroPage(pNew, pageFlags);
38780     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
38781     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
38782     assert( pNew->nOverflow==0 );
38783
38784     /* If this is an auto-vacuum database, update the pointer map entries
38785     ** that point to the siblings that were rearranged. These can be: left
38786     ** children of cells, the right-child of the page, or overflow pages
38787     ** pointed to by cells.
38788     */
38789     if( ISAUTOVACUUM ){
38790       for(k=j; k<cntNew[i]; k++){
38791         assert( k<nMaxCells );
38792         if( aFrom[k]==0xFF || apCopy[aFrom[k]]->pgno!=pNew->pgno ){
38793           rc = ptrmapPutOvfl(pNew, k-j);
38794           if( rc==SQLITE_OK && leafCorrection==0 ){
38795             rc = ptrmapPut(pBt, get4byte(apCell[k]), PTRMAP_BTREE, pNew->pgno);
38796           }
38797           if( rc!=SQLITE_OK ){
38798             goto balance_cleanup;
38799           }
38800         }
38801       }
38802     }
38803
38804     j = cntNew[i];
38805
38806     /* If the sibling page assembled above was not the right-most sibling,
38807     ** insert a divider cell into the parent page.
38808     */
38809     if( i<nNew-1 && j<nCell ){
38810       u8 *pCell;
38811       u8 *pTemp;
38812       int sz;
38813
38814       assert( j<nMaxCells );
38815       pCell = apCell[j];
38816       sz = szCell[j] + leafCorrection;
38817       pTemp = &aSpace2[iSpace2];
38818       if( !pNew->leaf ){
38819         memcpy(&pNew->aData[8], pCell, 4);
38820         if( ISAUTOVACUUM 
38821          && (aFrom[j]==0xFF || apCopy[aFrom[j]]->pgno!=pNew->pgno)
38822         ){
38823           rc = ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno);
38824           if( rc!=SQLITE_OK ){
38825             goto balance_cleanup;
38826           }
38827         }
38828       }else if( leafData ){
38829         /* If the tree is a leaf-data tree, and the siblings are leaves, 
38830         ** then there is no divider cell in apCell[]. Instead, the divider 
38831         ** cell consists of the integer key for the right-most cell of 
38832         ** the sibling-page assembled above only.
38833         */
38834         CellInfo info;
38835         j--;
38836         sqlite3BtreeParseCellPtr(pNew, apCell[j], &info);
38837         pCell = pTemp;
38838         fillInCell(pParent, pCell, 0, info.nKey, 0, 0, 0, &sz);
38839         pTemp = 0;
38840       }else{
38841         pCell -= 4;
38842         /* Obscure case for non-leaf-data trees: If the cell at pCell was
38843         ** previously stored on a leaf node, and its reported size was 4
38844         ** bytes, then it may actually be smaller than this 
38845         ** (see sqlite3BtreeParseCellPtr(), 4 bytes is the minimum size of
38846         ** any cell). But it is important to pass the correct size to 
38847         ** insertCell(), so reparse the cell now.
38848         **
38849         ** Note that this can never happen in an SQLite data file, as all
38850         ** cells are at least 4 bytes. It only happens in b-trees used
38851         ** to evaluate "IN (SELECT ...)" and similar clauses.
38852         */
38853         if( szCell[j]==4 ){
38854           assert(leafCorrection==4);
38855           sz = cellSizePtr(pParent, pCell);
38856         }
38857       }
38858       iSpace2 += sz;
38859       assert( sz<=pBt->pageSize/4 );
38860       assert( iSpace2<=pBt->pageSize );
38861       rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4);
38862       if( rc!=SQLITE_OK ) goto balance_cleanup;
38863       put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
38864
38865       /* If this is an auto-vacuum database, and not a leaf-data tree,
38866       ** then update the pointer map with an entry for the overflow page
38867       ** that the cell just inserted points to (if any).
38868       */
38869       if( ISAUTOVACUUM && !leafData ){
38870         rc = ptrmapPutOvfl(pParent, nxDiv);
38871         if( rc!=SQLITE_OK ){
38872           goto balance_cleanup;
38873         }
38874       }
38875       j++;
38876       nxDiv++;
38877     }
38878
38879     /* Set the pointer-map entry for the new sibling page. */
38880     if( ISAUTOVACUUM ){
38881       rc = ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno);
38882       if( rc!=SQLITE_OK ){
38883         goto balance_cleanup;
38884       }
38885     }
38886   }
38887   assert( j==nCell );
38888   assert( nOld>0 );
38889   assert( nNew>0 );
38890   if( (pageFlags & PTF_LEAF)==0 ){
38891     u8 *zChild = &apCopy[nOld-1]->aData[8];
38892     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
38893     if( ISAUTOVACUUM ){
38894       rc = ptrmapPut(pBt, get4byte(zChild), PTRMAP_BTREE, apNew[nNew-1]->pgno);
38895       if( rc!=SQLITE_OK ){
38896         goto balance_cleanup;
38897       }
38898     }
38899   }
38900   if( nxDiv==pParent->nCell+pParent->nOverflow ){
38901     /* Right-most sibling is the right-most child of pParent */
38902     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
38903   }else{
38904     /* Right-most sibling is the left child of the first entry in pParent
38905     ** past the right-most divider entry */
38906     put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
38907   }
38908
38909   /*
38910   ** Reparent children of all cells.
38911   */
38912   for(i=0; i<nNew; i++){
38913     rc = reparentChildPages(apNew[i], 0);
38914     if( rc!=SQLITE_OK ) goto balance_cleanup;
38915   }
38916   rc = reparentChildPages(pParent, 0);
38917   if( rc!=SQLITE_OK ) goto balance_cleanup;
38918
38919   /*
38920   ** Balance the parent page.  Note that the current page (pPage) might
38921   ** have been added to the freelist so it might no longer be initialized.
38922   ** But the parent page will always be initialized.
38923   */
38924   assert( pParent->isInit==PAGE_ISINIT_FULL );
38925   sqlite3ScratchFree(apCell);
38926   apCell = 0;
38927   rc = balance(pParent, 0);
38928   
38929   /*
38930   ** Cleanup before returning.
38931   */
38932 balance_cleanup:
38933   sqlite3PageFree(aSpace2);
38934   sqlite3ScratchFree(apCell);
38935   for(i=0; i<nOld; i++){
38936     releasePage(apOld[i]);
38937   }
38938   for(i=0; i<nNew; i++){
38939     releasePage(apNew[i]);
38940   }
38941
38942   releasePage(pParent);
38943   TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
38944           pPage->pgno, nOld, nNew, nCell));
38945
38946   return rc;
38947 }
38948
38949 /*
38950 ** This routine is called for the root page of a btree when the root
38951 ** page contains no cells.  This is an opportunity to make the tree
38952 ** shallower by one level.
38953 */
38954 static int balance_shallower(MemPage *pPage){
38955   MemPage *pChild;             /* The only child page of pPage */
38956   Pgno pgnoChild;              /* Page number for pChild */
38957   int rc = SQLITE_OK;          /* Return code from subprocedures */
38958   BtShared *pBt;                  /* The main BTree structure */
38959   int mxCellPerPage;           /* Maximum number of cells per page */
38960   u8 **apCell;                 /* All cells from pages being balanced */
38961   u16 *szCell;                 /* Local size of all cells */
38962
38963   assert( pPage->pParent==0 );
38964   assert( pPage->nCell==0 );
38965   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38966   pBt = pPage->pBt;
38967   mxCellPerPage = MX_CELL(pBt);
38968   apCell = sqlite3Malloc( mxCellPerPage*(sizeof(u8*)+sizeof(u16)) );
38969   if( apCell==0 ) return SQLITE_NOMEM;
38970   szCell = (u16*)&apCell[mxCellPerPage];
38971   if( pPage->leaf ){
38972     /* The table is completely empty */
38973     TRACE(("BALANCE: empty table %d\n", pPage->pgno));
38974   }else{
38975     /* The root page is empty but has one child.  Transfer the
38976     ** information from that one child into the root page if it 
38977     ** will fit.  This reduces the depth of the tree by one.
38978     **
38979     ** If the root page is page 1, it has less space available than
38980     ** its child (due to the 100 byte header that occurs at the beginning
38981     ** of the database fle), so it might not be able to hold all of the 
38982     ** information currently contained in the child.  If this is the 
38983     ** case, then do not do the transfer.  Leave page 1 empty except
38984     ** for the right-pointer to the child page.  The child page becomes
38985     ** the virtual root of the tree.
38986     */
38987     pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
38988     assert( pgnoChild>0 );
38989     assert( pgnoChild<=pagerPagecount(pPage->pBt->pPager) );
38990     rc = sqlite3BtreeGetPage(pPage->pBt, pgnoChild, &pChild, 0);
38991     if( rc ) goto end_shallow_balance;
38992     if( pPage->pgno==1 ){
38993       rc = sqlite3BtreeInitPage(pChild, pPage);
38994       if( rc ) goto end_shallow_balance;
38995       assert( pChild->nOverflow==0 );
38996       if( pChild->nFree>=100 ){
38997         /* The child information will fit on the root page, so do the
38998         ** copy */
38999         int i;
39000         zeroPage(pPage, pChild->aData[0]);
39001         for(i=0; i<pChild->nCell; i++){
39002           apCell[i] = findCell(pChild,i);
39003           szCell[i] = cellSizePtr(pChild, apCell[i]);
39004         }
39005         assemblePage(pPage, pChild->nCell, apCell, szCell);
39006         /* Copy the right-pointer of the child to the parent. */
39007         put4byte(&pPage->aData[pPage->hdrOffset+8], 
39008             get4byte(&pChild->aData[pChild->hdrOffset+8]));
39009         freePage(pChild);
39010         TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
39011       }else{
39012         /* The child has more information that will fit on the root.
39013         ** The tree is already balanced.  Do nothing. */
39014         TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
39015       }
39016     }else{
39017       memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
39018       pPage->isInit = 0;
39019       pPage->pParent = 0;
39020       rc = sqlite3BtreeInitPage(pPage, 0);
39021       assert( rc==SQLITE_OK );
39022       freePage(pChild);
39023       TRACE(("BALANCE: transfer child %d into root %d\n",
39024               pChild->pgno, pPage->pgno));
39025     }
39026     rc = reparentChildPages(pPage, 1);
39027     assert( pPage->nOverflow==0 );
39028     if( ISAUTOVACUUM ){
39029       int i;
39030       for(i=0; i<pPage->nCell; i++){ 
39031         rc = ptrmapPutOvfl(pPage, i);
39032         if( rc!=SQLITE_OK ){
39033           goto end_shallow_balance;
39034         }
39035       }
39036     }
39037     releasePage(pChild);
39038   }
39039 end_shallow_balance:
39040   sqlite3_free(apCell);
39041   return rc;
39042 }
39043
39044
39045 /*
39046 ** The root page is overfull
39047 **
39048 ** When this happens, Create a new child page and copy the
39049 ** contents of the root into the child.  Then make the root
39050 ** page an empty page with rightChild pointing to the new
39051 ** child.   Finally, call balance_internal() on the new child
39052 ** to cause it to split.
39053 */
39054 static int balance_deeper(MemPage *pPage){
39055   int rc;             /* Return value from subprocedures */
39056   MemPage *pChild;    /* Pointer to a new child page */
39057   Pgno pgnoChild;     /* Page number of the new child page */
39058   BtShared *pBt;         /* The BTree */
39059   int usableSize;     /* Total usable size of a page */
39060   u8 *data;           /* Content of the parent page */
39061   u8 *cdata;          /* Content of the child page */
39062   int hdr;            /* Offset to page header in parent */
39063   int cbrk;           /* Offset to content of first cell in parent */
39064
39065   assert( pPage->pParent==0 );
39066   assert( pPage->nOverflow>0 );
39067   pBt = pPage->pBt;
39068   assert( sqlite3_mutex_held(pBt->mutex) );
39069   rc = allocateBtreePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0);
39070   if( rc ) return rc;
39071   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
39072   usableSize = pBt->usableSize;
39073   data = pPage->aData;
39074   hdr = pPage->hdrOffset;
39075   cbrk = get2byte(&data[hdr+5]);
39076   cdata = pChild->aData;
39077   memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
39078   memcpy(&cdata[cbrk], &data[cbrk], usableSize-cbrk);
39079   if( pChild->isInit==PAGE_ISINIT_FULL ) return SQLITE_CORRUPT;
39080   rc = sqlite3BtreeInitPage(pChild, pPage);
39081   if( rc ) goto balancedeeper_out;
39082   memcpy(pChild->aOvfl, pPage->aOvfl, pPage->nOverflow*sizeof(pPage->aOvfl[0]));
39083   pChild->nOverflow = pPage->nOverflow;
39084   if( pChild->nOverflow ){
39085     pChild->nFree = 0;
39086   }
39087   assert( pChild->nCell==pPage->nCell );
39088   zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
39089   put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
39090   TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
39091   if( ISAUTOVACUUM ){
39092     int i;
39093     rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno);
39094     if( rc ) goto balancedeeper_out;
39095     for(i=0; i<pChild->nCell; i++){
39096       rc = ptrmapPutOvfl(pChild, i);
39097       if( rc!=SQLITE_OK ){
39098         goto balancedeeper_out;
39099       }
39100     }
39101     rc = reparentChildPages(pChild, 1);
39102   }
39103   if( rc==SQLITE_OK ){
39104     rc = balance_nonroot(pChild);
39105   }
39106
39107 balancedeeper_out:
39108   releasePage(pChild);
39109   return rc;
39110 }
39111
39112 /*
39113 ** Decide if the page pPage needs to be balanced.  If balancing is
39114 ** required, call the appropriate balancing routine.
39115 */
39116 static int balance(MemPage *pPage, int insert){
39117   int rc = SQLITE_OK;
39118   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
39119   if( pPage->pParent==0 ){
39120     rc = sqlite3PagerWrite(pPage->pDbPage);
39121     if( rc==SQLITE_OK && pPage->nOverflow>0 ){
39122       rc = balance_deeper(pPage);
39123     }
39124     if( rc==SQLITE_OK && pPage->nCell==0 ){
39125       rc = balance_shallower(pPage);
39126     }
39127   }else{
39128     if( pPage->nOverflow>0 || 
39129         (!insert && pPage->nFree>pPage->pBt->usableSize*2/3) ){
39130       rc = balance_nonroot(pPage);
39131     }
39132   }
39133   return rc;
39134 }
39135
39136 /*
39137 ** This routine checks all cursors that point to table pgnoRoot.
39138 ** If any of those cursors were opened with wrFlag==0 in a different
39139 ** database connection (a database connection that shares the pager
39140 ** cache with the current connection) and that other connection 
39141 ** is not in the ReadUncommmitted state, then this routine returns 
39142 ** SQLITE_LOCKED.
39143 **
39144 ** As well as cursors with wrFlag==0, cursors with wrFlag==1 and 
39145 ** isIncrblobHandle==1 are also considered 'read' cursors. Incremental 
39146 ** blob cursors are used for both reading and writing.
39147 **
39148 ** When pgnoRoot is the root page of an intkey table, this function is also
39149 ** responsible for invalidating incremental blob cursors when the table row
39150 ** on which they are opened is deleted or modified. Cursors are invalidated
39151 ** according to the following rules:
39152 **
39153 **   1) When BtreeClearTable() is called to completely delete the contents
39154 **      of a B-Tree table, pExclude is set to zero and parameter iRow is 
39155 **      set to non-zero. In this case all incremental blob cursors open
39156 **      on the table rooted at pgnoRoot are invalidated.
39157 **
39158 **   2) When BtreeInsert(), BtreeDelete() or BtreePutData() is called to 
39159 **      modify a table row via an SQL statement, pExclude is set to the 
39160 **      write cursor used to do the modification and parameter iRow is set
39161 **      to the integer row id of the B-Tree entry being modified. Unless
39162 **      pExclude is itself an incremental blob cursor, then all incremental
39163 **      blob cursors open on row iRow of the B-Tree are invalidated.
39164 **
39165 **   3) If both pExclude and iRow are set to zero, no incremental blob 
39166 **      cursors are invalidated.
39167 */
39168 static int checkReadLocks(
39169   Btree *pBtree, 
39170   Pgno pgnoRoot, 
39171   BtCursor *pExclude,
39172   i64 iRow
39173 ){
39174   BtCursor *p;
39175   BtShared *pBt = pBtree->pBt;
39176   sqlite3 *db = pBtree->db;
39177   assert( sqlite3BtreeHoldsMutex(pBtree) );
39178   for(p=pBt->pCursor; p; p=p->pNext){
39179     if( p==pExclude ) continue;
39180     if( p->pgnoRoot!=pgnoRoot ) continue;
39181 #ifndef SQLITE_OMIT_INCRBLOB
39182     if( p->isIncrblobHandle && ( 
39183          (!pExclude && iRow)
39184       || (pExclude && !pExclude->isIncrblobHandle && p->info.nKey==iRow)
39185     )){
39186       p->eState = CURSOR_INVALID;
39187     }
39188 #endif
39189     if( p->eState!=CURSOR_VALID ) continue;
39190     if( p->wrFlag==0 
39191 #ifndef SQLITE_OMIT_INCRBLOB
39192      || p->isIncrblobHandle
39193 #endif
39194     ){
39195       sqlite3 *dbOther = p->pBtree->db;
39196       if( dbOther==0 ||
39197          (dbOther!=db && (dbOther->flags & SQLITE_ReadUncommitted)==0) ){
39198         return SQLITE_LOCKED;
39199       }
39200     }
39201   }
39202   return SQLITE_OK;
39203 }
39204
39205 /*
39206 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
39207 ** and the data is given by (pData,nData).  The cursor is used only to
39208 ** define what table the record should be inserted into.  The cursor
39209 ** is left pointing at a random location.
39210 **
39211 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
39212 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
39213 */
39214 SQLITE_PRIVATE int sqlite3BtreeInsert(
39215   BtCursor *pCur,                /* Insert data into the table of this cursor */
39216   const void *pKey, i64 nKey,    /* The key of the new record */
39217   const void *pData, int nData,  /* The data of the new record */
39218   int nZero,                     /* Number of extra 0 bytes to append to data */
39219   int appendBias                 /* True if this is likely an append */
39220 ){
39221   int rc;
39222   int loc;
39223   int szNew;
39224   MemPage *pPage;
39225   Btree *p = pCur->pBtree;
39226   BtShared *pBt = p->pBt;
39227   unsigned char *oldCell;
39228   unsigned char *newCell = 0;
39229
39230   assert( cursorHoldsMutex(pCur) );
39231   if( pBt->inTransaction!=TRANS_WRITE ){
39232     /* Must start a transaction before doing an insert */
39233     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
39234     return rc;
39235   }
39236   assert( !pBt->readOnly );
39237   if( !pCur->wrFlag ){
39238     return SQLITE_PERM;   /* Cursor not open for writing */
39239   }
39240   if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur, nKey) ){
39241     return SQLITE_LOCKED; /* The table pCur points to has a read lock */
39242   }
39243   if( pCur->eState==CURSOR_FAULT ){
39244     return pCur->skip;
39245   }
39246
39247   /* Save the positions of any other cursors open on this table */
39248   clearCursorPosition(pCur);
39249   if( 
39250     SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
39251     SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, nKey, appendBias, &loc))
39252   ){
39253     return rc;
39254   }
39255
39256   pPage = pCur->pPage;
39257   assert( pPage->intKey || nKey>=0 );
39258   assert( pPage->leaf || !pPage->intKey );
39259   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
39260           pCur->pgnoRoot, nKey, nData, pPage->pgno,
39261           loc==0 ? "overwrite" : "new entry"));
39262   assert( pPage->isInit==PAGE_ISINIT_FULL );
39263   allocateTempSpace(pBt);
39264   newCell = pBt->pTmpSpace;
39265   if( newCell==0 ) return SQLITE_NOMEM;
39266   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
39267   if( rc ) goto end_insert;
39268   assert( szNew==cellSizePtr(pPage, newCell) );
39269   assert( szNew<=MX_CELL_SIZE(pBt) );
39270   if( loc==0 && CURSOR_VALID==pCur->eState ){
39271     u16 szOld;
39272     assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
39273     rc = sqlite3PagerWrite(pPage->pDbPage);
39274     if( rc ){
39275       goto end_insert;
39276     }
39277     oldCell = findCell(pPage, pCur->idx);
39278     if( !pPage->leaf ){
39279       memcpy(newCell, oldCell, 4);
39280     }
39281     szOld = cellSizePtr(pPage, oldCell);
39282     rc = clearCell(pPage, oldCell);
39283     if( rc ) goto end_insert;
39284     dropCell(pPage, pCur->idx, szOld);
39285   }else if( loc<0 && pPage->nCell>0 ){
39286     assert( pPage->leaf );
39287     pCur->idx++;
39288     pCur->info.nSize = 0;
39289     pCur->validNKey = 0;
39290   }else{
39291     assert( pPage->leaf );
39292   }
39293   rc = insertCell(pPage, pCur->idx, newCell, szNew, 0, 0);
39294   if( rc!=SQLITE_OK ) goto end_insert;
39295   rc = balance(pPage, 1);
39296   if( rc==SQLITE_OK ){
39297     moveToRoot(pCur);
39298   }
39299 end_insert:
39300   return rc;
39301 }
39302
39303 /*
39304 ** Delete the entry that the cursor is pointing to.  The cursor
39305 ** is left pointing at a random location.
39306 */
39307 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
39308   MemPage *pPage = pCur->pPage;
39309   unsigned char *pCell;
39310   int rc;
39311   Pgno pgnoChild = 0;
39312   Btree *p = pCur->pBtree;
39313   BtShared *pBt = p->pBt;
39314
39315   assert( cursorHoldsMutex(pCur) );
39316   assert( pPage->isInit==PAGE_ISINIT_FULL );
39317   if( pBt->inTransaction!=TRANS_WRITE ){
39318     /* Must start a transaction before doing a delete */
39319     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
39320     return rc;
39321   }
39322   assert( !pBt->readOnly );
39323   if( pCur->eState==CURSOR_FAULT ){
39324     return pCur->skip;
39325   }
39326   if( pCur->idx >= pPage->nCell ){
39327     return SQLITE_ERROR;  /* The cursor is not pointing to anything */
39328   }
39329   if( !pCur->wrFlag ){
39330     return SQLITE_PERM;   /* Did not open this cursor for writing */
39331   }
39332   if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur, pCur->info.nKey) ){
39333     return SQLITE_LOCKED; /* The table pCur points to has a read lock */
39334   }
39335
39336   /* Restore the current cursor position (a no-op if the cursor is not in 
39337   ** CURSOR_REQUIRESEEK state) and save the positions of any other cursors 
39338   ** open on the same table. Then call sqlite3PagerWrite() on the page
39339   ** that the entry will be deleted from.
39340   */
39341   if( 
39342     (rc = restoreCursorPosition(pCur))!=0 ||
39343     (rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur))!=0 ||
39344     (rc = sqlite3PagerWrite(pPage->pDbPage))!=0
39345   ){
39346     return rc;
39347   }
39348
39349   /* Locate the cell within its page and leave pCell pointing to the
39350   ** data. The clearCell() call frees any overflow pages associated with the
39351   ** cell. The cell itself is still intact.
39352   */
39353   pCell = findCell(pPage, pCur->idx);
39354   if( !pPage->leaf ){
39355     pgnoChild = get4byte(pCell);
39356   }
39357   rc = clearCell(pPage, pCell);
39358   if( rc ){
39359     return rc;
39360   }
39361
39362   if( !pPage->leaf ){
39363     /*
39364     ** The entry we are about to delete is not a leaf so if we do not
39365     ** do something we will leave a hole on an internal page.
39366     ** We have to fill the hole by moving in a cell from a leaf.  The
39367     ** next Cell after the one to be deleted is guaranteed to exist and
39368     ** to be a leaf so we can use it.
39369     */
39370     BtCursor leafCur;
39371     unsigned char *pNext;
39372     int notUsed;
39373     unsigned char *tempCell = 0;
39374     assert( !pPage->intKey );
39375     sqlite3BtreeGetTempCursor(pCur, &leafCur);
39376     rc = sqlite3BtreeNext(&leafCur, &notUsed);
39377     if( rc==SQLITE_OK ){
39378       rc = sqlite3PagerWrite(leafCur.pPage->pDbPage);
39379     }
39380     if( rc==SQLITE_OK ){
39381       u16 szNext;
39382       TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
39383          pCur->pgnoRoot, pPage->pgno, leafCur.pPage->pgno));
39384       dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
39385       pNext = findCell(leafCur.pPage, leafCur.idx);
39386       szNext = cellSizePtr(leafCur.pPage, pNext);
39387       assert( MX_CELL_SIZE(pBt)>=szNext+4 );
39388       allocateTempSpace(pBt);
39389       tempCell = pBt->pTmpSpace;
39390       if( tempCell==0 ){
39391         rc = SQLITE_NOMEM;
39392       }
39393       if( rc==SQLITE_OK ){
39394         rc = insertCell(pPage, pCur->idx, pNext-4, szNext+4, tempCell, 0);
39395       }
39396       if( rc==SQLITE_OK ){
39397         put4byte(findOverflowCell(pPage, pCur->idx), pgnoChild);
39398         rc = balance(pPage, 0);
39399       }
39400       if( rc==SQLITE_OK ){
39401         dropCell(leafCur.pPage, leafCur.idx, szNext);
39402         rc = balance(leafCur.pPage, 0);
39403       }
39404     }
39405     sqlite3BtreeReleaseTempCursor(&leafCur);
39406   }else{
39407     TRACE(("DELETE: table=%d delete from leaf %d\n",
39408        pCur->pgnoRoot, pPage->pgno));
39409     dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
39410     rc = balance(pPage, 0);
39411   }
39412   if( rc==SQLITE_OK ){
39413     moveToRoot(pCur);
39414   }
39415   return rc;
39416 }
39417
39418 /*
39419 ** Create a new BTree table.  Write into *piTable the page
39420 ** number for the root page of the new table.
39421 **
39422 ** The type of type is determined by the flags parameter.  Only the
39423 ** following values of flags are currently in use.  Other values for
39424 ** flags might not work:
39425 **
39426 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
39427 **     BTREE_ZERODATA                  Used for SQL indices
39428 */
39429 static int btreeCreateTable(Btree *p, int *piTable, int flags){
39430   BtShared *pBt = p->pBt;
39431   MemPage *pRoot;
39432   Pgno pgnoRoot;
39433   int rc;
39434
39435   assert( sqlite3BtreeHoldsMutex(p) );
39436   if( pBt->inTransaction!=TRANS_WRITE ){
39437     /* Must start a transaction first */
39438     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
39439     return rc;
39440   }
39441   assert( !pBt->readOnly );
39442
39443 #ifdef SQLITE_OMIT_AUTOVACUUM
39444   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
39445   if( rc ){
39446     return rc;
39447   }
39448 #else
39449   if( pBt->autoVacuum ){
39450     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
39451     MemPage *pPageMove; /* The page to move to. */
39452
39453     /* Creating a new table may probably require moving an existing database
39454     ** to make room for the new tables root page. In case this page turns
39455     ** out to be an overflow page, delete all overflow page-map caches
39456     ** held by open cursors.
39457     */
39458     invalidateAllOverflowCache(pBt);
39459
39460     /* Read the value of meta[3] from the database to determine where the
39461     ** root page of the new table should go. meta[3] is the largest root-page
39462     ** created so far, so the new root-page is (meta[3]+1).
39463     */
39464     rc = sqlite3BtreeGetMeta(p, 4, &pgnoRoot);
39465     if( rc!=SQLITE_OK ){
39466       return rc;
39467     }
39468     pgnoRoot++;
39469
39470     /* The new root-page may not be allocated on a pointer-map page, or the
39471     ** PENDING_BYTE page.
39472     */
39473     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
39474         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
39475       pgnoRoot++;
39476     }
39477     assert( pgnoRoot>=3 );
39478
39479     /* Allocate a page. The page that currently resides at pgnoRoot will
39480     ** be moved to the allocated page (unless the allocated page happens
39481     ** to reside at pgnoRoot).
39482     */
39483     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
39484     if( rc!=SQLITE_OK ){
39485       return rc;
39486     }
39487
39488     if( pgnoMove!=pgnoRoot ){
39489       /* pgnoRoot is the page that will be used for the root-page of
39490       ** the new table (assuming an error did not occur). But we were
39491       ** allocated pgnoMove. If required (i.e. if it was not allocated
39492       ** by extending the file), the current page at position pgnoMove
39493       ** is already journaled.
39494       */
39495       u8 eType;
39496       Pgno iPtrPage;
39497
39498       releasePage(pPageMove);
39499
39500       /* Move the page currently at pgnoRoot to pgnoMove. */
39501       rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
39502       if( rc!=SQLITE_OK ){
39503         return rc;
39504       }
39505       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
39506       if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
39507         releasePage(pRoot);
39508         return rc;
39509       }
39510       assert( eType!=PTRMAP_ROOTPAGE );
39511       assert( eType!=PTRMAP_FREEPAGE );
39512       rc = sqlite3PagerWrite(pRoot->pDbPage);
39513       if( rc!=SQLITE_OK ){
39514         releasePage(pRoot);
39515         return rc;
39516       }
39517       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
39518       releasePage(pRoot);
39519
39520       /* Obtain the page at pgnoRoot */
39521       if( rc!=SQLITE_OK ){
39522         return rc;
39523       }
39524       rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
39525       if( rc!=SQLITE_OK ){
39526         return rc;
39527       }
39528       rc = sqlite3PagerWrite(pRoot->pDbPage);
39529       if( rc!=SQLITE_OK ){
39530         releasePage(pRoot);
39531         return rc;
39532       }
39533     }else{
39534       pRoot = pPageMove;
39535     } 
39536
39537     /* Update the pointer-map and meta-data with the new root-page number. */
39538     rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
39539     if( rc ){
39540       releasePage(pRoot);
39541       return rc;
39542     }
39543     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
39544     if( rc ){
39545       releasePage(pRoot);
39546       return rc;
39547     }
39548
39549   }else{
39550     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
39551     if( rc ) return rc;
39552   }
39553 #endif
39554   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
39555   zeroPage(pRoot, flags | PTF_LEAF);
39556   sqlite3PagerUnref(pRoot->pDbPage);
39557   *piTable = (int)pgnoRoot;
39558   return SQLITE_OK;
39559 }
39560 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
39561   int rc;
39562   sqlite3BtreeEnter(p);
39563   p->pBt->db = p->db;
39564   rc = btreeCreateTable(p, piTable, flags);
39565   sqlite3BtreeLeave(p);
39566   return rc;
39567 }
39568
39569 /*
39570 ** Erase the given database page and all its children.  Return
39571 ** the page to the freelist.
39572 */
39573 static int clearDatabasePage(
39574   BtShared *pBt,           /* The BTree that contains the table */
39575   Pgno pgno,            /* Page number to clear */
39576   MemPage *pParent,     /* Parent page.  NULL for the root */
39577   int freePageFlag      /* Deallocate page if true */
39578 ){
39579   MemPage *pPage = 0;
39580   int rc;
39581   unsigned char *pCell;
39582   int i;
39583
39584   assert( sqlite3_mutex_held(pBt->mutex) );
39585   if( pgno>pagerPagecount(pBt->pPager) ){
39586     return SQLITE_CORRUPT_BKPT;
39587   }
39588
39589   rc = getAndInitPage(pBt, pgno, &pPage, pParent);
39590   if( rc ) goto cleardatabasepage_out;
39591   for(i=0; i<pPage->nCell; i++){
39592     pCell = findCell(pPage, i);
39593     if( !pPage->leaf ){
39594       rc = clearDatabasePage(pBt, get4byte(pCell), pPage, 1);
39595       if( rc ) goto cleardatabasepage_out;
39596     }
39597     rc = clearCell(pPage, pCell);
39598     if( rc ) goto cleardatabasepage_out;
39599   }
39600   if( !pPage->leaf ){
39601     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), pPage, 1);
39602     if( rc ) goto cleardatabasepage_out;
39603   }
39604   if( freePageFlag ){
39605     rc = freePage(pPage);
39606   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
39607     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
39608   }
39609
39610 cleardatabasepage_out:
39611   releasePage(pPage);
39612   return rc;
39613 }
39614
39615 /*
39616 ** Delete all information from a single table in the database.  iTable is
39617 ** the page number of the root of the table.  After this routine returns,
39618 ** the root page is empty, but still exists.
39619 **
39620 ** This routine will fail with SQLITE_LOCKED if there are any open
39621 ** read cursors on the table.  Open write cursors are moved to the
39622 ** root of the table.
39623 */
39624 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable){
39625   int rc;
39626   BtShared *pBt = p->pBt;
39627   sqlite3BtreeEnter(p);
39628   pBt->db = p->db;
39629   if( p->inTrans!=TRANS_WRITE ){
39630     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
39631   }else if( (rc = checkReadLocks(p, iTable, 0, 1))!=SQLITE_OK ){
39632     /* nothing to do */
39633   }else if( SQLITE_OK!=(rc = saveAllCursors(pBt, iTable, 0)) ){
39634     /* nothing to do */
39635   }else{
39636     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, 0);
39637   }
39638   sqlite3BtreeLeave(p);
39639   return rc;
39640 }
39641
39642 /*
39643 ** Erase all information in a table and add the root of the table to
39644 ** the freelist.  Except, the root of the principle table (the one on
39645 ** page 1) is never added to the freelist.
39646 **
39647 ** This routine will fail with SQLITE_LOCKED if there are any open
39648 ** cursors on the table.
39649 **
39650 ** If AUTOVACUUM is enabled and the page at iTable is not the last
39651 ** root page in the database file, then the last root page 
39652 ** in the database file is moved into the slot formerly occupied by
39653 ** iTable and that last slot formerly occupied by the last root page
39654 ** is added to the freelist instead of iTable.  In this say, all
39655 ** root pages are kept at the beginning of the database file, which
39656 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
39657 ** page number that used to be the last root page in the file before
39658 ** the move.  If no page gets moved, *piMoved is set to 0.
39659 ** The last root page is recorded in meta[3] and the value of
39660 ** meta[3] is updated by this procedure.
39661 */
39662 static int btreeDropTable(Btree *p, int iTable, int *piMoved){
39663   int rc;
39664   MemPage *pPage = 0;
39665   BtShared *pBt = p->pBt;
39666
39667   assert( sqlite3BtreeHoldsMutex(p) );
39668   if( p->inTrans!=TRANS_WRITE ){
39669     return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
39670   }
39671
39672   /* It is illegal to drop a table if any cursors are open on the
39673   ** database. This is because in auto-vacuum mode the backend may
39674   ** need to move another root-page to fill a gap left by the deleted
39675   ** root page. If an open cursor was using this page a problem would 
39676   ** occur.
39677   */
39678   if( pBt->pCursor ){
39679     return SQLITE_LOCKED;
39680   }
39681
39682   rc = sqlite3BtreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
39683   if( rc ) return rc;
39684   rc = sqlite3BtreeClearTable(p, iTable);
39685   if( rc ){
39686     releasePage(pPage);
39687     return rc;
39688   }
39689
39690   *piMoved = 0;
39691
39692   if( iTable>1 ){
39693 #ifdef SQLITE_OMIT_AUTOVACUUM
39694     rc = freePage(pPage);
39695     releasePage(pPage);
39696 #else
39697     if( pBt->autoVacuum ){
39698       Pgno maxRootPgno;
39699       rc = sqlite3BtreeGetMeta(p, 4, &maxRootPgno);
39700       if( rc!=SQLITE_OK ){
39701         releasePage(pPage);
39702         return rc;
39703       }
39704
39705       if( iTable==maxRootPgno ){
39706         /* If the table being dropped is the table with the largest root-page
39707         ** number in the database, put the root page on the free list. 
39708         */
39709         rc = freePage(pPage);
39710         releasePage(pPage);
39711         if( rc!=SQLITE_OK ){
39712           return rc;
39713         }
39714       }else{
39715         /* The table being dropped does not have the largest root-page
39716         ** number in the database. So move the page that does into the 
39717         ** gap left by the deleted root-page.
39718         */
39719         MemPage *pMove;
39720         releasePage(pPage);
39721         rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
39722         if( rc!=SQLITE_OK ){
39723           return rc;
39724         }
39725         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
39726         releasePage(pMove);
39727         if( rc!=SQLITE_OK ){
39728           return rc;
39729         }
39730         rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
39731         if( rc!=SQLITE_OK ){
39732           return rc;
39733         }
39734         rc = freePage(pMove);
39735         releasePage(pMove);
39736         if( rc!=SQLITE_OK ){
39737           return rc;
39738         }
39739         *piMoved = maxRootPgno;
39740       }
39741
39742       /* Set the new 'max-root-page' value in the database header. This
39743       ** is the old value less one, less one more if that happens to
39744       ** be a root-page number, less one again if that is the
39745       ** PENDING_BYTE_PAGE.
39746       */
39747       maxRootPgno--;
39748       if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
39749         maxRootPgno--;
39750       }
39751       if( maxRootPgno==PTRMAP_PAGENO(pBt, maxRootPgno) ){
39752         maxRootPgno--;
39753       }
39754       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
39755
39756       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
39757     }else{
39758       rc = freePage(pPage);
39759       releasePage(pPage);
39760     }
39761 #endif
39762   }else{
39763     /* If sqlite3BtreeDropTable was called on page 1. */
39764     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
39765     releasePage(pPage);
39766   }
39767   return rc;  
39768 }
39769 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
39770   int rc;
39771   sqlite3BtreeEnter(p);
39772   p->pBt->db = p->db;
39773   rc = btreeDropTable(p, iTable, piMoved);
39774   sqlite3BtreeLeave(p);
39775   return rc;
39776 }
39777
39778
39779 /*
39780 ** Read the meta-information out of a database file.  Meta[0]
39781 ** is the number of free pages currently in the database.  Meta[1]
39782 ** through meta[15] are available for use by higher layers.  Meta[0]
39783 ** is read-only, the others are read/write.
39784 ** 
39785 ** The schema layer numbers meta values differently.  At the schema
39786 ** layer (and the SetCookie and ReadCookie opcodes) the number of
39787 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
39788 */
39789 SQLITE_PRIVATE int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
39790   DbPage *pDbPage;
39791   int rc;
39792   unsigned char *pP1;
39793   BtShared *pBt = p->pBt;
39794
39795   sqlite3BtreeEnter(p);
39796   pBt->db = p->db;
39797
39798   /* Reading a meta-data value requires a read-lock on page 1 (and hence
39799   ** the sqlite_master table. We grab this lock regardless of whether or
39800   ** not the SQLITE_ReadUncommitted flag is set (the table rooted at page
39801   ** 1 is treated as a special case by queryTableLock() and lockTable()).
39802   */
39803   rc = queryTableLock(p, 1, READ_LOCK);
39804   if( rc!=SQLITE_OK ){
39805     sqlite3BtreeLeave(p);
39806     return rc;
39807   }
39808
39809   assert( idx>=0 && idx<=15 );
39810   if( pBt->pPage1 ){
39811     /* The b-tree is already holding a reference to page 1 of the database
39812     ** file. In this case the required meta-data value can be read directly
39813     ** from the page data of this reference. This is slightly faster than
39814     ** requesting a new reference from the pager layer.
39815     */
39816     pP1 = (unsigned char *)pBt->pPage1->aData;
39817   }else{
39818     /* The b-tree does not have a reference to page 1 of the database file.
39819     ** Obtain one from the pager layer.
39820     */
39821     rc = sqlite3PagerGet(pBt->pPager, 1, &pDbPage);
39822     if( rc ){
39823       sqlite3BtreeLeave(p);
39824       return rc;
39825     }
39826     pP1 = (unsigned char *)sqlite3PagerGetData(pDbPage);
39827   }
39828   *pMeta = get4byte(&pP1[36 + idx*4]);
39829
39830   /* If the b-tree is not holding a reference to page 1, then one was 
39831   ** requested from the pager layer in the above block. Release it now.
39832   */
39833   if( !pBt->pPage1 ){
39834     sqlite3PagerUnref(pDbPage);
39835   }
39836
39837   /* If autovacuumed is disabled in this build but we are trying to 
39838   ** access an autovacuumed database, then make the database readonly. 
39839   */
39840 #ifdef SQLITE_OMIT_AUTOVACUUM
39841   if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
39842 #endif
39843
39844   /* Grab the read-lock on page 1. */
39845   rc = lockTable(p, 1, READ_LOCK);
39846   sqlite3BtreeLeave(p);
39847   return rc;
39848 }
39849
39850 /*
39851 ** Write meta-information back into the database.  Meta[0] is
39852 ** read-only and may not be written.
39853 */
39854 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
39855   BtShared *pBt = p->pBt;
39856   unsigned char *pP1;
39857   int rc;
39858   assert( idx>=1 && idx<=15 );
39859   sqlite3BtreeEnter(p);
39860   pBt->db = p->db;
39861   if( p->inTrans!=TRANS_WRITE ){
39862     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
39863   }else{
39864     assert( pBt->pPage1!=0 );
39865     pP1 = pBt->pPage1->aData;
39866     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
39867     if( rc==SQLITE_OK ){
39868       put4byte(&pP1[36 + idx*4], iMeta);
39869 #ifndef SQLITE_OMIT_AUTOVACUUM
39870       if( idx==7 ){
39871         assert( pBt->autoVacuum || iMeta==0 );
39872         assert( iMeta==0 || iMeta==1 );
39873         pBt->incrVacuum = iMeta;
39874       }
39875 #endif
39876     }
39877   }
39878   sqlite3BtreeLeave(p);
39879   return rc;
39880 }
39881
39882 /*
39883 ** Return the flag byte at the beginning of the page that the cursor
39884 ** is currently pointing to.
39885 */
39886 SQLITE_PRIVATE int sqlite3BtreeFlags(BtCursor *pCur){
39887   /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call
39888   ** restoreCursorPosition() here.
39889   */
39890   MemPage *pPage;
39891   restoreCursorPosition(pCur);
39892   pPage = pCur->pPage;
39893   assert( cursorHoldsMutex(pCur) );
39894   assert( pPage->pBt==pCur->pBt );
39895   return pPage ? pPage->aData[pPage->hdrOffset] : 0;
39896 }
39897
39898
39899 /*
39900 ** Return the pager associated with a BTree.  This routine is used for
39901 ** testing and debugging only.
39902 */
39903 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
39904   return p->pBt->pPager;
39905 }
39906
39907 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
39908 /*
39909 ** Append a message to the error message string.
39910 */
39911 static void checkAppendMsg(
39912   IntegrityCk *pCheck,
39913   char *zMsg1,
39914   const char *zFormat,
39915   ...
39916 ){
39917   va_list ap;
39918   if( !pCheck->mxErr ) return;
39919   pCheck->mxErr--;
39920   pCheck->nErr++;
39921   va_start(ap, zFormat);
39922   if( pCheck->errMsg.nChar ){
39923     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
39924   }
39925   if( zMsg1 ){
39926     sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
39927   }
39928   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
39929   va_end(ap);
39930   if( pCheck->errMsg.mallocFailed ){
39931     pCheck->mallocFailed = 1;
39932   }
39933 }
39934 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
39935
39936 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
39937 /*
39938 ** Add 1 to the reference count for page iPage.  If this is the second
39939 ** reference to the page, add an error message to pCheck->zErrMsg.
39940 ** Return 1 if there are 2 ore more references to the page and 0 if
39941 ** if this is the first reference to the page.
39942 **
39943 ** Also check that the page number is in bounds.
39944 */
39945 static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
39946   if( iPage==0 ) return 1;
39947   if( iPage>pCheck->nPage || iPage<0 ){
39948     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
39949     return 1;
39950   }
39951   if( pCheck->anRef[iPage]==1 ){
39952     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
39953     return 1;
39954   }
39955   return  (pCheck->anRef[iPage]++)>1;
39956 }
39957
39958 #ifndef SQLITE_OMIT_AUTOVACUUM
39959 /*
39960 ** Check that the entry in the pointer-map for page iChild maps to 
39961 ** page iParent, pointer type ptrType. If not, append an error message
39962 ** to pCheck.
39963 */
39964 static void checkPtrmap(
39965   IntegrityCk *pCheck,   /* Integrity check context */
39966   Pgno iChild,           /* Child page number */
39967   u8 eType,              /* Expected pointer map type */
39968   Pgno iParent,          /* Expected pointer map parent page number */
39969   char *zContext         /* Context description (used for error msg) */
39970 ){
39971   int rc;
39972   u8 ePtrmapType;
39973   Pgno iPtrmapParent;
39974
39975   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
39976   if( rc!=SQLITE_OK ){
39977     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
39978     return;
39979   }
39980
39981   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
39982     checkAppendMsg(pCheck, zContext, 
39983       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
39984       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
39985   }
39986 }
39987 #endif
39988
39989 /*
39990 ** Check the integrity of the freelist or of an overflow page list.
39991 ** Verify that the number of pages on the list is N.
39992 */
39993 static void checkList(
39994   IntegrityCk *pCheck,  /* Integrity checking context */
39995   int isFreeList,       /* True for a freelist.  False for overflow page list */
39996   int iPage,            /* Page number for first page in the list */
39997   int N,                /* Expected number of pages in the list */
39998   char *zContext        /* Context for error messages */
39999 ){
40000   int i;
40001   int expected = N;
40002   int iFirst = iPage;
40003   while( N-- > 0 && pCheck->mxErr ){
40004     DbPage *pOvflPage;
40005     unsigned char *pOvflData;
40006     if( iPage<1 ){
40007       checkAppendMsg(pCheck, zContext,
40008          "%d of %d pages missing from overflow list starting at %d",
40009           N+1, expected, iFirst);
40010       break;
40011     }
40012     if( checkRef(pCheck, iPage, zContext) ) break;
40013     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
40014       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
40015       break;
40016     }
40017     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
40018     if( isFreeList ){
40019       int n = get4byte(&pOvflData[4]);
40020 #ifndef SQLITE_OMIT_AUTOVACUUM
40021       if( pCheck->pBt->autoVacuum ){
40022         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
40023       }
40024 #endif
40025       if( n>pCheck->pBt->usableSize/4-2 ){
40026         checkAppendMsg(pCheck, zContext,
40027            "freelist leaf count too big on page %d", iPage);
40028         N--;
40029       }else{
40030         for(i=0; i<n; i++){
40031           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
40032 #ifndef SQLITE_OMIT_AUTOVACUUM
40033           if( pCheck->pBt->autoVacuum ){
40034             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
40035           }
40036 #endif
40037           checkRef(pCheck, iFreePage, zContext);
40038         }
40039         N -= n;
40040       }
40041     }
40042 #ifndef SQLITE_OMIT_AUTOVACUUM
40043     else{
40044       /* If this database supports auto-vacuum and iPage is not the last
40045       ** page in this overflow list, check that the pointer-map entry for
40046       ** the following page matches iPage.
40047       */
40048       if( pCheck->pBt->autoVacuum && N>0 ){
40049         i = get4byte(pOvflData);
40050         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
40051       }
40052     }
40053 #endif
40054     iPage = get4byte(pOvflData);
40055     sqlite3PagerUnref(pOvflPage);
40056   }
40057 }
40058 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
40059
40060 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
40061 /*
40062 ** Do various sanity checks on a single page of a tree.  Return
40063 ** the tree depth.  Root pages return 0.  Parents of root pages
40064 ** return 1, and so forth.
40065 ** 
40066 ** These checks are done:
40067 **
40068 **      1.  Make sure that cells and freeblocks do not overlap
40069 **          but combine to completely cover the page.
40070 **  NO  2.  Make sure cell keys are in order.
40071 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
40072 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
40073 **      5.  Check the integrity of overflow pages.
40074 **      6.  Recursively call checkTreePage on all children.
40075 **      7.  Verify that the depth of all children is the same.
40076 **      8.  Make sure this page is at least 33% full or else it is
40077 **          the root of the tree.
40078 */
40079 static int checkTreePage(
40080   IntegrityCk *pCheck,  /* Context for the sanity check */
40081   int iPage,            /* Page number of the page to check */
40082   MemPage *pParent,     /* Parent page */
40083   char *zParentContext  /* Parent context */
40084 ){
40085   MemPage *pPage;
40086   int i, rc, depth, d2, pgno, cnt;
40087   int hdr, cellStart;
40088   int nCell;
40089   u8 *data;
40090   BtShared *pBt;
40091   int usableSize;
40092   char zContext[100];
40093   char *hit;
40094
40095   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
40096
40097   /* Check that the page exists
40098   */
40099   pBt = pCheck->pBt;
40100   usableSize = pBt->usableSize;
40101   if( iPage==0 ) return 0;
40102   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
40103   if( (rc = sqlite3BtreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
40104     checkAppendMsg(pCheck, zContext,
40105        "unable to get the page. error code=%d", rc);
40106     return 0;
40107   }
40108   if( (rc = sqlite3BtreeInitPage(pPage, pParent))!=0 ){
40109     checkAppendMsg(pCheck, zContext, 
40110                    "sqlite3BtreeInitPage() returns error code %d", rc);
40111     releasePage(pPage);
40112     return 0;
40113   }
40114
40115   /* Check out all the cells.
40116   */
40117   depth = 0;
40118   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
40119     u8 *pCell;
40120     int sz;
40121     CellInfo info;
40122
40123     /* Check payload overflow pages
40124     */
40125     sqlite3_snprintf(sizeof(zContext), zContext,
40126              "On tree page %d cell %d: ", iPage, i);
40127     pCell = findCell(pPage,i);
40128     sqlite3BtreeParseCellPtr(pPage, pCell, &info);
40129     sz = info.nData;
40130     if( !pPage->intKey ) sz += info.nKey;
40131     assert( sz==info.nPayload );
40132     if( sz>info.nLocal ){
40133       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
40134       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
40135 #ifndef SQLITE_OMIT_AUTOVACUUM
40136       if( pBt->autoVacuum ){
40137         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
40138       }
40139 #endif
40140       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
40141     }
40142
40143     /* Check sanity of left child page.
40144     */
40145     if( !pPage->leaf ){
40146       pgno = get4byte(pCell);
40147 #ifndef SQLITE_OMIT_AUTOVACUUM
40148       if( pBt->autoVacuum ){
40149         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
40150       }
40151 #endif
40152       d2 = checkTreePage(pCheck,pgno,pPage,zContext);
40153       if( i>0 && d2!=depth ){
40154         checkAppendMsg(pCheck, zContext, "Child page depth differs");
40155       }
40156       depth = d2;
40157     }
40158   }
40159   if( !pPage->leaf ){
40160     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
40161     sqlite3_snprintf(sizeof(zContext), zContext, 
40162                      "On page %d at right child: ", iPage);
40163 #ifndef SQLITE_OMIT_AUTOVACUUM
40164     if( pBt->autoVacuum ){
40165       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
40166     }
40167 #endif
40168     checkTreePage(pCheck, pgno, pPage, zContext);
40169   }
40170  
40171   /* Check for complete coverage of the page
40172   */
40173   data = pPage->aData;
40174   hdr = pPage->hdrOffset;
40175   hit = sqlite3PageMalloc( pBt->pageSize );
40176   if( hit==0 ){
40177     pCheck->mallocFailed = 1;
40178   }else{
40179     memset(hit, 0, usableSize );
40180     memset(hit, 1, get2byte(&data[hdr+5]));
40181     nCell = get2byte(&data[hdr+3]);
40182     cellStart = hdr + 12 - 4*pPage->leaf;
40183     for(i=0; i<nCell; i++){
40184       int pc = get2byte(&data[cellStart+i*2]);
40185       u16 size = 1024;
40186       int j;
40187       if( pc<=usableSize ){
40188         size = cellSizePtr(pPage, &data[pc]);
40189       }
40190       if( (pc+size-1)>=usableSize || pc<0 ){
40191         checkAppendMsg(pCheck, 0, 
40192             "Corruption detected in cell %d on page %d",i,iPage,0);
40193       }else{
40194         for(j=pc+size-1; j>=pc; j--) hit[j]++;
40195       }
40196     }
40197     for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000; 
40198            cnt++){
40199       int size = get2byte(&data[i+2]);
40200       int j;
40201       if( (i+size-1)>=usableSize || i<0 ){
40202         checkAppendMsg(pCheck, 0,  
40203             "Corruption detected in cell %d on page %d",i,iPage,0);
40204       }else{
40205         for(j=i+size-1; j>=i; j--) hit[j]++;
40206       }
40207       i = get2byte(&data[i]);
40208     }
40209     for(i=cnt=0; i<usableSize; i++){
40210       if( hit[i]==0 ){
40211         cnt++;
40212       }else if( hit[i]>1 ){
40213         checkAppendMsg(pCheck, 0,
40214           "Multiple uses for byte %d of page %d", i, iPage);
40215         break;
40216       }
40217     }
40218     if( cnt!=data[hdr+7] ){
40219       checkAppendMsg(pCheck, 0, 
40220           "Fragmented space is %d byte reported as %d on page %d",
40221           cnt, data[hdr+7], iPage);
40222     }
40223   }
40224   sqlite3PageFree(hit);
40225
40226   releasePage(pPage);
40227   return depth+1;
40228 }
40229 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
40230
40231 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
40232 /*
40233 ** This routine does a complete check of the given BTree file.  aRoot[] is
40234 ** an array of pages numbers were each page number is the root page of
40235 ** a table.  nRoot is the number of entries in aRoot.
40236 **
40237 ** Write the number of error seen in *pnErr.  Except for some memory
40238 ** allocation errors,  nn error message is held in memory obtained from
40239 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
40240 ** returned.
40241 */
40242 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
40243   Btree *p,     /* The btree to be checked */
40244   int *aRoot,   /* An array of root pages numbers for individual trees */
40245   int nRoot,    /* Number of entries in aRoot[] */
40246   int mxErr,    /* Stop reporting errors after this many */
40247   int *pnErr    /* Write number of errors seen to this variable */
40248 ){
40249   int i;
40250   int nRef;
40251   IntegrityCk sCheck;
40252   BtShared *pBt = p->pBt;
40253   char zErr[100];
40254
40255   sqlite3BtreeEnter(p);
40256   pBt->db = p->db;
40257   nRef = sqlite3PagerRefcount(pBt->pPager);
40258   if( lockBtreeWithRetry(p)!=SQLITE_OK ){
40259     *pnErr = 1;
40260     sqlite3BtreeLeave(p);
40261     return sqlite3DbStrDup(0, "cannot acquire a read lock on the database");
40262   }
40263   sCheck.pBt = pBt;
40264   sCheck.pPager = pBt->pPager;
40265   sCheck.nPage = pagerPagecount(sCheck.pPager);
40266   sCheck.mxErr = mxErr;
40267   sCheck.nErr = 0;
40268   sCheck.mallocFailed = 0;
40269   *pnErr = 0;
40270 #ifndef SQLITE_OMIT_AUTOVACUUM
40271   if( pBt->nTrunc!=0 ){
40272     sCheck.nPage = pBt->nTrunc;
40273   }
40274 #endif
40275   if( sCheck.nPage==0 ){
40276     unlockBtreeIfUnused(pBt);
40277     sqlite3BtreeLeave(p);
40278     return 0;
40279   }
40280   sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
40281   if( !sCheck.anRef ){
40282     unlockBtreeIfUnused(pBt);
40283     *pnErr = 1;
40284     sqlite3BtreeLeave(p);
40285     return 0;
40286   }
40287   for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
40288   i = PENDING_BYTE_PAGE(pBt);
40289   if( i<=sCheck.nPage ){
40290     sCheck.anRef[i] = 1;
40291   }
40292   sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
40293
40294   /* Check the integrity of the freelist
40295   */
40296   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
40297             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
40298
40299   /* Check all the tables.
40300   */
40301   for(i=0; i<nRoot && sCheck.mxErr; i++){
40302     if( aRoot[i]==0 ) continue;
40303 #ifndef SQLITE_OMIT_AUTOVACUUM
40304     if( pBt->autoVacuum && aRoot[i]>1 ){
40305       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
40306     }
40307 #endif
40308     checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ");
40309   }
40310
40311   /* Make sure every page in the file is referenced
40312   */
40313   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
40314 #ifdef SQLITE_OMIT_AUTOVACUUM
40315     if( sCheck.anRef[i]==0 ){
40316       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
40317     }
40318 #else
40319     /* If the database supports auto-vacuum, make sure no tables contain
40320     ** references to pointer-map pages.
40321     */
40322     if( sCheck.anRef[i]==0 && 
40323        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
40324       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
40325     }
40326     if( sCheck.anRef[i]!=0 && 
40327        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
40328       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
40329     }
40330 #endif
40331   }
40332
40333   /* Make sure this analysis did not leave any unref() pages
40334   */
40335   unlockBtreeIfUnused(pBt);
40336   if( nRef != sqlite3PagerRefcount(pBt->pPager) ){
40337     checkAppendMsg(&sCheck, 0, 
40338       "Outstanding page count goes from %d to %d during this analysis",
40339       nRef, sqlite3PagerRefcount(pBt->pPager)
40340     );
40341   }
40342
40343   /* Clean  up and report errors.
40344   */
40345   sqlite3BtreeLeave(p);
40346   sqlite3_free(sCheck.anRef);
40347   if( sCheck.mallocFailed ){
40348     sqlite3StrAccumReset(&sCheck.errMsg);
40349     *pnErr = sCheck.nErr+1;
40350     return 0;
40351   }
40352   *pnErr = sCheck.nErr;
40353   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
40354   return sqlite3StrAccumFinish(&sCheck.errMsg);
40355 }
40356 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
40357
40358 /*
40359 ** Return the full pathname of the underlying database file.
40360 **
40361 ** The pager filename is invariant as long as the pager is
40362 ** open so it is safe to access without the BtShared mutex.
40363 */
40364 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
40365   assert( p->pBt->pPager!=0 );
40366   return sqlite3PagerFilename(p->pBt->pPager);
40367 }
40368
40369 /*
40370 ** Return the pathname of the directory that contains the database file.
40371 **
40372 ** The pager directory name is invariant as long as the pager is
40373 ** open so it is safe to access without the BtShared mutex.
40374 */
40375 SQLITE_PRIVATE const char *sqlite3BtreeGetDirname(Btree *p){
40376   assert( p->pBt->pPager!=0 );
40377   return sqlite3PagerDirname(p->pBt->pPager);
40378 }
40379
40380 /*
40381 ** Return the pathname of the journal file for this database. The return
40382 ** value of this routine is the same regardless of whether the journal file
40383 ** has been created or not.
40384 **
40385 ** The pager journal filename is invariant as long as the pager is
40386 ** open so it is safe to access without the BtShared mutex.
40387 */
40388 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
40389   assert( p->pBt->pPager!=0 );
40390   return sqlite3PagerJournalname(p->pBt->pPager);
40391 }
40392
40393 #ifndef SQLITE_OMIT_VACUUM
40394 /*
40395 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
40396 ** must be active for both files.
40397 **
40398 ** The size of file pTo may be reduced by this operation.
40399 ** If anything goes wrong, the transaction on pTo is rolled back. 
40400 **
40401 ** If successful, CommitPhaseOne() may be called on pTo before returning. 
40402 ** The caller should finish committing the transaction on pTo by calling
40403 ** sqlite3BtreeCommit().
40404 */
40405 static int btreeCopyFile(Btree *pTo, Btree *pFrom){
40406   int rc = SQLITE_OK;
40407   Pgno i;
40408
40409   Pgno nFromPage;     /* Number of pages in pFrom */
40410   Pgno nToPage;       /* Number of pages in pTo */
40411   Pgno nNewPage;      /* Number of pages in pTo after the copy */
40412
40413   Pgno iSkip;         /* Pending byte page in pTo */
40414   int nToPageSize;    /* Page size of pTo in bytes */
40415   int nFromPageSize;  /* Page size of pFrom in bytes */
40416
40417   BtShared *pBtTo = pTo->pBt;
40418   BtShared *pBtFrom = pFrom->pBt;
40419   pBtTo->db = pTo->db;
40420   pBtFrom->db = pFrom->db;
40421
40422   nToPageSize = pBtTo->pageSize;
40423   nFromPageSize = pBtFrom->pageSize;
40424
40425   if( pTo->inTrans!=TRANS_WRITE || pFrom->inTrans!=TRANS_WRITE ){
40426     return SQLITE_ERROR;
40427   }
40428   if( pBtTo->pCursor ){
40429     return SQLITE_BUSY;
40430   }
40431
40432   nToPage = pagerPagecount(pBtTo->pPager);
40433   nFromPage = pagerPagecount(pBtFrom->pPager);
40434   iSkip = PENDING_BYTE_PAGE(pBtTo);
40435
40436   /* Variable nNewPage is the number of pages required to store the
40437   ** contents of pFrom using the current page-size of pTo.
40438   */
40439   nNewPage = ((i64)nFromPage * (i64)nFromPageSize + (i64)nToPageSize - 1) / 
40440       (i64)nToPageSize;
40441
40442   for(i=1; rc==SQLITE_OK && (i<=nToPage || i<=nNewPage); i++){
40443
40444     /* Journal the original page.
40445     **
40446     ** iSkip is the page number of the locking page (PENDING_BYTE_PAGE)
40447     ** in database *pTo (before the copy). This page is never written 
40448     ** into the journal file. Unless i==iSkip or the page was not
40449     ** present in pTo before the copy operation, journal page i from pTo.
40450     */
40451     if( i!=iSkip && i<=nToPage ){
40452       DbPage *pDbPage = 0;
40453       rc = sqlite3PagerGet(pBtTo->pPager, i, &pDbPage);
40454       if( rc==SQLITE_OK ){
40455         rc = sqlite3PagerWrite(pDbPage);
40456         if( rc==SQLITE_OK && i>nFromPage ){
40457           /* Yeah.  It seems wierd to call DontWrite() right after Write(). But
40458           ** that is because the names of those procedures do not exactly 
40459           ** represent what they do.  Write() really means "put this page in the
40460           ** rollback journal and mark it as dirty so that it will be written
40461           ** to the database file later."  DontWrite() undoes the second part of
40462           ** that and prevents the page from being written to the database. The
40463           ** page is still on the rollback journal, though.  And that is the 
40464           ** whole point of this block: to put pages on the rollback journal. 
40465           */
40466           rc = sqlite3PagerDontWrite(pDbPage);
40467         }
40468         sqlite3PagerUnref(pDbPage);
40469       }
40470     }
40471
40472     /* Overwrite the data in page i of the target database */
40473     if( rc==SQLITE_OK && i!=iSkip && i<=nNewPage ){
40474
40475       DbPage *pToPage = 0;
40476       sqlite3_int64 iOff;
40477
40478       rc = sqlite3PagerGet(pBtTo->pPager, i, &pToPage);
40479       if( rc==SQLITE_OK ){
40480         rc = sqlite3PagerWrite(pToPage);
40481       }
40482
40483       for(
40484         iOff=(i-1)*nToPageSize; 
40485         rc==SQLITE_OK && iOff<i*nToPageSize; 
40486         iOff += nFromPageSize
40487       ){
40488         DbPage *pFromPage = 0;
40489         Pgno iFrom = (iOff/nFromPageSize)+1;
40490
40491         if( iFrom==PENDING_BYTE_PAGE(pBtFrom) ){
40492           continue;
40493         }
40494
40495         rc = sqlite3PagerGet(pBtFrom->pPager, iFrom, &pFromPage);
40496         if( rc==SQLITE_OK ){
40497           char *zTo = sqlite3PagerGetData(pToPage);
40498           char *zFrom = sqlite3PagerGetData(pFromPage);
40499           int nCopy;
40500
40501           if( nFromPageSize>=nToPageSize ){
40502             zFrom += ((i-1)*nToPageSize - ((iFrom-1)*nFromPageSize));
40503             nCopy = nToPageSize;
40504           }else{
40505             zTo += (((iFrom-1)*nFromPageSize) - (i-1)*nToPageSize);
40506             nCopy = nFromPageSize;
40507           }
40508
40509           memcpy(zTo, zFrom, nCopy);
40510           sqlite3PagerUnref(pFromPage);
40511         }
40512       }
40513
40514       if( pToPage ){
40515         MemPage *p = (MemPage *)sqlite3PagerGetExtra(pToPage);
40516         p->isInit = 0;
40517         sqlite3PagerUnref(pToPage);
40518       }
40519     }
40520   }
40521
40522   /* If things have worked so far, the database file may need to be 
40523   ** truncated. The complex part is that it may need to be truncated to
40524   ** a size that is not an integer multiple of nToPageSize - the current
40525   ** page size used by the pager associated with B-Tree pTo.
40526   **
40527   ** For example, say the page-size of pTo is 2048 bytes and the original 
40528   ** number of pages is 5 (10 KB file). If pFrom has a page size of 1024 
40529   ** bytes and 9 pages, then the file needs to be truncated to 9KB.
40530   */
40531   if( rc==SQLITE_OK ){
40532     if( nFromPageSize!=nToPageSize ){
40533       sqlite3_file *pFile = sqlite3PagerFile(pBtTo->pPager);
40534       i64 iSize = (i64)nFromPageSize * (i64)nFromPage;
40535       i64 iNow = (i64)((nToPage>nNewPage)?nToPage:nNewPage) * (i64)nToPageSize; 
40536       i64 iPending = ((i64)PENDING_BYTE_PAGE(pBtTo)-1) *(i64)nToPageSize;
40537   
40538       assert( iSize<=iNow );
40539   
40540       /* Commit phase one syncs the journal file associated with pTo 
40541       ** containing the original data. It does not sync the database file
40542       ** itself. After doing this it is safe to use OsTruncate() and other
40543       ** file APIs on the database file directly.
40544       */
40545       pBtTo->db = pTo->db;
40546       rc = sqlite3PagerCommitPhaseOne(pBtTo->pPager, 0, 0, 1);
40547       if( iSize<iNow && rc==SQLITE_OK ){
40548         rc = sqlite3OsTruncate(pFile, iSize);
40549       }
40550   
40551       /* The loop that copied data from database pFrom to pTo did not
40552       ** populate the locking page of database pTo. If the page-size of
40553       ** pFrom is smaller than that of pTo, this means some data will
40554       ** not have been copied. 
40555       **
40556       ** This block copies the missing data from database pFrom to pTo 
40557       ** using file APIs. This is safe because at this point we know that
40558       ** all of the original data from pTo has been synced into the 
40559       ** journal file. At this point it would be safe to do anything at
40560       ** all to the database file except truncate it to zero bytes.
40561       */
40562       if( rc==SQLITE_OK && nFromPageSize<nToPageSize && iSize>iPending){
40563         i64 iOff;
40564         for(
40565           iOff=iPending; 
40566           rc==SQLITE_OK && iOff<(iPending+nToPageSize); 
40567           iOff += nFromPageSize
40568         ){
40569           DbPage *pFromPage = 0;
40570           Pgno iFrom = (iOff/nFromPageSize)+1;
40571   
40572           if( iFrom==PENDING_BYTE_PAGE(pBtFrom) || iFrom>nFromPage ){
40573             continue;
40574           }
40575   
40576           rc = sqlite3PagerGet(pBtFrom->pPager, iFrom, &pFromPage);
40577           if( rc==SQLITE_OK ){
40578             char *zFrom = sqlite3PagerGetData(pFromPage);
40579             rc = sqlite3OsWrite(pFile, zFrom, nFromPageSize, iOff);
40580             sqlite3PagerUnref(pFromPage);
40581           }
40582         }
40583       }
40584   
40585       /* Sync the database file */
40586       if( rc==SQLITE_OK ){
40587         rc = sqlite3PagerSync(pBtTo->pPager);
40588       }
40589     }else{
40590       rc = sqlite3PagerTruncate(pBtTo->pPager, nNewPage);
40591     }
40592     if( rc==SQLITE_OK ){
40593       pBtTo->pageSizeFixed = 0;
40594     }
40595   }
40596
40597   if( rc ){
40598     sqlite3BtreeRollback(pTo);
40599   }
40600
40601   return rc;  
40602 }
40603 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
40604   int rc;
40605   sqlite3BtreeEnter(pTo);
40606   sqlite3BtreeEnter(pFrom);
40607   rc = btreeCopyFile(pTo, pFrom);
40608   sqlite3BtreeLeave(pFrom);
40609   sqlite3BtreeLeave(pTo);
40610   return rc;
40611 }
40612
40613 #endif /* SQLITE_OMIT_VACUUM */
40614
40615 /*
40616 ** Return non-zero if a transaction is active.
40617 */
40618 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
40619   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
40620   return (p && (p->inTrans==TRANS_WRITE));
40621 }
40622
40623 /*
40624 ** Return non-zero if a statement transaction is active.
40625 */
40626 SQLITE_PRIVATE int sqlite3BtreeIsInStmt(Btree *p){
40627   assert( sqlite3BtreeHoldsMutex(p) );
40628   return (p->pBt && p->pBt->inStmt);
40629 }
40630
40631 /*
40632 ** Return non-zero if a read (or write) transaction is active.
40633 */
40634 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
40635   assert( sqlite3_mutex_held(p->db->mutex) );
40636   return (p && (p->inTrans!=TRANS_NONE));
40637 }
40638
40639 /*
40640 ** This function returns a pointer to a blob of memory associated with
40641 ** a single shared-btree. The memory is used by client code for its own
40642 ** purposes (for example, to store a high-level schema associated with 
40643 ** the shared-btree). The btree layer manages reference counting issues.
40644 **
40645 ** The first time this is called on a shared-btree, nBytes bytes of memory
40646 ** are allocated, zeroed, and returned to the caller. For each subsequent 
40647 ** call the nBytes parameter is ignored and a pointer to the same blob
40648 ** of memory returned. 
40649 **
40650 ** If the nBytes parameter is 0 and the blob of memory has not yet been
40651 ** allocated, a null pointer is returned. If the blob has already been
40652 ** allocated, it is returned as normal.
40653 **
40654 ** Just before the shared-btree is closed, the function passed as the 
40655 ** xFree argument when the memory allocation was made is invoked on the 
40656 ** blob of allocated memory. This function should not call sqlite3_free()
40657 ** on the memory, the btree layer does that.
40658 */
40659 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
40660   BtShared *pBt = p->pBt;
40661   sqlite3BtreeEnter(p);
40662   if( !pBt->pSchema && nBytes ){
40663     pBt->pSchema = sqlite3MallocZero(nBytes);
40664     pBt->xFreeSchema = xFree;
40665   }
40666   sqlite3BtreeLeave(p);
40667   return pBt->pSchema;
40668 }
40669
40670 /*
40671 ** Return true if another user of the same shared btree as the argument
40672 ** handle holds an exclusive lock on the sqlite_master table.
40673 */
40674 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
40675   int rc;
40676   assert( sqlite3_mutex_held(p->db->mutex) );
40677   sqlite3BtreeEnter(p);
40678   rc = (queryTableLock(p, MASTER_ROOT, READ_LOCK)!=SQLITE_OK);
40679   sqlite3BtreeLeave(p);
40680   return rc;
40681 }
40682
40683
40684 #ifndef SQLITE_OMIT_SHARED_CACHE
40685 /*
40686 ** Obtain a lock on the table whose root page is iTab.  The
40687 ** lock is a write lock if isWritelock is true or a read lock
40688 ** if it is false.
40689 */
40690 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
40691   int rc = SQLITE_OK;
40692   if( p->sharable ){
40693     u8 lockType = READ_LOCK + isWriteLock;
40694     assert( READ_LOCK+1==WRITE_LOCK );
40695     assert( isWriteLock==0 || isWriteLock==1 );
40696     sqlite3BtreeEnter(p);
40697     rc = queryTableLock(p, iTab, lockType);
40698     if( rc==SQLITE_OK ){
40699       rc = lockTable(p, iTab, lockType);
40700     }
40701     sqlite3BtreeLeave(p);
40702   }
40703   return rc;
40704 }
40705 #endif
40706
40707 #ifndef SQLITE_OMIT_INCRBLOB
40708 /*
40709 ** Argument pCsr must be a cursor opened for writing on an 
40710 ** INTKEY table currently pointing at a valid table entry. 
40711 ** This function modifies the data stored as part of that entry.
40712 ** Only the data content may only be modified, it is not possible
40713 ** to change the length of the data stored.
40714 */
40715 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
40716   assert( cursorHoldsMutex(pCsr) );
40717   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
40718   assert(pCsr->isIncrblobHandle);
40719
40720   restoreCursorPosition(pCsr);
40721   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
40722   if( pCsr->eState!=CURSOR_VALID ){
40723     return SQLITE_ABORT;
40724   }
40725
40726   /* Check some preconditions: 
40727   **   (a) the cursor is open for writing,
40728   **   (b) there is no read-lock on the table being modified and
40729   **   (c) the cursor points at a valid row of an intKey table.
40730   */
40731   if( !pCsr->wrFlag ){
40732     return SQLITE_READONLY;
40733   }
40734   assert( !pCsr->pBt->readOnly 
40735           && pCsr->pBt->inTransaction==TRANS_WRITE );
40736   if( checkReadLocks(pCsr->pBtree, pCsr->pgnoRoot, pCsr, 0) ){
40737     return SQLITE_LOCKED; /* The table pCur points to has a read lock */
40738   }
40739   if( pCsr->eState==CURSOR_INVALID || !pCsr->pPage->intKey ){
40740     return SQLITE_ERROR;
40741   }
40742
40743   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 0, 1);
40744 }
40745
40746 /* 
40747 ** Set a flag on this cursor to cache the locations of pages from the 
40748 ** overflow list for the current row. This is used by cursors opened
40749 ** for incremental blob IO only.
40750 **
40751 ** This function sets a flag only. The actual page location cache
40752 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
40753 ** accessPayload() (the worker function for sqlite3BtreeData() and
40754 ** sqlite3BtreePutData()).
40755 */
40756 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
40757   assert( cursorHoldsMutex(pCur) );
40758   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
40759   assert(!pCur->isIncrblobHandle);
40760   assert(!pCur->aOverflow);
40761   pCur->isIncrblobHandle = 1;
40762 }
40763 #endif
40764
40765 /************** End of btree.c ***********************************************/
40766 /************** Begin file vdbefifo.c ****************************************/
40767 /*
40768 ** 2005 June 16
40769 **
40770 ** The author disclaims copyright to this source code.  In place of
40771 ** a legal notice, here is a blessing:
40772 **
40773 **    May you do good and not evil.
40774 **    May you find forgiveness for yourself and forgive others.
40775 **    May you share freely, never taking more than you give.
40776 **
40777 *************************************************************************
40778 ** This file implements a FIFO queue of rowids used for processing
40779 ** UPDATE and DELETE statements.
40780 **
40781 ** $Id: vdbefifo.c,v 1.8 2008/07/28 19:34:54 drh Exp $
40782 */
40783
40784 /*
40785 ** Constants FIFOSIZE_FIRST and FIFOSIZE_MAX are the initial
40786 ** number of entries in a fifo page and the maximum number of
40787 ** entries in a fifo page.
40788 */
40789 #define FIFOSIZE_FIRST (((128-sizeof(FifoPage))/8)+1)
40790 #ifdef SQLITE_MALLOC_SOFT_LIMIT
40791 # define FIFOSIZE_MAX   (((SQLITE_MALLOC_SOFT_LIMIT-sizeof(FifoPage))/8)+1)
40792 #else
40793 # define FIFOSIZE_MAX   (((262144-sizeof(FifoPage))/8)+1)
40794 #endif
40795
40796 /*
40797 ** Allocate a new FifoPage and return a pointer to it.  Return NULL if
40798 ** we run out of memory.  Leave space on the page for nEntry entries.
40799 */
40800 static FifoPage *allocateFifoPage(sqlite3 *db, int nEntry){
40801   FifoPage *pPage;
40802   if( nEntry>FIFOSIZE_MAX ){
40803     nEntry = FIFOSIZE_MAX;
40804   }
40805   pPage = sqlite3DbMallocRaw(db, sizeof(FifoPage) + sizeof(i64)*(nEntry-1) );
40806   if( pPage ){
40807     pPage->nSlot = nEntry;
40808     pPage->iWrite = 0;
40809     pPage->iRead = 0;
40810     pPage->pNext = 0;
40811   }
40812   return pPage;
40813 }
40814
40815 /*
40816 ** Initialize a Fifo structure.
40817 */
40818 SQLITE_PRIVATE void sqlite3VdbeFifoInit(Fifo *pFifo, sqlite3 *db){
40819   memset(pFifo, 0, sizeof(*pFifo));
40820   pFifo->db = db;
40821 }
40822
40823 /*
40824 ** Push a single 64-bit integer value into the Fifo.  Return SQLITE_OK
40825 ** normally.   SQLITE_NOMEM is returned if we are unable to allocate
40826 ** memory.
40827 */
40828 SQLITE_PRIVATE int sqlite3VdbeFifoPush(Fifo *pFifo, i64 val){
40829   FifoPage *pPage;
40830   pPage = pFifo->pLast;
40831   if( pPage==0 ){
40832     pPage = pFifo->pLast = pFifo->pFirst =
40833          allocateFifoPage(pFifo->db, FIFOSIZE_FIRST);
40834     if( pPage==0 ){
40835       return SQLITE_NOMEM;
40836     }
40837   }else if( pPage->iWrite>=pPage->nSlot ){
40838     pPage->pNext = allocateFifoPage(pFifo->db, pFifo->nEntry);
40839     if( pPage->pNext==0 ){
40840       return SQLITE_NOMEM;
40841     }
40842     pPage = pFifo->pLast = pPage->pNext;
40843   }
40844   pPage->aSlot[pPage->iWrite++] = val;
40845   pFifo->nEntry++;
40846   return SQLITE_OK;
40847 }
40848
40849 /*
40850 ** Extract a single 64-bit integer value from the Fifo.  The integer
40851 ** extracted is the one least recently inserted.  If the Fifo is empty
40852 ** return SQLITE_DONE.
40853 */
40854 SQLITE_PRIVATE int sqlite3VdbeFifoPop(Fifo *pFifo, i64 *pVal){
40855   FifoPage *pPage;
40856   if( pFifo->nEntry==0 ){
40857     return SQLITE_DONE;
40858   }
40859   assert( pFifo->nEntry>0 );
40860   pPage = pFifo->pFirst;
40861   assert( pPage!=0 );
40862   assert( pPage->iWrite>pPage->iRead );
40863   assert( pPage->iWrite<=pPage->nSlot );
40864   assert( pPage->iRead<pPage->nSlot );
40865   assert( pPage->iRead>=0 );
40866   *pVal = pPage->aSlot[pPage->iRead++];
40867   pFifo->nEntry--;
40868   if( pPage->iRead>=pPage->iWrite ){
40869     pFifo->pFirst = pPage->pNext;
40870     sqlite3DbFree(pFifo->db, pPage);
40871     if( pFifo->nEntry==0 ){
40872       assert( pFifo->pLast==pPage );
40873       pFifo->pLast = 0;
40874     }else{
40875       assert( pFifo->pFirst!=0 );
40876     }
40877   }else{
40878     assert( pFifo->nEntry>0 );
40879   }
40880   return SQLITE_OK;
40881 }
40882
40883 /*
40884 ** Delete all information from a Fifo object.   Free all memory held
40885 ** by the Fifo.
40886 */
40887 SQLITE_PRIVATE void sqlite3VdbeFifoClear(Fifo *pFifo){
40888   FifoPage *pPage, *pNextPage;
40889   for(pPage=pFifo->pFirst; pPage; pPage=pNextPage){
40890     pNextPage = pPage->pNext;
40891     sqlite3DbFree(pFifo->db, pPage);
40892   }
40893   sqlite3VdbeFifoInit(pFifo, pFifo->db);
40894 }
40895
40896 /************** End of vdbefifo.c ********************************************/
40897 /************** Begin file vdbemem.c *****************************************/
40898 /*
40899 ** 2004 May 26
40900 **
40901 ** The author disclaims copyright to this source code.  In place of
40902 ** a legal notice, here is a blessing:
40903 **
40904 **    May you do good and not evil.
40905 **    May you find forgiveness for yourself and forgive others.
40906 **    May you share freely, never taking more than you give.
40907 **
40908 *************************************************************************
40909 **
40910 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
40911 ** stores a single value in the VDBE.  Mem is an opaque structure visible
40912 ** only within the VDBE.  Interface routines refer to a Mem using the
40913 ** name sqlite_value
40914 **
40915 ** $Id: vdbemem.c,v 1.123 2008/09/16 12:06:08 danielk1977 Exp $
40916 */
40917
40918 /*
40919 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
40920 ** P if required.
40921 */
40922 #define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
40923
40924 /*
40925 ** If pMem is an object with a valid string representation, this routine
40926 ** ensures the internal encoding for the string representation is
40927 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
40928 **
40929 ** If pMem is not a string object, or the encoding of the string
40930 ** representation is already stored using the requested encoding, then this
40931 ** routine is a no-op.
40932 **
40933 ** SQLITE_OK is returned if the conversion is successful (or not required).
40934 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
40935 ** between formats.
40936 */
40937 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
40938   int rc;
40939   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
40940     return SQLITE_OK;
40941   }
40942   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
40943 #ifdef SQLITE_OMIT_UTF16
40944   return SQLITE_ERROR;
40945 #else
40946
40947   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
40948   ** then the encoding of the value may not have changed.
40949   */
40950   rc = sqlite3VdbeMemTranslate(pMem, desiredEnc);
40951   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
40952   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
40953   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
40954   return rc;
40955 #endif
40956 }
40957
40958 /*
40959 ** Make sure pMem->z points to a writable allocation of at least 
40960 ** n bytes.
40961 **
40962 ** If the memory cell currently contains string or blob data
40963 ** and the third argument passed to this function is true, the 
40964 ** current content of the cell is preserved. Otherwise, it may
40965 ** be discarded.  
40966 **
40967 ** This function sets the MEM_Dyn flag and clears any xDel callback.
40968 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is 
40969 ** not set, Mem.n is zeroed.
40970 */
40971 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
40972   assert( 1 >=
40973     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
40974     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) + 
40975     ((pMem->flags&MEM_Ephem) ? 1 : 0) + 
40976     ((pMem->flags&MEM_Static) ? 1 : 0)
40977   );
40978
40979   if( n<32 ) n = 32;
40980   if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
40981     if( preserve && pMem->z==pMem->zMalloc ){
40982       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
40983       if( !pMem->z ){
40984         pMem->flags = MEM_Null;
40985       }
40986       preserve = 0;
40987     }else{
40988       sqlite3DbFree(pMem->db, pMem->zMalloc);
40989       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
40990     }
40991   }
40992
40993   if( preserve && pMem->z && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
40994     memcpy(pMem->zMalloc, pMem->z, pMem->n);
40995   }
40996   if( pMem->flags&MEM_Dyn && pMem->xDel ){
40997     pMem->xDel((void *)(pMem->z));
40998   }
40999
41000   pMem->z = pMem->zMalloc;
41001   pMem->flags &= ~(MEM_Ephem|MEM_Static);
41002   pMem->xDel = 0;
41003   return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
41004 }
41005
41006 /*
41007 ** Make the given Mem object MEM_Dyn.  In other words, make it so
41008 ** that any TEXT or BLOB content is stored in memory obtained from
41009 ** malloc().  In this way, we know that the memory is safe to be
41010 ** overwritten or altered.
41011 **
41012 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
41013 */
41014 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
41015   int f;
41016   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41017   expandBlob(pMem);
41018   f = pMem->flags;
41019   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
41020     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
41021       return SQLITE_NOMEM;
41022     }
41023     pMem->z[pMem->n] = 0;
41024     pMem->z[pMem->n+1] = 0;
41025     pMem->flags |= MEM_Term;
41026   }
41027
41028   return SQLITE_OK;
41029 }
41030
41031 /*
41032 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
41033 ** blob stored in dynamically allocated space.
41034 */
41035 #ifndef SQLITE_OMIT_INCRBLOB
41036 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
41037   if( pMem->flags & MEM_Zero ){
41038     int nByte;
41039     assert( pMem->flags&MEM_Blob );
41040     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41041
41042     /* Set nByte to the number of bytes required to store the expanded blob. */
41043     nByte = pMem->n + pMem->u.i;
41044     if( nByte<=0 ){
41045       nByte = 1;
41046     }
41047     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
41048       return SQLITE_NOMEM;
41049     }
41050
41051     memset(&pMem->z[pMem->n], 0, pMem->u.i);
41052     pMem->n += pMem->u.i;
41053     pMem->flags &= ~(MEM_Zero|MEM_Term);
41054   }
41055   return SQLITE_OK;
41056 }
41057 #endif
41058
41059
41060 /*
41061 ** Make sure the given Mem is \u0000 terminated.
41062 */
41063 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
41064   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41065   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
41066     return SQLITE_OK;   /* Nothing to do */
41067   }
41068   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
41069     return SQLITE_NOMEM;
41070   }
41071   pMem->z[pMem->n] = 0;
41072   pMem->z[pMem->n+1] = 0;
41073   pMem->flags |= MEM_Term;
41074   return SQLITE_OK;
41075 }
41076
41077 /*
41078 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
41079 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
41080 ** is a no-op.
41081 **
41082 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
41083 **
41084 ** A MEM_Null value will never be passed to this function. This function is
41085 ** used for converting values to text for returning to the user (i.e. via
41086 ** sqlite3_value_text()), or for ensuring that values to be used as btree
41087 ** keys are strings. In the former case a NULL pointer is returned the
41088 ** user and the later is an internal programming error.
41089 */
41090 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
41091   int rc = SQLITE_OK;
41092   int fg = pMem->flags;
41093   const int nByte = 32;
41094
41095   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41096   assert( !(fg&MEM_Zero) );
41097   assert( !(fg&(MEM_Str|MEM_Blob)) );
41098   assert( fg&(MEM_Int|MEM_Real) );
41099
41100   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
41101     return SQLITE_NOMEM;
41102   }
41103
41104   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
41105   ** string representation of the value. Then, if the required encoding
41106   ** is UTF-16le or UTF-16be do a translation.
41107   ** 
41108   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
41109   */
41110   if( fg & MEM_Int ){
41111     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
41112   }else{
41113     assert( fg & MEM_Real );
41114     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
41115   }
41116   pMem->n = strlen(pMem->z);
41117   pMem->enc = SQLITE_UTF8;
41118   pMem->flags |= MEM_Str|MEM_Term;
41119   sqlite3VdbeChangeEncoding(pMem, enc);
41120   return rc;
41121 }
41122
41123 /*
41124 ** Memory cell pMem contains the context of an aggregate function.
41125 ** This routine calls the finalize method for that function.  The
41126 ** result of the aggregate is stored back into pMem.
41127 **
41128 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
41129 ** otherwise.
41130 */
41131 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
41132   int rc = SQLITE_OK;
41133   if( pFunc && pFunc->xFinalize ){
41134     sqlite3_context ctx;
41135     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
41136     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41137     memset(&ctx, 0, sizeof(ctx));
41138     ctx.s.flags = MEM_Null;
41139     ctx.s.db = pMem->db;
41140     ctx.pMem = pMem;
41141     ctx.pFunc = pFunc;
41142     pFunc->xFinalize(&ctx);
41143     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
41144     sqlite3DbFree(pMem->db, pMem->zMalloc);
41145     *pMem = ctx.s;
41146     rc = (ctx.isError?SQLITE_ERROR:SQLITE_OK);
41147   }
41148   return rc;
41149 }
41150
41151 /*
41152 ** If the memory cell contains a string value that must be freed by
41153 ** invoking an external callback, free it now. Calling this function
41154 ** does not free any Mem.zMalloc buffer.
41155 */
41156 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
41157   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
41158   if( p->flags&MEM_Agg ){
41159     sqlite3VdbeMemFinalize(p, p->u.pDef);
41160     assert( (p->flags & MEM_Agg)==0 );
41161     sqlite3VdbeMemRelease(p);
41162   }else if( p->flags&MEM_Dyn && p->xDel ){
41163     p->xDel((void *)p->z);
41164     p->xDel = 0;
41165   }
41166 }
41167
41168 /*
41169 ** Release any memory held by the Mem. This may leave the Mem in an
41170 ** inconsistent state, for example with (Mem.z==0) and
41171 ** (Mem.type==SQLITE_TEXT).
41172 */
41173 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
41174   sqlite3VdbeMemReleaseExternal(p);
41175   sqlite3DbFree(p->db, p->zMalloc);
41176   p->z = 0;
41177   p->zMalloc = 0;
41178   p->xDel = 0;
41179 }
41180
41181 /*
41182 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
41183 ** If the double is too large, return 0x8000000000000000.
41184 **
41185 ** Most systems appear to do this simply by assigning
41186 ** variables and without the extra range tests.  But
41187 ** there are reports that windows throws an expection
41188 ** if the floating point value is out of range. (See ticket #2880.)
41189 ** Because we do not completely understand the problem, we will
41190 ** take the conservative approach and always do range tests
41191 ** before attempting the conversion.
41192 */
41193 static i64 doubleToInt64(double r){
41194   /*
41195   ** Many compilers we encounter do not define constants for the
41196   ** minimum and maximum 64-bit integers, or they define them
41197   ** inconsistently.  And many do not understand the "LL" notation.
41198   ** So we define our own static constants here using nothing
41199   ** larger than a 32-bit integer constant.
41200   */
41201   static const i64 maxInt = LARGEST_INT64;
41202   static const i64 minInt = SMALLEST_INT64;
41203
41204   if( r<(double)minInt ){
41205     return minInt;
41206   }else if( r>(double)maxInt ){
41207     return minInt;
41208   }else{
41209     return (i64)r;
41210   }
41211 }
41212
41213 /*
41214 ** Return some kind of integer value which is the best we can do
41215 ** at representing the value that *pMem describes as an integer.
41216 ** If pMem is an integer, then the value is exact.  If pMem is
41217 ** a floating-point then the value returned is the integer part.
41218 ** If pMem is a string or blob, then we make an attempt to convert
41219 ** it into a integer and return that.  If pMem is NULL, return 0.
41220 **
41221 ** If pMem is a string, its encoding might be changed.
41222 */
41223 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
41224   int flags;
41225   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41226   flags = pMem->flags;
41227   if( flags & MEM_Int ){
41228     return pMem->u.i;
41229   }else if( flags & MEM_Real ){
41230     return doubleToInt64(pMem->r);
41231   }else if( flags & (MEM_Str|MEM_Blob) ){
41232     i64 value;
41233     pMem->flags |= MEM_Str;
41234     if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
41235        || sqlite3VdbeMemNulTerminate(pMem) ){
41236       return 0;
41237     }
41238     assert( pMem->z );
41239     sqlite3Atoi64(pMem->z, &value);
41240     return value;
41241   }else{
41242     return 0;
41243   }
41244 }
41245
41246 /*
41247 ** Return the best representation of pMem that we can get into a
41248 ** double.  If pMem is already a double or an integer, return its
41249 ** value.  If it is a string or blob, try to convert it to a double.
41250 ** If it is a NULL, return 0.0.
41251 */
41252 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
41253   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41254   if( pMem->flags & MEM_Real ){
41255     return pMem->r;
41256   }else if( pMem->flags & MEM_Int ){
41257     return (double)pMem->u.i;
41258   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
41259     double val = 0.0;
41260     pMem->flags |= MEM_Str;
41261     if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
41262        || sqlite3VdbeMemNulTerminate(pMem) ){
41263       return 0.0;
41264     }
41265     assert( pMem->z );
41266     sqlite3AtoF(pMem->z, &val);
41267     return val;
41268   }else{
41269     return 0.0;
41270   }
41271 }
41272
41273 /*
41274 ** The MEM structure is already a MEM_Real.  Try to also make it a
41275 ** MEM_Int if we can.
41276 */
41277 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
41278   assert( pMem->flags & MEM_Real );
41279   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41280
41281   pMem->u.i = doubleToInt64(pMem->r);
41282   if( pMem->r==(double)pMem->u.i ){
41283     pMem->flags |= MEM_Int;
41284   }
41285 }
41286
41287 static void setTypeFlag(Mem *pMem, int f){
41288   MemSetTypeFlag(pMem, f);
41289 }
41290
41291 /*
41292 ** Convert pMem to type integer.  Invalidate any prior representations.
41293 */
41294 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
41295   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41296   pMem->u.i = sqlite3VdbeIntValue(pMem);
41297   setTypeFlag(pMem, MEM_Int);
41298   return SQLITE_OK;
41299 }
41300
41301 /*
41302 ** Convert pMem so that it is of type MEM_Real.
41303 ** Invalidate any prior representations.
41304 */
41305 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
41306   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41307   pMem->r = sqlite3VdbeRealValue(pMem);
41308   setTypeFlag(pMem, MEM_Real);
41309   return SQLITE_OK;
41310 }
41311
41312 /*
41313 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
41314 ** Invalidate any prior representations.
41315 */
41316 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
41317   double r1, r2;
41318   i64 i;
41319   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 );
41320   assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
41321   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41322   r1 = sqlite3VdbeRealValue(pMem);
41323   i = doubleToInt64(r1);
41324   r2 = (double)i;
41325   if( r1==r2 ){
41326     sqlite3VdbeMemIntegerify(pMem);
41327   }else{
41328     pMem->r = r1;
41329     setTypeFlag(pMem, MEM_Real);
41330   }
41331   return SQLITE_OK;
41332 }
41333
41334 /*
41335 ** Delete any previous value and set the value stored in *pMem to NULL.
41336 */
41337 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
41338   setTypeFlag(pMem, MEM_Null);
41339   pMem->type = SQLITE_NULL;
41340 }
41341
41342 /*
41343 ** Delete any previous value and set the value to be a BLOB of length
41344 ** n containing all zeros.
41345 */
41346 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
41347   sqlite3VdbeMemRelease(pMem);
41348   setTypeFlag(pMem, MEM_Blob);
41349   pMem->flags = MEM_Blob|MEM_Zero;
41350   pMem->type = SQLITE_BLOB;
41351   pMem->n = 0;
41352   if( n<0 ) n = 0;
41353   pMem->u.i = n;
41354   pMem->enc = SQLITE_UTF8;
41355 }
41356
41357 /*
41358 ** Delete any previous value and set the value stored in *pMem to val,
41359 ** manifest type INTEGER.
41360 */
41361 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
41362   sqlite3VdbeMemRelease(pMem);
41363   pMem->u.i = val;
41364   pMem->flags = MEM_Int;
41365   pMem->type = SQLITE_INTEGER;
41366 }
41367
41368 /*
41369 ** Delete any previous value and set the value stored in *pMem to val,
41370 ** manifest type REAL.
41371 */
41372 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
41373   if( sqlite3IsNaN(val) ){
41374     sqlite3VdbeMemSetNull(pMem);
41375   }else{
41376     sqlite3VdbeMemRelease(pMem);
41377     pMem->r = val;
41378     pMem->flags = MEM_Real;
41379     pMem->type = SQLITE_FLOAT;
41380   }
41381 }
41382
41383 /*
41384 ** Return true if the Mem object contains a TEXT or BLOB that is
41385 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
41386 */
41387 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
41388   assert( p->db!=0 );
41389   if( p->flags & (MEM_Str|MEM_Blob) ){
41390     int n = p->n;
41391     if( p->flags & MEM_Zero ){
41392       n += p->u.i;
41393     }
41394     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
41395   }
41396   return 0; 
41397 }
41398
41399 /*
41400 ** Size of struct Mem not including the Mem.zMalloc member.
41401 */
41402 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
41403
41404 /*
41405 ** Make an shallow copy of pFrom into pTo.  Prior contents of
41406 ** pTo are freed.  The pFrom->z field is not duplicated.  If
41407 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
41408 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
41409 */
41410 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
41411   sqlite3VdbeMemReleaseExternal(pTo);
41412   memcpy(pTo, pFrom, MEMCELLSIZE);
41413   pTo->xDel = 0;
41414   if( (pFrom->flags&MEM_Dyn)!=0 || pFrom->z==pFrom->zMalloc ){
41415     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
41416     assert( srcType==MEM_Ephem || srcType==MEM_Static );
41417     pTo->flags |= srcType;
41418   }
41419 }
41420
41421 /*
41422 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
41423 ** freed before the copy is made.
41424 */
41425 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
41426   int rc = SQLITE_OK;
41427
41428   sqlite3VdbeMemReleaseExternal(pTo);
41429   memcpy(pTo, pFrom, MEMCELLSIZE);
41430   pTo->flags &= ~MEM_Dyn;
41431
41432   if( pTo->flags&(MEM_Str|MEM_Blob) ){
41433     if( 0==(pFrom->flags&MEM_Static) ){
41434       pTo->flags |= MEM_Ephem;
41435       rc = sqlite3VdbeMemMakeWriteable(pTo);
41436     }
41437   }
41438
41439   return rc;
41440 }
41441
41442 /*
41443 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
41444 ** freed. If pFrom contains ephemeral data, a copy is made.
41445 **
41446 ** pFrom contains an SQL NULL when this routine returns.
41447 */
41448 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
41449   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
41450   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
41451   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
41452
41453   sqlite3VdbeMemRelease(pTo);
41454   memcpy(pTo, pFrom, sizeof(Mem));
41455   pFrom->flags = MEM_Null;
41456   pFrom->xDel = 0;
41457   pFrom->zMalloc = 0;
41458 }
41459
41460 /*
41461 ** Change the value of a Mem to be a string or a BLOB.
41462 **
41463 ** The memory management strategy depends on the value of the xDel
41464 ** parameter. If the value passed is SQLITE_TRANSIENT, then the 
41465 ** string is copied into a (possibly existing) buffer managed by the 
41466 ** Mem structure. Otherwise, any existing buffer is freed and the
41467 ** pointer copied.
41468 */
41469 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
41470   Mem *pMem,          /* Memory cell to set to string value */
41471   const char *z,      /* String pointer */
41472   int n,              /* Bytes in string, or negative */
41473   u8 enc,             /* Encoding of z.  0 for BLOBs */
41474   void (*xDel)(void*) /* Destructor function */
41475 ){
41476   int nByte = n;      /* New value for pMem->n */
41477   int iLimit;         /* Maximum allowed string or blob size */
41478   int flags = 0;      /* New value for pMem->flags */
41479
41480   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41481
41482   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
41483   if( !z ){
41484     sqlite3VdbeMemSetNull(pMem);
41485     return SQLITE_OK;
41486   }
41487
41488   if( pMem->db ){
41489     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
41490   }else{
41491     iLimit = SQLITE_MAX_LENGTH;
41492   }
41493   flags = (enc==0?MEM_Blob:MEM_Str);
41494   if( nByte<0 ){
41495     assert( enc!=0 );
41496     if( enc==SQLITE_UTF8 ){
41497       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
41498     }else{
41499       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
41500     }
41501     flags |= MEM_Term;
41502   }
41503   if( nByte>iLimit ){
41504     return SQLITE_TOOBIG;
41505   }
41506
41507   /* The following block sets the new values of Mem.z and Mem.xDel. It
41508   ** also sets a flag in local variable "flags" to indicate the memory
41509   ** management (one of MEM_Dyn or MEM_Static).
41510   */
41511   if( xDel==SQLITE_TRANSIENT ){
41512     int nAlloc = nByte;
41513     if( flags&MEM_Term ){
41514       nAlloc += (enc==SQLITE_UTF8?1:2);
41515     }
41516     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
41517       return SQLITE_NOMEM;
41518     }
41519     memcpy(pMem->z, z, nAlloc);
41520   }else if( xDel==SQLITE_DYNAMIC ){
41521     sqlite3VdbeMemRelease(pMem);
41522     pMem->zMalloc = pMem->z = (char *)z;
41523     pMem->xDel = 0;
41524   }else{
41525     sqlite3VdbeMemRelease(pMem);
41526     pMem->z = (char *)z;
41527     pMem->xDel = xDel;
41528     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
41529   }
41530
41531   pMem->n = nByte;
41532   pMem->flags = flags;
41533   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
41534   pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
41535
41536 #ifndef SQLITE_OMIT_UTF16
41537   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
41538     return SQLITE_NOMEM;
41539   }
41540 #endif
41541
41542   return SQLITE_OK;
41543 }
41544
41545 /*
41546 ** Compare the values contained by the two memory cells, returning
41547 ** negative, zero or positive if pMem1 is less than, equal to, or greater
41548 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
41549 ** and reals) sorted numerically, followed by text ordered by the collating
41550 ** sequence pColl and finally blob's ordered by memcmp().
41551 **
41552 ** Two NULL values are considered equal by this function.
41553 */
41554 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
41555   int rc;
41556   int f1, f2;
41557   int combined_flags;
41558
41559   /* Interchange pMem1 and pMem2 if the collating sequence specifies
41560   ** DESC order.
41561   */
41562   f1 = pMem1->flags;
41563   f2 = pMem2->flags;
41564   combined_flags = f1|f2;
41565  
41566   /* If one value is NULL, it is less than the other. If both values
41567   ** are NULL, return 0.
41568   */
41569   if( combined_flags&MEM_Null ){
41570     return (f2&MEM_Null) - (f1&MEM_Null);
41571   }
41572
41573   /* If one value is a number and the other is not, the number is less.
41574   ** If both are numbers, compare as reals if one is a real, or as integers
41575   ** if both values are integers.
41576   */
41577   if( combined_flags&(MEM_Int|MEM_Real) ){
41578     if( !(f1&(MEM_Int|MEM_Real)) ){
41579       return 1;
41580     }
41581     if( !(f2&(MEM_Int|MEM_Real)) ){
41582       return -1;
41583     }
41584     if( (f1 & f2 & MEM_Int)==0 ){
41585       double r1, r2;
41586       if( (f1&MEM_Real)==0 ){
41587         r1 = pMem1->u.i;
41588       }else{
41589         r1 = pMem1->r;
41590       }
41591       if( (f2&MEM_Real)==0 ){
41592         r2 = pMem2->u.i;
41593       }else{
41594         r2 = pMem2->r;
41595       }
41596       if( r1<r2 ) return -1;
41597       if( r1>r2 ) return 1;
41598       return 0;
41599     }else{
41600       assert( f1&MEM_Int );
41601       assert( f2&MEM_Int );
41602       if( pMem1->u.i < pMem2->u.i ) return -1;
41603       if( pMem1->u.i > pMem2->u.i ) return 1;
41604       return 0;
41605     }
41606   }
41607
41608   /* If one value is a string and the other is a blob, the string is less.
41609   ** If both are strings, compare using the collating functions.
41610   */
41611   if( combined_flags&MEM_Str ){
41612     if( (f1 & MEM_Str)==0 ){
41613       return 1;
41614     }
41615     if( (f2 & MEM_Str)==0 ){
41616       return -1;
41617     }
41618
41619     assert( pMem1->enc==pMem2->enc );
41620     assert( pMem1->enc==SQLITE_UTF8 || 
41621             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
41622
41623     /* The collation sequence must be defined at this point, even if
41624     ** the user deletes the collation sequence after the vdbe program is
41625     ** compiled (this was not always the case).
41626     */
41627     assert( !pColl || pColl->xCmp );
41628
41629     if( pColl ){
41630       if( pMem1->enc==pColl->enc ){
41631         /* The strings are already in the correct encoding.  Call the
41632         ** comparison function directly */
41633         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
41634       }else{
41635         const void *v1, *v2;
41636         int n1, n2;
41637         Mem c1;
41638         Mem c2;
41639         memset(&c1, 0, sizeof(c1));
41640         memset(&c2, 0, sizeof(c2));
41641         sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
41642         sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
41643         v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
41644         n1 = v1==0 ? 0 : c1.n;
41645         v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
41646         n2 = v2==0 ? 0 : c2.n;
41647         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
41648         sqlite3VdbeMemRelease(&c1);
41649         sqlite3VdbeMemRelease(&c2);
41650         return rc;
41651       }
41652     }
41653     /* If a NULL pointer was passed as the collate function, fall through
41654     ** to the blob case and use memcmp().  */
41655   }
41656  
41657   /* Both values must be blobs.  Compare using memcmp().  */
41658   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
41659   if( rc==0 ){
41660     rc = pMem1->n - pMem2->n;
41661   }
41662   return rc;
41663 }
41664
41665 /*
41666 ** Move data out of a btree key or data field and into a Mem structure.
41667 ** The data or key is taken from the entry that pCur is currently pointing
41668 ** to.  offset and amt determine what portion of the data or key to retrieve.
41669 ** key is true to get the key or false to get data.  The result is written
41670 ** into the pMem element.
41671 **
41672 ** The pMem structure is assumed to be uninitialized.  Any prior content
41673 ** is overwritten without being freed.
41674 **
41675 ** If this routine fails for any reason (malloc returns NULL or unable
41676 ** to read from the disk) then the pMem is left in an inconsistent state.
41677 */
41678 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
41679   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
41680   int offset,       /* Offset from the start of data to return bytes from. */
41681   int amt,          /* Number of bytes to return. */
41682   int key,          /* If true, retrieve from the btree key, not data. */
41683   Mem *pMem         /* OUT: Return data in this Mem structure. */
41684 ){
41685   char *zData;       /* Data from the btree layer */
41686   int available = 0; /* Number of bytes available on the local btree page */
41687   sqlite3 *db;       /* Database connection */
41688   int rc = SQLITE_OK;
41689
41690   db = sqlite3BtreeCursorDb(pCur);
41691   assert( sqlite3_mutex_held(db->mutex) );
41692   if( key ){
41693     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
41694   }else{
41695     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
41696   }
41697   assert( zData!=0 );
41698
41699   if( offset+amt<=available && ((pMem->flags&MEM_Dyn)==0 || pMem->xDel) ){
41700     sqlite3VdbeMemRelease(pMem);
41701     pMem->z = &zData[offset];
41702     pMem->flags = MEM_Blob|MEM_Ephem;
41703   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
41704     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
41705     pMem->enc = 0;
41706     pMem->type = SQLITE_BLOB;
41707     if( key ){
41708       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
41709     }else{
41710       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
41711     }
41712     pMem->z[amt] = 0;
41713     pMem->z[amt+1] = 0;
41714     if( rc!=SQLITE_OK ){
41715       sqlite3VdbeMemRelease(pMem);
41716     }
41717   }
41718   pMem->n = amt;
41719
41720   return rc;
41721 }
41722
41723 #if 0
41724 /*
41725 ** Perform various checks on the memory cell pMem. An assert() will
41726 ** fail if pMem is internally inconsistent.
41727 */
41728 SQLITE_PRIVATE void sqlite3VdbeMemSanity(Mem *pMem){
41729   int flags = pMem->flags;
41730   assert( flags!=0 );  /* Must define some type */
41731   if( flags & (MEM_Str|MEM_Blob) ){
41732     int x = flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short);
41733     assert( x!=0 );            /* Strings must define a string subtype */
41734     assert( (x & (x-1))==0 );  /* Only one string subtype can be defined */
41735     assert( pMem->z!=0 );      /* Strings must have a value */
41736     /* Mem.z points to Mem.zShort iff the subtype is MEM_Short */
41737     assert( (x & MEM_Short)==0 || pMem->z==pMem->zShort );
41738     assert( (x & MEM_Short)!=0 || pMem->z!=pMem->zShort );
41739     /* No destructor unless there is MEM_Dyn */
41740     assert( pMem->xDel==0 || (pMem->flags & MEM_Dyn)!=0 );
41741
41742     if( (flags & MEM_Str) ){
41743       assert( pMem->enc==SQLITE_UTF8 || 
41744               pMem->enc==SQLITE_UTF16BE ||
41745               pMem->enc==SQLITE_UTF16LE 
41746       );
41747       /* If the string is UTF-8 encoded and nul terminated, then pMem->n
41748       ** must be the length of the string.  (Later:)  If the database file
41749       ** has been corrupted, '\000' characters might have been inserted
41750       ** into the middle of the string.  In that case, the strlen() might
41751       ** be less.
41752       */
41753       if( pMem->enc==SQLITE_UTF8 && (flags & MEM_Term) ){ 
41754         assert( strlen(pMem->z)<=pMem->n );
41755         assert( pMem->z[pMem->n]==0 );
41756       }
41757     }
41758   }else{
41759     /* Cannot define a string subtype for non-string objects */
41760     assert( (pMem->flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short))==0 );
41761     assert( pMem->xDel==0 );
41762   }
41763   /* MEM_Null excludes all other types */
41764   assert( (pMem->flags&(MEM_Str|MEM_Int|MEM_Real|MEM_Blob))==0
41765           || (pMem->flags&MEM_Null)==0 );
41766   /* If the MEM is both real and integer, the values are equal */
41767   assert( (pMem->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) 
41768           || pMem->r==pMem->u.i );
41769 }
41770 #endif
41771
41772 /* This function is only available internally, it is not part of the
41773 ** external API. It works in a similar way to sqlite3_value_text(),
41774 ** except the data returned is in the encoding specified by the second
41775 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
41776 ** SQLITE_UTF8.
41777 **
41778 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
41779 ** If that is the case, then the result must be aligned on an even byte
41780 ** boundary.
41781 */
41782 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
41783   if( !pVal ) return 0;
41784
41785   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
41786   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
41787
41788   if( pVal->flags&MEM_Null ){
41789     return 0;
41790   }
41791   assert( (MEM_Blob>>3) == MEM_Str );
41792   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
41793   expandBlob(pVal);
41794   if( pVal->flags&MEM_Str ){
41795     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
41796     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
41797       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
41798       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
41799         return 0;
41800       }
41801     }
41802     sqlite3VdbeMemNulTerminate(pVal);
41803   }else{
41804     assert( (pVal->flags&MEM_Blob)==0 );
41805     sqlite3VdbeMemStringify(pVal, enc);
41806     assert( 0==(1&(int)pVal->z) );
41807   }
41808   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
41809               || pVal->db->mallocFailed );
41810   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
41811     return pVal->z;
41812   }else{
41813     return 0;
41814   }
41815 }
41816
41817 /*
41818 ** Create a new sqlite3_value object.
41819 */
41820 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
41821   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
41822   if( p ){
41823     p->flags = MEM_Null;
41824     p->type = SQLITE_NULL;
41825     p->db = db;
41826   }
41827   return p;
41828 }
41829
41830 /*
41831 ** Create a new sqlite3_value object, containing the value of pExpr.
41832 **
41833 ** This only works for very simple expressions that consist of one constant
41834 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
41835 ** be converted directly into a value, then the value is allocated and
41836 ** a pointer written to *ppVal. The caller is responsible for deallocating
41837 ** the value by passing it to sqlite3ValueFree() later on. If the expression
41838 ** cannot be converted to a value, then *ppVal is set to NULL.
41839 */
41840 SQLITE_PRIVATE int sqlite3ValueFromExpr(
41841   sqlite3 *db,              /* The database connection */
41842   Expr *pExpr,              /* The expression to evaluate */
41843   u8 enc,                   /* Encoding to use */
41844   u8 affinity,              /* Affinity to use */
41845   sqlite3_value **ppVal     /* Write the new value here */
41846 ){
41847   int op;
41848   char *zVal = 0;
41849   sqlite3_value *pVal = 0;
41850
41851   if( !pExpr ){
41852     *ppVal = 0;
41853     return SQLITE_OK;
41854   }
41855   op = pExpr->op;
41856
41857   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
41858     zVal = sqlite3DbStrNDup(db, (char*)pExpr->token.z, pExpr->token.n);
41859     pVal = sqlite3ValueNew(db);
41860     if( !zVal || !pVal ) goto no_mem;
41861     sqlite3Dequote(zVal);
41862     sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
41863     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
41864       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, enc);
41865     }else{
41866       sqlite3ValueApplyAffinity(pVal, affinity, enc);
41867     }
41868   }else if( op==TK_UMINUS ) {
41869     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
41870       pVal->u.i = -1 * pVal->u.i;
41871       pVal->r = -1.0 * pVal->r;
41872     }
41873   }
41874 #ifndef SQLITE_OMIT_BLOB_LITERAL
41875   else if( op==TK_BLOB ){
41876     int nVal;
41877     assert( pExpr->token.n>=3 );
41878     assert( pExpr->token.z[0]=='x' || pExpr->token.z[0]=='X' );
41879     assert( pExpr->token.z[1]=='\'' );
41880     assert( pExpr->token.z[pExpr->token.n-1]=='\'' );
41881     pVal = sqlite3ValueNew(db);
41882     nVal = pExpr->token.n - 3;
41883     zVal = (char*)pExpr->token.z + 2;
41884     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
41885                          0, SQLITE_DYNAMIC);
41886   }
41887 #endif
41888
41889   *ppVal = pVal;
41890   return SQLITE_OK;
41891
41892 no_mem:
41893   db->mallocFailed = 1;
41894   sqlite3DbFree(db, zVal);
41895   sqlite3ValueFree(pVal);
41896   *ppVal = 0;
41897   return SQLITE_NOMEM;
41898 }
41899
41900 /*
41901 ** Change the string value of an sqlite3_value object
41902 */
41903 SQLITE_PRIVATE void sqlite3ValueSetStr(
41904   sqlite3_value *v,     /* Value to be set */
41905   int n,                /* Length of string z */
41906   const void *z,        /* Text of the new string */
41907   u8 enc,               /* Encoding to use */
41908   void (*xDel)(void*)   /* Destructor for the string */
41909 ){
41910   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
41911 }
41912
41913 /*
41914 ** Free an sqlite3_value object
41915 */
41916 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
41917   if( !v ) return;
41918   sqlite3VdbeMemRelease((Mem *)v);
41919   sqlite3DbFree(((Mem*)v)->db, v);
41920 }
41921
41922 /*
41923 ** Return the number of bytes in the sqlite3_value object assuming
41924 ** that it uses the encoding "enc"
41925 */
41926 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
41927   Mem *p = (Mem*)pVal;
41928   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
41929     if( p->flags & MEM_Zero ){
41930       return p->n+p->u.i;
41931     }else{
41932       return p->n;
41933     }
41934   }
41935   return 0;
41936 }
41937
41938 /************** End of vdbemem.c *********************************************/
41939 /************** Begin file vdbeaux.c *****************************************/
41940 /*
41941 ** 2003 September 6
41942 **
41943 ** The author disclaims copyright to this source code.  In place of
41944 ** a legal notice, here is a blessing:
41945 **
41946 **    May you do good and not evil.
41947 **    May you find forgiveness for yourself and forgive others.
41948 **    May you share freely, never taking more than you give.
41949 **
41950 *************************************************************************
41951 ** This file contains code used for creating, destroying, and populating
41952 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
41953 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
41954 ** But that file was getting too big so this subroutines were split out.
41955 **
41956 ** $Id: vdbeaux.c,v 1.411 2008/09/19 18:32:27 danielk1977 Exp $
41957 */
41958
41959
41960
41961 /*
41962 ** When debugging the code generator in a symbolic debugger, one can
41963 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
41964 ** as they are added to the instruction stream.
41965 */
41966 #ifdef SQLITE_DEBUG
41967 SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
41968 #endif
41969
41970
41971 /*
41972 ** Create a new virtual database engine.
41973 */
41974 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
41975   Vdbe *p;
41976   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
41977   if( p==0 ) return 0;
41978   p->db = db;
41979   if( db->pVdbe ){
41980     db->pVdbe->pPrev = p;
41981   }
41982   p->pNext = db->pVdbe;
41983   p->pPrev = 0;
41984   db->pVdbe = p;
41985   p->magic = VDBE_MAGIC_INIT;
41986   return p;
41987 }
41988
41989 /*
41990 ** Remember the SQL string for a prepared statement.
41991 */
41992 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n){
41993   if( p==0 ) return;
41994   assert( p->zSql==0 );
41995   p->zSql = sqlite3DbStrNDup(p->db, z, n);
41996 }
41997
41998 /*
41999 ** Return the SQL associated with a prepared statement
42000 */
42001 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
42002   return ((Vdbe *)pStmt)->zSql;
42003 }
42004
42005 /*
42006 ** Swap all content between two VDBE structures.
42007 */
42008 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
42009   Vdbe tmp, *pTmp;
42010   char *zTmp;
42011   int nTmp;
42012   tmp = *pA;
42013   *pA = *pB;
42014   *pB = tmp;
42015   pTmp = pA->pNext;
42016   pA->pNext = pB->pNext;
42017   pB->pNext = pTmp;
42018   pTmp = pA->pPrev;
42019   pA->pPrev = pB->pPrev;
42020   pB->pPrev = pTmp;
42021   zTmp = pA->zSql;
42022   pA->zSql = pB->zSql;
42023   pB->zSql = zTmp;
42024   nTmp = pA->nSql;
42025   pA->nSql = pB->nSql;
42026   pB->nSql = nTmp;
42027 }
42028
42029 #ifdef SQLITE_DEBUG
42030 /*
42031 ** Turn tracing on or off
42032 */
42033 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
42034   p->trace = trace;
42035 }
42036 #endif
42037
42038 /*
42039 ** Resize the Vdbe.aOp array so that it contains at least N
42040 ** elements.
42041 **
42042 ** If an out-of-memory error occurs while resizing the array,
42043 ** Vdbe.aOp and Vdbe.nOpAlloc remain unchanged (this is so that
42044 ** any opcodes already allocated can be correctly deallocated
42045 ** along with the rest of the Vdbe).
42046 */
42047 static void resizeOpArray(Vdbe *p, int N){
42048   VdbeOp *pNew;
42049   pNew = sqlite3DbRealloc(p->db, p->aOp, N*sizeof(Op));
42050   if( pNew ){
42051     p->nOpAlloc = N;
42052     p->aOp = pNew;
42053   }
42054 }
42055
42056 /*
42057 ** Add a new instruction to the list of instructions current in the
42058 ** VDBE.  Return the address of the new instruction.
42059 **
42060 ** Parameters:
42061 **
42062 **    p               Pointer to the VDBE
42063 **
42064 **    op              The opcode for this instruction
42065 **
42066 **    p1, p2, p3      Operands
42067 **
42068 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
42069 ** the sqlite3VdbeChangeP4() function to change the value of the P4
42070 ** operand.
42071 */
42072 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
42073   int i;
42074   VdbeOp *pOp;
42075
42076   i = p->nOp;
42077   assert( p->magic==VDBE_MAGIC_INIT );
42078   if( p->nOpAlloc<=i ){
42079     resizeOpArray(p, p->nOpAlloc ? p->nOpAlloc*2 : 1024/sizeof(Op));
42080     if( p->db->mallocFailed ){
42081       return 0;
42082     }
42083   }
42084   p->nOp++;
42085   pOp = &p->aOp[i];
42086   pOp->opcode = op;
42087   pOp->p5 = 0;
42088   pOp->p1 = p1;
42089   pOp->p2 = p2;
42090   pOp->p3 = p3;
42091   pOp->p4.p = 0;
42092   pOp->p4type = P4_NOTUSED;
42093   p->expired = 0;
42094 #ifdef SQLITE_DEBUG
42095   pOp->zComment = 0;
42096   if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
42097 #endif
42098 #ifdef VDBE_PROFILE
42099   pOp->cycles = 0;
42100   pOp->cnt = 0;
42101 #endif
42102   return i;
42103 }
42104 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
42105   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
42106 }
42107 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
42108   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
42109 }
42110 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
42111   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
42112 }
42113
42114
42115 /*
42116 ** Add an opcode that includes the p4 value as a pointer.
42117 */
42118 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
42119   Vdbe *p,            /* Add the opcode to this VM */
42120   int op,             /* The new opcode */
42121   int p1,             /* The P1 operand */
42122   int p2,             /* The P2 operand */
42123   int p3,             /* The P3 operand */
42124   const char *zP4,    /* The P4 operand */
42125   int p4type          /* P4 operand type */
42126 ){
42127   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
42128   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
42129   return addr;
42130 }
42131
42132 /*
42133 ** Create a new symbolic label for an instruction that has yet to be
42134 ** coded.  The symbolic label is really just a negative number.  The
42135 ** label can be used as the P2 value of an operation.  Later, when
42136 ** the label is resolved to a specific address, the VDBE will scan
42137 ** through its operation list and change all values of P2 which match
42138 ** the label into the resolved address.
42139 **
42140 ** The VDBE knows that a P2 value is a label because labels are
42141 ** always negative and P2 values are suppose to be non-negative.
42142 ** Hence, a negative P2 value is a label that has yet to be resolved.
42143 **
42144 ** Zero is returned if a malloc() fails.
42145 */
42146 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
42147   int i;
42148   i = p->nLabel++;
42149   assert( p->magic==VDBE_MAGIC_INIT );
42150   if( i>=p->nLabelAlloc ){
42151     p->nLabelAlloc = p->nLabelAlloc*2 + 10;
42152     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
42153                                     p->nLabelAlloc*sizeof(p->aLabel[0]));
42154   }
42155   if( p->aLabel ){
42156     p->aLabel[i] = -1;
42157   }
42158   return -1-i;
42159 }
42160
42161 /*
42162 ** Resolve label "x" to be the address of the next instruction to
42163 ** be inserted.  The parameter "x" must have been obtained from
42164 ** a prior call to sqlite3VdbeMakeLabel().
42165 */
42166 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
42167   int j = -1-x;
42168   assert( p->magic==VDBE_MAGIC_INIT );
42169   assert( j>=0 && j<p->nLabel );
42170   if( p->aLabel ){
42171     p->aLabel[j] = p->nOp;
42172   }
42173 }
42174
42175 /*
42176 ** Loop through the program looking for P2 values that are negative
42177 ** on jump instructions.  Each such value is a label.  Resolve the
42178 ** label by setting the P2 value to its correct non-zero value.
42179 **
42180 ** This routine is called once after all opcodes have been inserted.
42181 **
42182 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
42183 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by 
42184 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
42185 **
42186 ** This routine also does the following optimization:  It scans for
42187 ** instructions that might cause a statement rollback.  Such instructions
42188 ** are:
42189 **
42190 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
42191 **   *  OP_Destroy
42192 **   *  OP_VUpdate
42193 **   *  OP_VRename
42194 **
42195 ** If no such instruction is found, then every Statement instruction 
42196 ** is changed to a Noop.  In this way, we avoid creating the statement 
42197 ** journal file unnecessarily.
42198 */
42199 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
42200   int i;
42201   int nMaxArgs = 0;
42202   Op *pOp;
42203   int *aLabel = p->aLabel;
42204   int doesStatementRollback = 0;
42205   int hasStatementBegin = 0;
42206   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
42207     u8 opcode = pOp->opcode;
42208
42209     if( opcode==OP_Function || opcode==OP_AggStep ){
42210       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
42211 #ifndef SQLITE_OMIT_VIRTUALTABLE
42212     }else if( opcode==OP_VUpdate ){
42213       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
42214 #endif
42215     }
42216     if( opcode==OP_Halt ){
42217       if( pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort ){
42218         doesStatementRollback = 1;
42219       }
42220     }else if( opcode==OP_Statement ){
42221       hasStatementBegin = 1;
42222     }else if( opcode==OP_Destroy ){
42223       doesStatementRollback = 1;
42224 #ifndef SQLITE_OMIT_VIRTUALTABLE
42225     }else if( opcode==OP_VUpdate || opcode==OP_VRename ){
42226       doesStatementRollback = 1;
42227     }else if( opcode==OP_VFilter ){
42228       int n;
42229       assert( p->nOp - i >= 3 );
42230       assert( pOp[-1].opcode==OP_Integer );
42231       n = pOp[-1].p1;
42232       if( n>nMaxArgs ) nMaxArgs = n;
42233 #endif
42234     }
42235
42236     if( sqlite3VdbeOpcodeHasProperty(opcode, OPFLG_JUMP) && pOp->p2<0 ){
42237       assert( -1-pOp->p2<p->nLabel );
42238       pOp->p2 = aLabel[-1-pOp->p2];
42239     }
42240   }
42241   sqlite3DbFree(p->db, p->aLabel);
42242   p->aLabel = 0;
42243
42244   *pMaxFuncArgs = nMaxArgs;
42245
42246   /* If we never rollback a statement transaction, then statement
42247   ** transactions are not needed.  So change every OP_Statement
42248   ** opcode into an OP_Noop.  This avoid a call to sqlite3OsOpenExclusive()
42249   ** which can be expensive on some platforms.
42250   */
42251   if( hasStatementBegin && !doesStatementRollback ){
42252     for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
42253       if( pOp->opcode==OP_Statement ){
42254         pOp->opcode = OP_Noop;
42255       }
42256     }
42257   }
42258 }
42259
42260 /*
42261 ** Return the address of the next instruction to be inserted.
42262 */
42263 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
42264   assert( p->magic==VDBE_MAGIC_INIT );
42265   return p->nOp;
42266 }
42267
42268 /*
42269 ** Add a whole list of operations to the operation stack.  Return the
42270 ** address of the first operation added.
42271 */
42272 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
42273   int addr;
42274   assert( p->magic==VDBE_MAGIC_INIT );
42275   if( p->nOp + nOp > p->nOpAlloc ){
42276     resizeOpArray(p, p->nOpAlloc ? p->nOpAlloc*2 : 1024/sizeof(Op));
42277     assert( p->nOp+nOp<=p->nOpAlloc || p->db->mallocFailed );
42278   }
42279   if( p->db->mallocFailed ){
42280     return 0;
42281   }
42282   addr = p->nOp;
42283   if( nOp>0 ){
42284     int i;
42285     VdbeOpList const *pIn = aOp;
42286     for(i=0; i<nOp; i++, pIn++){
42287       int p2 = pIn->p2;
42288       VdbeOp *pOut = &p->aOp[i+addr];
42289       pOut->opcode = pIn->opcode;
42290       pOut->p1 = pIn->p1;
42291       if( p2<0 && sqlite3VdbeOpcodeHasProperty(pOut->opcode, OPFLG_JUMP) ){
42292         pOut->p2 = addr + ADDR(p2);
42293       }else{
42294         pOut->p2 = p2;
42295       }
42296       pOut->p3 = pIn->p3;
42297       pOut->p4type = P4_NOTUSED;
42298       pOut->p4.p = 0;
42299       pOut->p5 = 0;
42300 #ifdef SQLITE_DEBUG
42301       pOut->zComment = 0;
42302       if( sqlite3VdbeAddopTrace ){
42303         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
42304       }
42305 #endif
42306     }
42307     p->nOp += nOp;
42308   }
42309   return addr;
42310 }
42311
42312 /*
42313 ** Change the value of the P1 operand for a specific instruction.
42314 ** This routine is useful when a large program is loaded from a
42315 ** static array using sqlite3VdbeAddOpList but we want to make a
42316 ** few minor changes to the program.
42317 */
42318 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
42319   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
42320   if( p && addr>=0 && p->nOp>addr && p->aOp ){
42321     p->aOp[addr].p1 = val;
42322   }
42323 }
42324
42325 /*
42326 ** Change the value of the P2 operand for a specific instruction.
42327 ** This routine is useful for setting a jump destination.
42328 */
42329 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
42330   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
42331   if( p && addr>=0 && p->nOp>addr && p->aOp ){
42332     p->aOp[addr].p2 = val;
42333   }
42334 }
42335
42336 /*
42337 ** Change the value of the P3 operand for a specific instruction.
42338 */
42339 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
42340   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
42341   if( p && addr>=0 && p->nOp>addr && p->aOp ){
42342     p->aOp[addr].p3 = val;
42343   }
42344 }
42345
42346 /*
42347 ** Change the value of the P5 operand for the most recently
42348 ** added operation.
42349 */
42350 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
42351   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
42352   if( p && p->aOp ){
42353     assert( p->nOp>0 );
42354     p->aOp[p->nOp-1].p5 = val;
42355   }
42356 }
42357
42358 /*
42359 ** Change the P2 operand of instruction addr so that it points to
42360 ** the address of the next instruction to be coded.
42361 */
42362 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
42363   sqlite3VdbeChangeP2(p, addr, p->nOp);
42364 }
42365
42366
42367 /*
42368 ** If the input FuncDef structure is ephemeral, then free it.  If
42369 ** the FuncDef is not ephermal, then do nothing.
42370 */
42371 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
42372   if( pDef && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
42373     sqlite3DbFree(db, pDef);
42374   }
42375 }
42376
42377 /*
42378 ** Delete a P4 value if necessary.
42379 */
42380 static void freeP4(sqlite3 *db, int p4type, void *p4){
42381   if( p4 ){
42382     switch( p4type ){
42383       case P4_REAL:
42384       case P4_INT64:
42385       case P4_MPRINTF:
42386       case P4_DYNAMIC:
42387       case P4_KEYINFO:
42388       case P4_INTARRAY:
42389       case P4_KEYINFO_HANDOFF: {
42390         sqlite3DbFree(db, p4);
42391         break;
42392       }
42393       case P4_VDBEFUNC: {
42394         VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
42395         freeEphemeralFunction(db, pVdbeFunc->pFunc);
42396         sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
42397         sqlite3DbFree(db, pVdbeFunc);
42398         break;
42399       }
42400       case P4_FUNCDEF: {
42401         freeEphemeralFunction(db, (FuncDef*)p4);
42402         break;
42403       }
42404       case P4_MEM: {
42405         sqlite3ValueFree((sqlite3_value*)p4);
42406         break;
42407       }
42408     }
42409   }
42410 }
42411
42412
42413 /*
42414 ** Change N opcodes starting at addr to No-ops.
42415 */
42416 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
42417   if( p && p->aOp ){
42418     VdbeOp *pOp = &p->aOp[addr];
42419     sqlite3 *db = p->db;
42420     while( N-- ){
42421       freeP4(db, pOp->p4type, pOp->p4.p);
42422       memset(pOp, 0, sizeof(pOp[0]));
42423       pOp->opcode = OP_Noop;
42424       pOp++;
42425     }
42426   }
42427 }
42428
42429 /*
42430 ** Change the value of the P4 operand for a specific instruction.
42431 ** This routine is useful when a large program is loaded from a
42432 ** static array using sqlite3VdbeAddOpList but we want to make a
42433 ** few minor changes to the program.
42434 **
42435 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
42436 ** the string is made into memory obtained from sqlite3_malloc().
42437 ** A value of n==0 means copy bytes of zP4 up to and including the
42438 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
42439 **
42440 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
42441 ** A copy is made of the KeyInfo structure into memory obtained from
42442 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
42443 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
42444 ** stored in memory that the caller has obtained from sqlite3_malloc. The 
42445 ** caller should not free the allocation, it will be freed when the Vdbe is
42446 ** finalized.
42447 ** 
42448 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
42449 ** to a string or structure that is guaranteed to exist for the lifetime of
42450 ** the Vdbe. In these cases we can just copy the pointer.
42451 **
42452 ** If addr<0 then change P4 on the most recently inserted instruction.
42453 */
42454 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
42455   Op *pOp;
42456   sqlite3 *db;
42457   assert( p!=0 );
42458   db = p->db;
42459   assert( p->magic==VDBE_MAGIC_INIT );
42460   if( p->aOp==0 || db->mallocFailed ){
42461     if (n != P4_KEYINFO) {
42462       freeP4(db, n, (void*)*(char**)&zP4);
42463     }
42464     return;
42465   }
42466   assert( addr<p->nOp );
42467   if( addr<0 ){
42468     addr = p->nOp - 1;
42469     if( addr<0 ) return;
42470   }
42471   pOp = &p->aOp[addr];
42472   freeP4(db, pOp->p4type, pOp->p4.p);
42473   pOp->p4.p = 0;
42474   if( n==P4_INT32 ){
42475     /* Note: this cast is safe, because the origin data point was an int
42476     ** that was cast to a (const char *). */
42477     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
42478     pOp->p4type = n;
42479   }else if( zP4==0 ){
42480     pOp->p4.p = 0;
42481     pOp->p4type = P4_NOTUSED;
42482   }else if( n==P4_KEYINFO ){
42483     KeyInfo *pKeyInfo;
42484     int nField, nByte;
42485
42486     nField = ((KeyInfo*)zP4)->nField;
42487     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
42488     pKeyInfo = sqlite3Malloc( nByte );
42489     pOp->p4.pKeyInfo = pKeyInfo;
42490     if( pKeyInfo ){
42491       u8 *aSortOrder;
42492       memcpy(pKeyInfo, zP4, nByte);
42493       aSortOrder = pKeyInfo->aSortOrder;
42494       if( aSortOrder ){
42495         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
42496         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
42497       }
42498       pOp->p4type = P4_KEYINFO;
42499     }else{
42500       p->db->mallocFailed = 1;
42501       pOp->p4type = P4_NOTUSED;
42502     }
42503   }else if( n==P4_KEYINFO_HANDOFF ){
42504     pOp->p4.p = (void*)zP4;
42505     pOp->p4type = P4_KEYINFO;
42506   }else if( n<0 ){
42507     pOp->p4.p = (void*)zP4;
42508     pOp->p4type = n;
42509   }else{
42510     if( n==0 ) n = strlen(zP4);
42511     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
42512     pOp->p4type = P4_DYNAMIC;
42513   }
42514 }
42515
42516 #ifndef NDEBUG
42517 /*
42518 ** Change the comment on the the most recently coded instruction.  Or
42519 ** insert a No-op and add the comment to that new instruction.  This
42520 ** makes the code easier to read during debugging.  None of this happens
42521 ** in a production build.
42522 */
42523 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
42524   va_list ap;
42525   assert( p->nOp>0 || p->aOp==0 );
42526   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
42527   if( p->nOp ){
42528     char **pz = &p->aOp[p->nOp-1].zComment;
42529     va_start(ap, zFormat);
42530     sqlite3DbFree(p->db, *pz);
42531     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
42532     va_end(ap);
42533   }
42534 }
42535 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
42536   va_list ap;
42537   sqlite3VdbeAddOp0(p, OP_Noop);
42538   assert( p->nOp>0 || p->aOp==0 );
42539   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
42540   if( p->nOp ){
42541     char **pz = &p->aOp[p->nOp-1].zComment;
42542     va_start(ap, zFormat);
42543     sqlite3DbFree(p->db, *pz);
42544     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
42545     va_end(ap);
42546   }
42547 }
42548 #endif  /* NDEBUG */
42549
42550 /*
42551 ** Return the opcode for a given address.
42552 */
42553 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
42554   assert( p->magic==VDBE_MAGIC_INIT );
42555   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
42556   return ((addr>=0 && addr<p->nOp)?(&p->aOp[addr]):0);
42557 }
42558
42559 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
42560      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
42561 /*
42562 ** Compute a string that describes the P4 parameter for an opcode.
42563 ** Use zTemp for any required temporary buffer space.
42564 */
42565 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
42566   char *zP4 = zTemp;
42567   assert( nTemp>=20 );
42568   switch( pOp->p4type ){
42569     case P4_KEYINFO_STATIC:
42570     case P4_KEYINFO: {
42571       int i, j;
42572       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
42573       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
42574       i = strlen(zTemp);
42575       for(j=0; j<pKeyInfo->nField; j++){
42576         CollSeq *pColl = pKeyInfo->aColl[j];
42577         if( pColl ){
42578           int n = strlen(pColl->zName);
42579           if( i+n>nTemp-6 ){
42580             memcpy(&zTemp[i],",...",4);
42581             break;
42582           }
42583           zTemp[i++] = ',';
42584           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
42585             zTemp[i++] = '-';
42586           }
42587           memcpy(&zTemp[i], pColl->zName,n+1);
42588           i += n;
42589         }else if( i+4<nTemp-6 ){
42590           memcpy(&zTemp[i],",nil",4);
42591           i += 4;
42592         }
42593       }
42594       zTemp[i++] = ')';
42595       zTemp[i] = 0;
42596       assert( i<nTemp );
42597       break;
42598     }
42599     case P4_COLLSEQ: {
42600       CollSeq *pColl = pOp->p4.pColl;
42601       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
42602       break;
42603     }
42604     case P4_FUNCDEF: {
42605       FuncDef *pDef = pOp->p4.pFunc;
42606       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
42607       break;
42608     }
42609     case P4_INT64: {
42610       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
42611       break;
42612     }
42613     case P4_INT32: {
42614       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
42615       break;
42616     }
42617     case P4_REAL: {
42618       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
42619       break;
42620     }
42621     case P4_MEM: {
42622       Mem *pMem = pOp->p4.pMem;
42623       assert( (pMem->flags & MEM_Null)==0 );
42624       if( pMem->flags & MEM_Str ){
42625         zP4 = pMem->z;
42626       }else if( pMem->flags & MEM_Int ){
42627         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
42628       }else if( pMem->flags & MEM_Real ){
42629         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
42630       }
42631       break;
42632     }
42633 #ifndef SQLITE_OMIT_VIRTUALTABLE
42634     case P4_VTAB: {
42635       sqlite3_vtab *pVtab = pOp->p4.pVtab;
42636       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
42637       break;
42638     }
42639 #endif
42640     case P4_INTARRAY: {
42641       sqlite3_snprintf(nTemp, zTemp, "intarray");
42642       break;
42643     }
42644     default: {
42645       zP4 = pOp->p4.z;
42646       if( zP4==0 ){
42647         zP4 = zTemp;
42648         zTemp[0] = 0;
42649       }
42650     }
42651   }
42652   assert( zP4!=0 );
42653   return zP4;
42654 }
42655 #endif
42656
42657 /*
42658 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
42659 **
42660 */
42661 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
42662   int mask;
42663   assert( i>=0 && i<p->db->nDb );
42664   assert( i<sizeof(p->btreeMask)*8 );
42665   mask = 1<<i;
42666   if( (p->btreeMask & mask)==0 ){
42667     p->btreeMask |= mask;
42668     sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
42669   }
42670 }
42671
42672
42673 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
42674 /*
42675 ** Print a single opcode.  This routine is used for debugging only.
42676 */
42677 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
42678   char *zP4;
42679   char zPtr[50];
42680   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
42681   if( pOut==0 ) pOut = stdout;
42682   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
42683   fprintf(pOut, zFormat1, pc, 
42684       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
42685 #ifdef SQLITE_DEBUG
42686       pOp->zComment ? pOp->zComment : ""
42687 #else
42688       ""
42689 #endif
42690   );
42691   fflush(pOut);
42692 }
42693 #endif
42694
42695 /*
42696 ** Release an array of N Mem elements
42697 */
42698 static void releaseMemArray(Mem *p, int N){
42699   if( p && N ){
42700     Mem *pEnd;
42701     sqlite3 *db = p->db;
42702     int malloc_failed = db->mallocFailed;
42703     for(pEnd=&p[N]; p<pEnd; p++){
42704       assert( (&p[1])==pEnd || p[0].db==p[1].db );
42705
42706       /* This block is really an inlined version of sqlite3VdbeMemRelease()
42707       ** that takes advantage of the fact that the memory cell value is 
42708       ** being set to NULL after releasing any dynamic resources.
42709       **
42710       ** The justification for duplicating code is that according to 
42711       ** callgrind, this causes a certain test case to hit the CPU 4.7 
42712       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if 
42713       ** sqlite3MemRelease() were called from here. With -O2, this jumps
42714       ** to 6.6 percent. The test case is inserting 1000 rows into a table 
42715       ** with no indexes using a single prepared INSERT statement, bind() 
42716       ** and reset(). Inserts are grouped into a transaction.
42717       */
42718       if( p->flags&(MEM_Agg|MEM_Dyn) ){
42719         sqlite3VdbeMemRelease(p);
42720       }else if( p->zMalloc ){
42721         sqlite3DbFree(db, p->zMalloc);
42722         p->zMalloc = 0;
42723       }
42724
42725       p->flags = MEM_Null;
42726     }
42727     db->mallocFailed = malloc_failed;
42728   }
42729 }
42730
42731 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
42732 SQLITE_PRIVATE int sqlite3VdbeReleaseBuffers(Vdbe *p){
42733   int ii;
42734   int nFree = 0;
42735   assert( sqlite3_mutex_held(p->db->mutex) );
42736   for(ii=1; ii<=p->nMem; ii++){
42737     Mem *pMem = &p->aMem[ii];
42738     if( pMem->z && pMem->flags&MEM_Dyn ){
42739       assert( !pMem->xDel );
42740       nFree += sqlite3DbMallocSize(pMem->db, pMem->z);
42741       sqlite3VdbeMemRelease(pMem);
42742     }
42743   }
42744   return nFree;
42745 }
42746 #endif
42747
42748 #ifndef SQLITE_OMIT_EXPLAIN
42749 /*
42750 ** Give a listing of the program in the virtual machine.
42751 **
42752 ** The interface is the same as sqlite3VdbeExec().  But instead of
42753 ** running the code, it invokes the callback once for each instruction.
42754 ** This feature is used to implement "EXPLAIN".
42755 **
42756 ** When p->explain==1, each instruction is listed.  When
42757 ** p->explain==2, only OP_Explain instructions are listed and these
42758 ** are shown in a different format.  p->explain==2 is used to implement
42759 ** EXPLAIN QUERY PLAN.
42760 */
42761 SQLITE_PRIVATE int sqlite3VdbeList(
42762   Vdbe *p                   /* The VDBE */
42763 ){
42764   sqlite3 *db = p->db;
42765   int i;
42766   int rc = SQLITE_OK;
42767   Mem *pMem = p->pResultSet = &p->aMem[1];
42768
42769   assert( p->explain );
42770   if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
42771   assert( db->magic==SQLITE_MAGIC_BUSY );
42772   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
42773
42774   /* Even though this opcode does not use dynamic strings for
42775   ** the result, result columns may become dynamic if the user calls
42776   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
42777   */
42778   releaseMemArray(pMem, p->nMem);
42779
42780   do{
42781     i = p->pc++;
42782   }while( i<p->nOp && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
42783   if( i>=p->nOp ){
42784     p->rc = SQLITE_OK;
42785     rc = SQLITE_DONE;
42786   }else if( db->u1.isInterrupted ){
42787     p->rc = SQLITE_INTERRUPT;
42788     rc = SQLITE_ERROR;
42789     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
42790   }else{
42791     char *z;
42792     Op *pOp = &p->aOp[i];
42793     if( p->explain==1 ){
42794       pMem->flags = MEM_Int;
42795       pMem->type = SQLITE_INTEGER;
42796       pMem->u.i = i;                                /* Program counter */
42797       pMem++;
42798   
42799       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
42800       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
42801       assert( pMem->z!=0 );
42802       pMem->n = strlen(pMem->z);
42803       pMem->type = SQLITE_TEXT;
42804       pMem->enc = SQLITE_UTF8;
42805       pMem++;
42806     }
42807
42808     pMem->flags = MEM_Int;
42809     pMem->u.i = pOp->p1;                          /* P1 */
42810     pMem->type = SQLITE_INTEGER;
42811     pMem++;
42812
42813     pMem->flags = MEM_Int;
42814     pMem->u.i = pOp->p2;                          /* P2 */
42815     pMem->type = SQLITE_INTEGER;
42816     pMem++;
42817
42818     if( p->explain==1 ){
42819       pMem->flags = MEM_Int;
42820       pMem->u.i = pOp->p3;                          /* P3 */
42821       pMem->type = SQLITE_INTEGER;
42822       pMem++;
42823     }
42824
42825     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
42826       p->db->mallocFailed = 1;
42827       return SQLITE_NOMEM;
42828     }
42829     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
42830     z = displayP4(pOp, pMem->z, 32);
42831     if( z!=pMem->z ){
42832       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
42833     }else{
42834       assert( pMem->z!=0 );
42835       pMem->n = strlen(pMem->z);
42836       pMem->enc = SQLITE_UTF8;
42837     }
42838     pMem->type = SQLITE_TEXT;
42839     pMem++;
42840
42841     if( p->explain==1 ){
42842       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
42843         p->db->mallocFailed = 1;
42844         return SQLITE_NOMEM;
42845       }
42846       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
42847       pMem->n = 2;
42848       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
42849       pMem->type = SQLITE_TEXT;
42850       pMem->enc = SQLITE_UTF8;
42851       pMem++;
42852   
42853 #ifdef SQLITE_DEBUG
42854       if( pOp->zComment ){
42855         pMem->flags = MEM_Str|MEM_Term;
42856         pMem->z = pOp->zComment;
42857         pMem->n = strlen(pMem->z);
42858         pMem->enc = SQLITE_UTF8;
42859         pMem->type = SQLITE_TEXT;
42860       }else
42861 #endif
42862       {
42863         pMem->flags = MEM_Null;                       /* Comment */
42864         pMem->type = SQLITE_NULL;
42865       }
42866     }
42867
42868     p->nResColumn = 8 - 5*(p->explain-1);
42869     p->rc = SQLITE_OK;
42870     rc = SQLITE_ROW;
42871   }
42872   return rc;
42873 }
42874 #endif /* SQLITE_OMIT_EXPLAIN */
42875
42876 #ifdef SQLITE_DEBUG
42877 /*
42878 ** Print the SQL that was used to generate a VDBE program.
42879 */
42880 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
42881   int nOp = p->nOp;
42882   VdbeOp *pOp;
42883   if( nOp<1 ) return;
42884   pOp = &p->aOp[0];
42885   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
42886     const char *z = pOp->p4.z;
42887     while( isspace(*(u8*)z) ) z++;
42888     printf("SQL: [%s]\n", z);
42889   }
42890 }
42891 #endif
42892
42893 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
42894 /*
42895 ** Print an IOTRACE message showing SQL content.
42896 */
42897 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
42898   int nOp = p->nOp;
42899   VdbeOp *pOp;
42900   if( sqlite3IoTrace==0 ) return;
42901   if( nOp<1 ) return;
42902   pOp = &p->aOp[0];
42903   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
42904     int i, j;
42905     char z[1000];
42906     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
42907     for(i=0; isspace((unsigned char)z[i]); i++){}
42908     for(j=0; z[i]; i++){
42909       if( isspace((unsigned char)z[i]) ){
42910         if( z[i-1]!=' ' ){
42911           z[j++] = ' ';
42912         }
42913       }else{
42914         z[j++] = z[i];
42915       }
42916     }
42917     z[j] = 0;
42918     sqlite3IoTrace("SQL %s\n", z);
42919   }
42920 }
42921 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
42922
42923
42924 /*
42925 ** Prepare a virtual machine for execution.  This involves things such
42926 ** as allocating stack space and initializing the program counter.
42927 ** After the VDBE has be prepped, it can be executed by one or more
42928 ** calls to sqlite3VdbeExec().  
42929 **
42930 ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
42931 ** VDBE_MAGIC_RUN.
42932 */
42933 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
42934   Vdbe *p,                       /* The VDBE */
42935   int nVar,                      /* Number of '?' see in the SQL statement */
42936   int nMem,                      /* Number of memory cells to allocate */
42937   int nCursor,                   /* Number of cursors to allocate */
42938   int isExplain                  /* True if the EXPLAIN keywords is present */
42939 ){
42940   int n;
42941   sqlite3 *db = p->db;
42942
42943   assert( p!=0 );
42944   assert( p->magic==VDBE_MAGIC_INIT );
42945
42946   /* There should be at least one opcode.
42947   */
42948   assert( p->nOp>0 );
42949
42950   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. This
42951    * is because the call to resizeOpArray() below may shrink the
42952    * p->aOp[] array to save memory if called when in VDBE_MAGIC_RUN 
42953    * state.
42954    */
42955   p->magic = VDBE_MAGIC_RUN;
42956
42957   /* For each cursor required, also allocate a memory cell. Memory
42958   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
42959   ** the vdbe program. Instead they are used to allocate space for
42960   ** Cursor/BtCursor structures. The blob of memory associated with 
42961   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
42962   ** stores the blob of memory associated with cursor 1, etc.
42963   **
42964   ** See also: allocateCursor().
42965   */
42966   nMem += nCursor;
42967
42968   /*
42969   ** Allocation space for registers.
42970   */
42971   if( p->aMem==0 ){
42972     int nArg;       /* Maximum number of args passed to a user function. */
42973     resolveP2Values(p, &nArg);
42974     /*resizeOpArray(p, p->nOp);*/
42975     assert( nVar>=0 );
42976     if( isExplain && nMem<10 ){
42977       p->nMem = nMem = 10;
42978     }
42979     p->aMem = sqlite3DbMallocZero(db,
42980         nMem*sizeof(Mem)               /* aMem */
42981       + nVar*sizeof(Mem)               /* aVar */
42982       + nArg*sizeof(Mem*)              /* apArg */
42983       + nVar*sizeof(char*)             /* azVar */
42984       + nCursor*sizeof(Cursor*) + 1    /* apCsr */
42985     );
42986     if( !db->mallocFailed ){
42987       p->aMem--;             /* aMem[] goes from 1..nMem */
42988       p->nMem = nMem;        /*       not from 0..nMem-1 */
42989       p->aVar = &p->aMem[nMem+1];
42990       p->nVar = nVar;
42991       p->okVar = 0;
42992       p->apArg = (Mem**)&p->aVar[nVar];
42993       p->azVar = (char**)&p->apArg[nArg];
42994       p->apCsr = (Cursor**)&p->azVar[nVar];
42995       p->nCursor = nCursor;
42996       for(n=0; n<nVar; n++){
42997         p->aVar[n].flags = MEM_Null;
42998         p->aVar[n].db = db;
42999       }
43000       for(n=1; n<=nMem; n++){
43001         p->aMem[n].flags = MEM_Null;
43002         p->aMem[n].db = db;
43003       }
43004     }
43005   }
43006 #ifdef SQLITE_DEBUG
43007   for(n=1; n<p->nMem; n++){
43008     assert( p->aMem[n].db==db );
43009   }
43010 #endif
43011
43012   p->pc = -1;
43013   p->rc = SQLITE_OK;
43014   p->uniqueCnt = 0;
43015   p->errorAction = OE_Abort;
43016   p->explain |= isExplain;
43017   p->magic = VDBE_MAGIC_RUN;
43018   p->nChange = 0;
43019   p->cacheCtr = 1;
43020   p->minWriteFileFormat = 255;
43021   p->openedStatement = 0;
43022 #ifdef VDBE_PROFILE
43023   {
43024     int i;
43025     for(i=0; i<p->nOp; i++){
43026       p->aOp[i].cnt = 0;
43027       p->aOp[i].cycles = 0;
43028     }
43029   }
43030 #endif
43031 }
43032
43033 /*
43034 ** Close a VDBE cursor and release all the resources that cursor 
43035 ** happens to hold.
43036 */
43037 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, Cursor *pCx){
43038   if( pCx==0 ){
43039     return;
43040   }
43041   if( pCx->pBt ){
43042     sqlite3BtreeClose(pCx->pBt);
43043     /* The pCx->pCursor will be close automatically, if it exists, by
43044     ** the call above. */
43045   }else if( pCx->pCursor ){
43046     sqlite3BtreeCloseCursor(pCx->pCursor);
43047   }
43048 #ifndef SQLITE_OMIT_VIRTUALTABLE
43049   if( pCx->pVtabCursor ){
43050     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
43051     const sqlite3_module *pModule = pCx->pModule;
43052     p->inVtabMethod = 1;
43053     (void)sqlite3SafetyOff(p->db);
43054     pModule->xClose(pVtabCursor);
43055     (void)sqlite3SafetyOn(p->db);
43056     p->inVtabMethod = 0;
43057   }
43058 #endif
43059   if( !pCx->ephemPseudoTable ){
43060     sqlite3DbFree(p->db, pCx->pData);
43061   }
43062 }
43063
43064 /*
43065 ** Close all cursors except for VTab cursors that are currently
43066 ** in use.
43067 */
43068 static void closeAllCursorsExceptActiveVtabs(Vdbe *p){
43069   int i;
43070   if( p->apCsr==0 ) return;
43071   for(i=0; i<p->nCursor; i++){
43072     Cursor *pC = p->apCsr[i];
43073     if( pC && (!p->inVtabMethod || !pC->pVtabCursor) ){
43074       sqlite3VdbeFreeCursor(p, pC);
43075       p->apCsr[i] = 0;
43076     }
43077   }
43078 }
43079
43080 /*
43081 ** Clean up the VM after execution.
43082 **
43083 ** This routine will automatically close any cursors, lists, and/or
43084 ** sorters that were left open.  It also deletes the values of
43085 ** variables in the aVar[] array.
43086 */
43087 static void Cleanup(Vdbe *p){
43088   int i;
43089   sqlite3 *db = p->db;
43090   closeAllCursorsExceptActiveVtabs(p);
43091   for(i=1; i<=p->nMem; i++){
43092     MemSetTypeFlag(&p->aMem[i], MEM_Null);
43093   }
43094   releaseMemArray(&p->aMem[1], p->nMem);
43095   sqlite3VdbeFifoClear(&p->sFifo);
43096   if( p->contextStack ){
43097     for(i=0; i<p->contextStackTop; i++){
43098       sqlite3VdbeFifoClear(&p->contextStack[i].sFifo);
43099     }
43100     sqlite3DbFree(db, p->contextStack);
43101   }
43102   p->contextStack = 0;
43103   p->contextStackDepth = 0;
43104   p->contextStackTop = 0;
43105   sqlite3DbFree(db, p->zErrMsg);
43106   p->zErrMsg = 0;
43107   p->pResultSet = 0;
43108 }
43109
43110 /*
43111 ** Set the number of result columns that will be returned by this SQL
43112 ** statement. This is now set at compile time, rather than during
43113 ** execution of the vdbe program so that sqlite3_column_count() can
43114 ** be called on an SQL statement before sqlite3_step().
43115 */
43116 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
43117   Mem *pColName;
43118   int n;
43119   sqlite3 *db = p->db;
43120
43121   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
43122   sqlite3DbFree(db, p->aColName);
43123   n = nResColumn*COLNAME_N;
43124   p->nResColumn = nResColumn;
43125   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
43126   if( p->aColName==0 ) return;
43127   while( n-- > 0 ){
43128     pColName->flags = MEM_Null;
43129     pColName->db = p->db;
43130     pColName++;
43131   }
43132 }
43133
43134 /*
43135 ** Set the name of the idx'th column to be returned by the SQL statement.
43136 ** zName must be a pointer to a nul terminated string.
43137 **
43138 ** This call must be made after a call to sqlite3VdbeSetNumCols().
43139 **
43140 ** If N==P4_STATIC  it means that zName is a pointer to a constant static
43141 ** string and we can just copy the pointer. If it is P4_DYNAMIC, then 
43142 ** the string is freed using sqlite3DbFree(db, ) when the vdbe is finished with
43143 ** it. Otherwise, N bytes of zName are copied.
43144 */
43145 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe *p, int idx, int var, const char *zName, int N){
43146   int rc;
43147   Mem *pColName;
43148   assert( idx<p->nResColumn );
43149   assert( var<COLNAME_N );
43150   if( p->db->mallocFailed ) return SQLITE_NOMEM;
43151   assert( p->aColName!=0 );
43152   pColName = &(p->aColName[idx+var*p->nResColumn]);
43153   if( N==P4_DYNAMIC || N==P4_STATIC ){
43154     rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, SQLITE_STATIC);
43155   }else{
43156     rc = sqlite3VdbeMemSetStr(pColName, zName, N, SQLITE_UTF8,SQLITE_TRANSIENT);
43157   }
43158   if( rc==SQLITE_OK && N==P4_DYNAMIC ){
43159     pColName->flags &= (~MEM_Static);
43160     pColName->zMalloc = pColName->z;
43161   }
43162   return rc;
43163 }
43164
43165 /*
43166 ** A read or write transaction may or may not be active on database handle
43167 ** db. If a transaction is active, commit it. If there is a
43168 ** write-transaction spanning more than one database file, this routine
43169 ** takes care of the master journal trickery.
43170 */
43171 static int vdbeCommit(sqlite3 *db, Vdbe *p){
43172   int i;
43173   int nTrans = 0;  /* Number of databases with an active write-transaction */
43174   int rc = SQLITE_OK;
43175   int needXcommit = 0;
43176
43177   /* Before doing anything else, call the xSync() callback for any
43178   ** virtual module tables written in this transaction. This has to
43179   ** be done before determining whether a master journal file is 
43180   ** required, as an xSync() callback may add an attached database
43181   ** to the transaction.
43182   */
43183   rc = sqlite3VtabSync(db, &p->zErrMsg);
43184   if( rc!=SQLITE_OK ){
43185     return rc;
43186   }
43187
43188   /* This loop determines (a) if the commit hook should be invoked and
43189   ** (b) how many database files have open write transactions, not 
43190   ** including the temp database. (b) is important because if more than 
43191   ** one database file has an open write transaction, a master journal
43192   ** file is required for an atomic commit.
43193   */ 
43194   for(i=0; i<db->nDb; i++){ 
43195     Btree *pBt = db->aDb[i].pBt;
43196     if( sqlite3BtreeIsInTrans(pBt) ){
43197       needXcommit = 1;
43198       if( i!=1 ) nTrans++;
43199     }
43200   }
43201
43202   /* If there are any write-transactions at all, invoke the commit hook */
43203   if( needXcommit && db->xCommitCallback ){
43204     (void)sqlite3SafetyOff(db);
43205     rc = db->xCommitCallback(db->pCommitArg);
43206     (void)sqlite3SafetyOn(db);
43207     if( rc ){
43208       return SQLITE_CONSTRAINT;
43209     }
43210   }
43211
43212   /* The simple case - no more than one database file (not counting the
43213   ** TEMP database) has a transaction active.   There is no need for the
43214   ** master-journal.
43215   **
43216   ** If the return value of sqlite3BtreeGetFilename() is a zero length
43217   ** string, it means the main database is :memory: or a temp file.  In 
43218   ** that case we do not support atomic multi-file commits, so use the 
43219   ** simple case then too.
43220   */
43221   if( 0==strlen(sqlite3BtreeGetFilename(db->aDb[0].pBt)) || nTrans<=1 ){
43222     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
43223       Btree *pBt = db->aDb[i].pBt;
43224       if( pBt ){
43225         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
43226       }
43227     }
43228
43229     /* Do the commit only if all databases successfully complete phase 1. 
43230     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
43231     ** IO error while deleting or truncating a journal file. It is unlikely,
43232     ** but could happen. In this case abandon processing and return the error.
43233     */
43234     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
43235       Btree *pBt = db->aDb[i].pBt;
43236       if( pBt ){
43237         rc = sqlite3BtreeCommitPhaseTwo(pBt);
43238       }
43239     }
43240     if( rc==SQLITE_OK ){
43241       sqlite3VtabCommit(db);
43242     }
43243   }
43244
43245   /* The complex case - There is a multi-file write-transaction active.
43246   ** This requires a master journal file to ensure the transaction is
43247   ** committed atomicly.
43248   */
43249 #ifndef SQLITE_OMIT_DISKIO
43250   else{
43251     sqlite3_vfs *pVfs = db->pVfs;
43252     int needSync = 0;
43253     char *zMaster = 0;   /* File-name for the master journal */
43254     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
43255     sqlite3_file *pMaster = 0;
43256     i64 offset = 0;
43257     int res;
43258
43259     /* Select a master journal file name */
43260     do {
43261       u32 random;
43262       sqlite3DbFree(db, zMaster);
43263       sqlite3_randomness(sizeof(random), &random);
43264       zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, random&0x7fffffff);
43265       if( !zMaster ){
43266         return SQLITE_NOMEM;
43267       }
43268       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
43269     }while( rc==SQLITE_OK && res );
43270     if( rc==SQLITE_OK ){
43271       /* Open the master journal. */
43272       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
43273           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
43274           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
43275       );
43276     }
43277     if( rc!=SQLITE_OK ){
43278       sqlite3DbFree(db, zMaster);
43279       return rc;
43280     }
43281  
43282     /* Write the name of each database file in the transaction into the new
43283     ** master journal file. If an error occurs at this point close
43284     ** and delete the master journal file. All the individual journal files
43285     ** still have 'null' as the master journal pointer, so they will roll
43286     ** back independently if a failure occurs.
43287     */
43288     for(i=0; i<db->nDb; i++){
43289       Btree *pBt = db->aDb[i].pBt;
43290       if( i==1 ) continue;   /* Ignore the TEMP database */
43291       if( sqlite3BtreeIsInTrans(pBt) ){
43292         char const *zFile = sqlite3BtreeGetJournalname(pBt);
43293         if( zFile[0]==0 ) continue;  /* Ignore :memory: databases */
43294         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
43295           needSync = 1;
43296         }
43297         rc = sqlite3OsWrite(pMaster, zFile, strlen(zFile)+1, offset);
43298         offset += strlen(zFile)+1;
43299         if( rc!=SQLITE_OK ){
43300           sqlite3OsCloseFree(pMaster);
43301           sqlite3OsDelete(pVfs, zMaster, 0);
43302           sqlite3DbFree(db, zMaster);
43303           return rc;
43304         }
43305       }
43306     }
43307
43308     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
43309     ** flag is set this is not required.
43310     */
43311     zMainFile = sqlite3BtreeGetDirname(db->aDb[0].pBt);
43312     if( (needSync 
43313      && (0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL))
43314      && (rc=sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))!=SQLITE_OK) ){
43315       sqlite3OsCloseFree(pMaster);
43316       sqlite3OsDelete(pVfs, zMaster, 0);
43317       sqlite3DbFree(db, zMaster);
43318       return rc;
43319     }
43320
43321     /* Sync all the db files involved in the transaction. The same call
43322     ** sets the master journal pointer in each individual journal. If
43323     ** an error occurs here, do not delete the master journal file.
43324     **
43325     ** If the error occurs during the first call to
43326     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
43327     ** master journal file will be orphaned. But we cannot delete it,
43328     ** in case the master journal file name was written into the journal
43329     ** file before the failure occured.
43330     */
43331     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
43332       Btree *pBt = db->aDb[i].pBt;
43333       if( pBt ){
43334         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
43335       }
43336     }
43337     sqlite3OsCloseFree(pMaster);
43338     if( rc!=SQLITE_OK ){
43339       sqlite3DbFree(db, zMaster);
43340       return rc;
43341     }
43342
43343     /* Delete the master journal file. This commits the transaction. After
43344     ** doing this the directory is synced again before any individual
43345     ** transaction files are deleted.
43346     */
43347     rc = sqlite3OsDelete(pVfs, zMaster, 1);
43348     sqlite3DbFree(db, zMaster);
43349     zMaster = 0;
43350     if( rc ){
43351       return rc;
43352     }
43353
43354     /* All files and directories have already been synced, so the following
43355     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
43356     ** deleting or truncating journals. If something goes wrong while
43357     ** this is happening we don't really care. The integrity of the
43358     ** transaction is already guaranteed, but some stray 'cold' journals
43359     ** may be lying around. Returning an error code won't help matters.
43360     */
43361     disable_simulated_io_errors();
43362     sqlite3BeginBenignMalloc();
43363     for(i=0; i<db->nDb; i++){ 
43364       Btree *pBt = db->aDb[i].pBt;
43365       if( pBt ){
43366         sqlite3BtreeCommitPhaseTwo(pBt);
43367       }
43368     }
43369     sqlite3EndBenignMalloc();
43370     enable_simulated_io_errors();
43371
43372     sqlite3VtabCommit(db);
43373   }
43374 #endif
43375
43376   return rc;
43377 }
43378
43379 /* 
43380 ** This routine checks that the sqlite3.activeVdbeCnt count variable
43381 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
43382 ** currently active. An assertion fails if the two counts do not match.
43383 ** This is an internal self-check only - it is not an essential processing
43384 ** step.
43385 **
43386 ** This is a no-op if NDEBUG is defined.
43387 */
43388 #ifndef NDEBUG
43389 static void checkActiveVdbeCnt(sqlite3 *db){
43390   Vdbe *p;
43391   int cnt = 0;
43392   p = db->pVdbe;
43393   while( p ){
43394     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
43395       cnt++;
43396     }
43397     p = p->pNext;
43398   }
43399   assert( cnt==db->activeVdbeCnt );
43400 }
43401 #else
43402 #define checkActiveVdbeCnt(x)
43403 #endif
43404
43405 /*
43406 ** For every Btree that in database connection db which 
43407 ** has been modified, "trip" or invalidate each cursor in
43408 ** that Btree might have been modified so that the cursor
43409 ** can never be used again.  This happens when a rollback
43410 *** occurs.  We have to trip all the other cursors, even
43411 ** cursor from other VMs in different database connections,
43412 ** so that none of them try to use the data at which they
43413 ** were pointing and which now may have been changed due
43414 ** to the rollback.
43415 **
43416 ** Remember that a rollback can delete tables complete and
43417 ** reorder rootpages.  So it is not sufficient just to save
43418 ** the state of the cursor.  We have to invalidate the cursor
43419 ** so that it is never used again.
43420 */
43421 static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
43422   int i;
43423   for(i=0; i<db->nDb; i++){
43424     Btree *p = db->aDb[i].pBt;
43425     if( p && sqlite3BtreeIsInTrans(p) ){
43426       sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
43427     }
43428   }
43429 }
43430
43431 /*
43432 ** This routine is called the when a VDBE tries to halt.  If the VDBE
43433 ** has made changes and is in autocommit mode, then commit those
43434 ** changes.  If a rollback is needed, then do the rollback.
43435 **
43436 ** This routine is the only way to move the state of a VM from
43437 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
43438 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
43439 **
43440 ** Return an error code.  If the commit could not complete because of
43441 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
43442 ** means the close did not happen and needs to be repeated.
43443 */
43444 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
43445   sqlite3 *db = p->db;
43446   int i;
43447   int (*xFunc)(Btree *pBt) = 0;  /* Function to call on each btree backend */
43448   int isSpecialError;            /* Set to true if SQLITE_NOMEM or IOERR */
43449
43450   /* This function contains the logic that determines if a statement or
43451   ** transaction will be committed or rolled back as a result of the
43452   ** execution of this virtual machine. 
43453   **
43454   ** If any of the following errors occur:
43455   **
43456   **     SQLITE_NOMEM
43457   **     SQLITE_IOERR
43458   **     SQLITE_FULL
43459   **     SQLITE_INTERRUPT
43460   **
43461   ** Then the internal cache might have been left in an inconsistent
43462   ** state.  We need to rollback the statement transaction, if there is
43463   ** one, or the complete transaction if there is no statement transaction.
43464   */
43465
43466   if( p->db->mallocFailed ){
43467     p->rc = SQLITE_NOMEM;
43468   }
43469   closeAllCursorsExceptActiveVtabs(p);
43470   if( p->magic!=VDBE_MAGIC_RUN ){
43471     return SQLITE_OK;
43472   }
43473   checkActiveVdbeCnt(db);
43474
43475   /* No commit or rollback needed if the program never started */
43476   if( p->pc>=0 ){
43477     int mrc;   /* Primary error code from p->rc */
43478
43479     /* Lock all btrees used by the statement */
43480     sqlite3BtreeMutexArrayEnter(&p->aMutex);
43481
43482     /* Check for one of the special errors */
43483     mrc = p->rc & 0xff;
43484     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
43485                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
43486     if( isSpecialError ){
43487       /* This loop does static analysis of the query to see which of the
43488       ** following three categories it falls into:
43489       **
43490       **     Read-only
43491       **     Query with statement journal
43492       **     Query without statement journal
43493       **
43494       ** We could do something more elegant than this static analysis (i.e.
43495       ** store the type of query as part of the compliation phase), but 
43496       ** handling malloc() or IO failure is a fairly obscure edge case so 
43497       ** this is probably easier. Todo: Might be an opportunity to reduce 
43498       ** code size a very small amount though...
43499       */
43500       int notReadOnly = 0;
43501       int isStatement = 0;
43502       assert(p->aOp || p->nOp==0);
43503       for(i=0; i<p->nOp; i++){ 
43504         switch( p->aOp[i].opcode ){
43505           case OP_Transaction:
43506             notReadOnly |= p->aOp[i].p2;
43507             break;
43508           case OP_Statement:
43509             isStatement = 1;
43510             break;
43511         }
43512       }
43513
43514    
43515       /* If the query was read-only, we need do no rollback at all. Otherwise,
43516       ** proceed with the special handling.
43517       */
43518       if( notReadOnly || mrc!=SQLITE_INTERRUPT ){
43519         if( p->rc==SQLITE_IOERR_BLOCKED && isStatement ){
43520           xFunc = sqlite3BtreeRollbackStmt;
43521           p->rc = SQLITE_BUSY;
43522         } else if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && isStatement ){
43523           xFunc = sqlite3BtreeRollbackStmt;
43524         }else{
43525           /* We are forced to roll back the active transaction. Before doing
43526           ** so, abort any other statements this handle currently has active.
43527           */
43528           invalidateCursorsOnModifiedBtrees(db);
43529           sqlite3RollbackAll(db);
43530           db->autoCommit = 1;
43531         }
43532       }
43533     }
43534   
43535     /* If the auto-commit flag is set and this is the only active vdbe, then
43536     ** we do either a commit or rollback of the current transaction. 
43537     **
43538     ** Note: This block also runs if one of the special errors handled 
43539     ** above has occured. 
43540     */
43541     if( db->autoCommit && db->activeVdbeCnt==1 ){
43542       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
43543         /* The auto-commit flag is true, and the vdbe program was 
43544         ** successful or hit an 'OR FAIL' constraint. This means a commit 
43545         ** is required.
43546         */
43547         int rc = vdbeCommit(db, p);
43548         if( rc==SQLITE_BUSY ){
43549           sqlite3BtreeMutexArrayLeave(&p->aMutex);
43550           return SQLITE_BUSY;
43551         }else if( rc!=SQLITE_OK ){
43552           p->rc = rc;
43553           sqlite3RollbackAll(db);
43554         }else{
43555           sqlite3CommitInternalChanges(db);
43556         }
43557       }else{
43558         sqlite3RollbackAll(db);
43559       }
43560     }else if( !xFunc ){
43561       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
43562         if( p->openedStatement ){
43563           xFunc = sqlite3BtreeCommitStmt;
43564         } 
43565       }else if( p->errorAction==OE_Abort ){
43566         xFunc = sqlite3BtreeRollbackStmt;
43567       }else{
43568         invalidateCursorsOnModifiedBtrees(db);
43569         sqlite3RollbackAll(db);
43570         db->autoCommit = 1;
43571       }
43572     }
43573   
43574     /* If xFunc is not NULL, then it is one of sqlite3BtreeRollbackStmt or
43575     ** sqlite3BtreeCommitStmt. Call it once on each backend. If an error occurs
43576     ** and the return code is still SQLITE_OK, set the return code to the new
43577     ** error value.
43578     */
43579     assert(!xFunc ||
43580       xFunc==sqlite3BtreeCommitStmt ||
43581       xFunc==sqlite3BtreeRollbackStmt
43582     );
43583     for(i=0; xFunc && i<db->nDb; i++){ 
43584       int rc;
43585       Btree *pBt = db->aDb[i].pBt;
43586       if( pBt ){
43587         rc = xFunc(pBt);
43588         if( rc && (p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT) ){
43589           p->rc = rc;
43590           sqlite3DbFree(db, p->zErrMsg);
43591           p->zErrMsg = 0;
43592         }
43593       }
43594     }
43595   
43596     /* If this was an INSERT, UPDATE or DELETE and the statement was committed, 
43597     ** set the change counter. 
43598     */
43599     if( p->changeCntOn && p->pc>=0 ){
43600       if( !xFunc || xFunc==sqlite3BtreeCommitStmt ){
43601         sqlite3VdbeSetChanges(db, p->nChange);
43602       }else{
43603         sqlite3VdbeSetChanges(db, 0);
43604       }
43605       p->nChange = 0;
43606     }
43607   
43608     /* Rollback or commit any schema changes that occurred. */
43609     if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
43610       sqlite3ResetInternalSchema(db, 0);
43611       db->flags = (db->flags | SQLITE_InternChanges);
43612     }
43613
43614     /* Release the locks */
43615     sqlite3BtreeMutexArrayLeave(&p->aMutex);
43616   }
43617
43618   /* We have successfully halted and closed the VM.  Record this fact. */
43619   if( p->pc>=0 ){
43620     db->activeVdbeCnt--;
43621   }
43622   p->magic = VDBE_MAGIC_HALT;
43623   checkActiveVdbeCnt(db);
43624   if( p->db->mallocFailed ){
43625     p->rc = SQLITE_NOMEM;
43626   }
43627
43628   return SQLITE_OK;
43629 }
43630
43631
43632 /*
43633 ** Each VDBE holds the result of the most recent sqlite3_step() call
43634 ** in p->rc.  This routine sets that result back to SQLITE_OK.
43635 */
43636 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
43637   p->rc = SQLITE_OK;
43638 }
43639
43640 /*
43641 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
43642 ** Write any error messages into *pzErrMsg.  Return the result code.
43643 **
43644 ** After this routine is run, the VDBE should be ready to be executed
43645 ** again.
43646 **
43647 ** To look at it another way, this routine resets the state of the
43648 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
43649 ** VDBE_MAGIC_INIT.
43650 */
43651 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
43652   sqlite3 *db;
43653   db = p->db;
43654
43655   /* If the VM did not run to completion or if it encountered an
43656   ** error, then it might not have been halted properly.  So halt
43657   ** it now.
43658   */
43659   (void)sqlite3SafetyOn(db);
43660   sqlite3VdbeHalt(p);
43661   (void)sqlite3SafetyOff(db);
43662
43663   /* If the VDBE has be run even partially, then transfer the error code
43664   ** and error message from the VDBE into the main database structure.  But
43665   ** if the VDBE has just been set to run but has not actually executed any
43666   ** instructions yet, leave the main database error information unchanged.
43667   */
43668   if( p->pc>=0 ){
43669     if( p->zErrMsg ){
43670       sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
43671       db->errCode = p->rc;
43672       sqlite3DbFree(db, p->zErrMsg);
43673       p->zErrMsg = 0;
43674     }else if( p->rc ){
43675       sqlite3Error(db, p->rc, 0);
43676     }else{
43677       sqlite3Error(db, SQLITE_OK, 0);
43678     }
43679   }else if( p->rc && p->expired ){
43680     /* The expired flag was set on the VDBE before the first call
43681     ** to sqlite3_step(). For consistency (since sqlite3_step() was
43682     ** called), set the database error in this case as well.
43683     */
43684     sqlite3Error(db, p->rc, 0);
43685     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
43686     sqlite3DbFree(db, p->zErrMsg);
43687     p->zErrMsg = 0;
43688   }
43689
43690   /* Reclaim all memory used by the VDBE
43691   */
43692   Cleanup(p);
43693
43694   /* Save profiling information from this VDBE run.
43695   */
43696 #ifdef VDBE_PROFILE
43697   {
43698     FILE *out = fopen("vdbe_profile.out", "a");
43699     if( out ){
43700       int i;
43701       fprintf(out, "---- ");
43702       for(i=0; i<p->nOp; i++){
43703         fprintf(out, "%02x", p->aOp[i].opcode);
43704       }
43705       fprintf(out, "\n");
43706       for(i=0; i<p->nOp; i++){
43707         fprintf(out, "%6d %10lld %8lld ",
43708            p->aOp[i].cnt,
43709            p->aOp[i].cycles,
43710            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
43711         );
43712         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
43713       }
43714       fclose(out);
43715     }
43716   }
43717 #endif
43718   p->magic = VDBE_MAGIC_INIT;
43719   return p->rc & db->errMask;
43720 }
43721  
43722 /*
43723 ** Clean up and delete a VDBE after execution.  Return an integer which is
43724 ** the result code.  Write any error message text into *pzErrMsg.
43725 */
43726 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
43727   int rc = SQLITE_OK;
43728   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
43729     rc = sqlite3VdbeReset(p);
43730     assert( (rc & p->db->errMask)==rc );
43731   }else if( p->magic!=VDBE_MAGIC_INIT ){
43732     return SQLITE_MISUSE;
43733   }
43734   sqlite3VdbeDelete(p);
43735   return rc;
43736 }
43737
43738 /*
43739 ** Call the destructor for each auxdata entry in pVdbeFunc for which
43740 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
43741 ** are always destroyed.  To destroy all auxdata entries, call this
43742 ** routine with mask==0.
43743 */
43744 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
43745   int i;
43746   for(i=0; i<pVdbeFunc->nAux; i++){
43747     struct AuxData *pAux = &pVdbeFunc->apAux[i];
43748     if( (i>31 || !(mask&(1<<i))) && pAux->pAux ){
43749       if( pAux->xDelete ){
43750         pAux->xDelete(pAux->pAux);
43751       }
43752       pAux->pAux = 0;
43753     }
43754   }
43755 }
43756
43757 /*
43758 ** Delete an entire VDBE.
43759 */
43760 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
43761   int i;
43762   sqlite3 *db;
43763
43764   if( p==0 ) return;
43765   db = p->db;
43766   if( p->pPrev ){
43767     p->pPrev->pNext = p->pNext;
43768   }else{
43769     assert( db->pVdbe==p );
43770     db->pVdbe = p->pNext;
43771   }
43772   if( p->pNext ){
43773     p->pNext->pPrev = p->pPrev;
43774   }
43775   if( p->aOp ){
43776     Op *pOp = p->aOp;
43777     for(i=0; i<p->nOp; i++, pOp++){
43778       freeP4(db, pOp->p4type, pOp->p4.p);
43779 #ifdef SQLITE_DEBUG
43780       sqlite3DbFree(db, pOp->zComment);
43781 #endif     
43782     }
43783     sqlite3DbFree(db, p->aOp);
43784   }
43785   releaseMemArray(p->aVar, p->nVar);
43786   sqlite3DbFree(db, p->aLabel);
43787   if( p->aMem ){
43788     sqlite3DbFree(db, &p->aMem[1]);
43789   }
43790   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
43791   sqlite3DbFree(db, p->aColName);
43792   sqlite3DbFree(db, p->zSql);
43793   p->magic = VDBE_MAGIC_DEAD;
43794   sqlite3DbFree(db, p);
43795 }
43796
43797 /*
43798 ** If a MoveTo operation is pending on the given cursor, then do that
43799 ** MoveTo now.  Return an error code.  If no MoveTo is pending, this
43800 ** routine does nothing and returns SQLITE_OK.
43801 */
43802 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(Cursor *p){
43803   if( p->deferredMoveto ){
43804     int res, rc;
43805 #ifdef SQLITE_TEST
43806     extern int sqlite3_search_count;
43807 #endif
43808     assert( p->isTable );
43809     rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
43810     if( rc ) return rc;
43811     p->lastRowid = keyToInt(p->movetoTarget);
43812     p->rowidIsValid = res==0;
43813     if( res<0 ){
43814       rc = sqlite3BtreeNext(p->pCursor, &res);
43815       if( rc ) return rc;
43816     }
43817 #ifdef SQLITE_TEST
43818     sqlite3_search_count++;
43819 #endif
43820     p->deferredMoveto = 0;
43821     p->cacheStatus = CACHE_STALE;
43822   }else if( p->pCursor ){
43823     int hasMoved;
43824     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
43825     if( rc ) return rc;
43826     if( hasMoved ){
43827       p->cacheStatus = CACHE_STALE;
43828       p->nullRow = 1;
43829     }
43830   }
43831   return SQLITE_OK;
43832 }
43833
43834 /*
43835 ** The following functions:
43836 **
43837 ** sqlite3VdbeSerialType()
43838 ** sqlite3VdbeSerialTypeLen()
43839 ** sqlite3VdbeSerialLen()
43840 ** sqlite3VdbeSerialPut()
43841 ** sqlite3VdbeSerialGet()
43842 **
43843 ** encapsulate the code that serializes values for storage in SQLite
43844 ** data and index records. Each serialized value consists of a
43845 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
43846 ** integer, stored as a varint.
43847 **
43848 ** In an SQLite index record, the serial type is stored directly before
43849 ** the blob of data that it corresponds to. In a table record, all serial
43850 ** types are stored at the start of the record, and the blobs of data at
43851 ** the end. Hence these functions allow the caller to handle the
43852 ** serial-type and data blob seperately.
43853 **
43854 ** The following table describes the various storage classes for data:
43855 **
43856 **   serial type        bytes of data      type
43857 **   --------------     ---------------    ---------------
43858 **      0                     0            NULL
43859 **      1                     1            signed integer
43860 **      2                     2            signed integer
43861 **      3                     3            signed integer
43862 **      4                     4            signed integer
43863 **      5                     6            signed integer
43864 **      6                     8            signed integer
43865 **      7                     8            IEEE float
43866 **      8                     0            Integer constant 0
43867 **      9                     0            Integer constant 1
43868 **     10,11                               reserved for expansion
43869 **    N>=12 and even       (N-12)/2        BLOB
43870 **    N>=13 and odd        (N-13)/2        text
43871 **
43872 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
43873 ** of SQLite will not understand those serial types.
43874 */
43875
43876 /*
43877 ** Return the serial-type for the value stored in pMem.
43878 */
43879 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
43880   int flags = pMem->flags;
43881   int n;
43882
43883   if( flags&MEM_Null ){
43884     return 0;
43885   }
43886   if( flags&MEM_Int ){
43887     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
43888 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
43889     i64 i = pMem->u.i;
43890     u64 u;
43891     if( file_format>=4 && (i&1)==i ){
43892       return 8+i;
43893     }
43894     u = i<0 ? -i : i;
43895     if( u<=127 ) return 1;
43896     if( u<=32767 ) return 2;
43897     if( u<=8388607 ) return 3;
43898     if( u<=2147483647 ) return 4;
43899     if( u<=MAX_6BYTE ) return 5;
43900     return 6;
43901   }
43902   if( flags&MEM_Real ){
43903     return 7;
43904   }
43905   assert( flags&(MEM_Str|MEM_Blob) );
43906   n = pMem->n;
43907   if( flags & MEM_Zero ){
43908     n += pMem->u.i;
43909   }
43910   assert( n>=0 );
43911   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
43912 }
43913
43914 /*
43915 ** Return the length of the data corresponding to the supplied serial-type.
43916 */
43917 SQLITE_PRIVATE int sqlite3VdbeSerialTypeLen(u32 serial_type){
43918   if( serial_type>=12 ){
43919     return (serial_type-12)/2;
43920   }else{
43921     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
43922     return aSize[serial_type];
43923   }
43924 }
43925
43926 /*
43927 ** If we are on an architecture with mixed-endian floating 
43928 ** points (ex: ARM7) then swap the lower 4 bytes with the 
43929 ** upper 4 bytes.  Return the result.
43930 **
43931 ** For most architectures, this is a no-op.
43932 **
43933 ** (later):  It is reported to me that the mixed-endian problem
43934 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
43935 ** that early versions of GCC stored the two words of a 64-bit
43936 ** float in the wrong order.  And that error has been propagated
43937 ** ever since.  The blame is not necessarily with GCC, though.
43938 ** GCC might have just copying the problem from a prior compiler.
43939 ** I am also told that newer versions of GCC that follow a different
43940 ** ABI get the byte order right.
43941 **
43942 ** Developers using SQLite on an ARM7 should compile and run their
43943 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
43944 ** enabled, some asserts below will ensure that the byte order of
43945 ** floating point values is correct.
43946 **
43947 ** (2007-08-30)  Frank van Vugt has studied this problem closely
43948 ** and has send his findings to the SQLite developers.  Frank
43949 ** writes that some Linux kernels offer floating point hardware
43950 ** emulation that uses only 32-bit mantissas instead of a full 
43951 ** 48-bits as required by the IEEE standard.  (This is the
43952 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
43953 ** byte swapping becomes very complicated.  To avoid problems,
43954 ** the necessary byte swapping is carried out using a 64-bit integer
43955 ** rather than a 64-bit float.  Frank assures us that the code here
43956 ** works for him.  We, the developers, have no way to independently
43957 ** verify this, but Frank seems to know what he is talking about
43958 ** so we trust him.
43959 */
43960 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
43961 static u64 floatSwap(u64 in){
43962   union {
43963     u64 r;
43964     u32 i[2];
43965   } u;
43966   u32 t;
43967
43968   u.r = in;
43969   t = u.i[0];
43970   u.i[0] = u.i[1];
43971   u.i[1] = t;
43972   return u.r;
43973 }
43974 # define swapMixedEndianFloat(X)  X = floatSwap(X)
43975 #else
43976 # define swapMixedEndianFloat(X)
43977 #endif
43978
43979 /*
43980 ** Write the serialized data blob for the value stored in pMem into 
43981 ** buf. It is assumed that the caller has allocated sufficient space.
43982 ** Return the number of bytes written.
43983 **
43984 ** nBuf is the amount of space left in buf[].  nBuf must always be
43985 ** large enough to hold the entire field.  Except, if the field is
43986 ** a blob with a zero-filled tail, then buf[] might be just the right
43987 ** size to hold everything except for the zero-filled tail.  If buf[]
43988 ** is only big enough to hold the non-zero prefix, then only write that
43989 ** prefix into buf[].  But if buf[] is large enough to hold both the
43990 ** prefix and the tail then write the prefix and set the tail to all
43991 ** zeros.
43992 **
43993 ** Return the number of bytes actually written into buf[].  The number
43994 ** of bytes in the zero-filled tail is included in the return value only
43995 ** if those bytes were zeroed in buf[].
43996 */ 
43997 SQLITE_PRIVATE int sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
43998   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
43999   int len;
44000
44001   /* Integer and Real */
44002   if( serial_type<=7 && serial_type>0 ){
44003     u64 v;
44004     int i;
44005     if( serial_type==7 ){
44006       assert( sizeof(v)==sizeof(pMem->r) );
44007       memcpy(&v, &pMem->r, sizeof(v));
44008       swapMixedEndianFloat(v);
44009     }else{
44010       v = pMem->u.i;
44011     }
44012     len = i = sqlite3VdbeSerialTypeLen(serial_type);
44013     assert( len<=nBuf );
44014     while( i-- ){
44015       buf[i] = (v&0xFF);
44016       v >>= 8;
44017     }
44018     return len;
44019   }
44020
44021   /* String or blob */
44022   if( serial_type>=12 ){
44023     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.i:0)
44024              == sqlite3VdbeSerialTypeLen(serial_type) );
44025     assert( pMem->n<=nBuf );
44026     len = pMem->n;
44027     memcpy(buf, pMem->z, len);
44028     if( pMem->flags & MEM_Zero ){
44029       len += pMem->u.i;
44030       if( len>nBuf ){
44031         len = nBuf;
44032       }
44033       memset(&buf[pMem->n], 0, len-pMem->n);
44034     }
44035     return len;
44036   }
44037
44038   /* NULL or constants 0 or 1 */
44039   return 0;
44040 }
44041
44042 /*
44043 ** Deserialize the data blob pointed to by buf as serial type serial_type
44044 ** and store the result in pMem.  Return the number of bytes read.
44045 */ 
44046 SQLITE_PRIVATE int sqlite3VdbeSerialGet(
44047   const unsigned char *buf,     /* Buffer to deserialize from */
44048   u32 serial_type,              /* Serial type to deserialize */
44049   Mem *pMem                     /* Memory cell to write value into */
44050 ){
44051   switch( serial_type ){
44052     case 10:   /* Reserved for future use */
44053     case 11:   /* Reserved for future use */
44054     case 0: {  /* NULL */
44055       pMem->flags = MEM_Null;
44056       break;
44057     }
44058     case 1: { /* 1-byte signed integer */
44059       pMem->u.i = (signed char)buf[0];
44060       pMem->flags = MEM_Int;
44061       return 1;
44062     }
44063     case 2: { /* 2-byte signed integer */
44064       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
44065       pMem->flags = MEM_Int;
44066       return 2;
44067     }
44068     case 3: { /* 3-byte signed integer */
44069       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
44070       pMem->flags = MEM_Int;
44071       return 3;
44072     }
44073     case 4: { /* 4-byte signed integer */
44074       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
44075       pMem->flags = MEM_Int;
44076       return 4;
44077     }
44078     case 5: { /* 6-byte signed integer */
44079       u64 x = (((signed char)buf[0])<<8) | buf[1];
44080       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
44081       x = (x<<32) | y;
44082       pMem->u.i = *(i64*)&x;
44083       pMem->flags = MEM_Int;
44084       return 6;
44085     }
44086     case 6:   /* 8-byte signed integer */
44087     case 7: { /* IEEE floating point */
44088       u64 x;
44089       u32 y;
44090 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
44091       /* Verify that integers and floating point values use the same
44092       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
44093       ** defined that 64-bit floating point values really are mixed
44094       ** endian.
44095       */
44096       static const u64 t1 = ((u64)0x3ff00000)<<32;
44097       static const double r1 = 1.0;
44098       u64 t2 = t1;
44099       swapMixedEndianFloat(t2);
44100       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
44101 #endif
44102
44103       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
44104       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
44105       x = (x<<32) | y;
44106       if( serial_type==6 ){
44107         pMem->u.i = *(i64*)&x;
44108         pMem->flags = MEM_Int;
44109       }else{
44110         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
44111         swapMixedEndianFloat(x);
44112         memcpy(&pMem->r, &x, sizeof(x));
44113         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
44114       }
44115       return 8;
44116     }
44117     case 8:    /* Integer 0 */
44118     case 9: {  /* Integer 1 */
44119       pMem->u.i = serial_type-8;
44120       pMem->flags = MEM_Int;
44121       return 0;
44122     }
44123     default: {
44124       int len = (serial_type-12)/2;
44125       pMem->z = (char *)buf;
44126       pMem->n = len;
44127       pMem->xDel = 0;
44128       if( serial_type&0x01 ){
44129         pMem->flags = MEM_Str | MEM_Ephem;
44130       }else{
44131         pMem->flags = MEM_Blob | MEM_Ephem;
44132       }
44133       return len;
44134     }
44135   }
44136   return 0;
44137 }
44138
44139
44140 /*
44141 ** Given the nKey-byte encoding of a record in pKey[], parse the
44142 ** record into a UnpackedRecord structure.  Return a pointer to
44143 ** that structure.
44144 **
44145 ** The calling function might provide szSpace bytes of memory
44146 ** space at pSpace.  This space can be used to hold the returned
44147 ** VDbeParsedRecord structure if it is large enough.  If it is
44148 ** not big enough, space is obtained from sqlite3_malloc().
44149 **
44150 ** The returned structure should be closed by a call to
44151 ** sqlite3VdbeDeleteUnpackedRecord().
44152 */ 
44153 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(
44154   KeyInfo *pKeyInfo,     /* Information about the record format */
44155   int nKey,              /* Size of the binary record */
44156   const void *pKey,      /* The binary record */
44157   UnpackedRecord *pSpace,/* Space available to hold resulting object */
44158   int szSpace            /* Size of pSpace[] in bytes */
44159 ){
44160   const unsigned char *aKey = (const unsigned char *)pKey;
44161   UnpackedRecord *p;
44162   int nByte;
44163   int idx, d;
44164   u16 u;                 /* Unsigned loop counter */
44165   u32 szHdr;
44166   Mem *pMem;
44167   
44168   assert( sizeof(Mem)>sizeof(*p) );
44169   nByte = sizeof(Mem)*(pKeyInfo->nField+2);
44170   if( nByte>szSpace ){
44171     p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
44172     if( p==0 ) return 0;
44173     p->flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
44174   }else{
44175     p = pSpace;
44176     p->flags = UNPACKED_NEED_DESTROY;
44177   }
44178   p->pKeyInfo = pKeyInfo;
44179   p->nField = pKeyInfo->nField + 1;
44180   p->aMem = pMem = &((Mem*)p)[1];
44181   idx = getVarint32(aKey, szHdr);
44182   d = szHdr;
44183   u = 0;
44184   while( idx<szHdr && u<p->nField ){
44185     u32 serial_type;
44186
44187     idx += getVarint32( aKey+idx, serial_type);
44188     if( d>=nKey && sqlite3VdbeSerialTypeLen(serial_type)>0 ) break;
44189     pMem->enc = pKeyInfo->enc;
44190     pMem->db = pKeyInfo->db;
44191     pMem->flags = 0;
44192     pMem->zMalloc = 0;
44193     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
44194     pMem++;
44195     u++;
44196   }
44197   assert( u<=pKeyInfo->nField + 1 );
44198   p->nField = u;
44199   return (void*)p;
44200 }
44201
44202 /*
44203 ** This routine destroys a UnpackedRecord object
44204 */
44205 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
44206   if( p ){
44207     if( p->flags & UNPACKED_NEED_DESTROY ){
44208       int i;
44209       Mem *pMem;
44210       for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
44211         if( pMem->zMalloc ){
44212           sqlite3VdbeMemRelease(pMem);
44213         }
44214       }
44215     }
44216     if( p->flags & UNPACKED_NEED_FREE ){
44217       sqlite3DbFree(p->pKeyInfo->db, p);
44218     }
44219   }
44220 }
44221
44222 /*
44223 ** This function compares the two table rows or index records
44224 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
44225 ** or positive integer if key1 is less than, equal to or 
44226 ** greater than key2.  The {nKey1, pKey1} key must be a blob
44227 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
44228 ** key must be a parsed key such as obtained from
44229 ** sqlite3VdbeParseRecord.
44230 **
44231 ** Key1 and Key2 do not have to contain the same number of fields.
44232 ** The key with fewer fields is usually compares less than the 
44233 ** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
44234 ** and the common prefixes are equal, then key1 is less than key2.
44235 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
44236 ** equal, then the keys are considered to be equal and
44237 ** the parts beyond the common prefix are ignored.
44238 **
44239 ** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
44240 ** the header of pKey1 is ignored.  It is assumed that pKey1 is
44241 ** an index key, and thus ends with a rowid value.  The last byte
44242 ** of the header will therefore be the serial type of the rowid:
44243 ** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
44244 ** The serial type of the final rowid will always be a single byte.
44245 ** By ignoring this last byte of the header, we force the comparison
44246 ** to ignore the rowid at the end of key1.
44247 */
44248 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
44249   int nKey1, const void *pKey1, /* Left key */
44250   UnpackedRecord *pPKey2        /* Right key */
44251 ){
44252   u32 d1;            /* Offset into aKey[] of next data element */
44253   u32 idx1;          /* Offset into aKey[] of next header element */
44254   u32 szHdr1;        /* Number of bytes in header */
44255   int i = 0;
44256   int nField;
44257   int rc = 0;
44258   const unsigned char *aKey1 = (const unsigned char *)pKey1;
44259   KeyInfo *pKeyInfo;
44260   Mem mem1;
44261
44262   pKeyInfo = pPKey2->pKeyInfo;
44263   mem1.enc = pKeyInfo->enc;
44264   mem1.db = pKeyInfo->db;
44265   mem1.flags = 0;
44266   mem1.zMalloc = 0;
44267   
44268   idx1 = getVarint32(aKey1, szHdr1);
44269   d1 = szHdr1;
44270   if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
44271     szHdr1--;
44272   }
44273   nField = pKeyInfo->nField;
44274   while( idx1<szHdr1 && i<pPKey2->nField ){
44275     u32 serial_type1;
44276
44277     /* Read the serial types for the next element in each key. */
44278     idx1 += getVarint32( aKey1+idx1, serial_type1 );
44279     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
44280
44281     /* Extract the values to be compared.
44282     */
44283     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
44284
44285     /* Do the comparison
44286     */
44287     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
44288                            i<nField ? pKeyInfo->aColl[i] : 0);
44289     if( rc!=0 ){
44290       break;
44291     }
44292     i++;
44293   }
44294   if( mem1.zMalloc ) sqlite3VdbeMemRelease(&mem1);
44295
44296   if( rc==0 ){
44297     /* rc==0 here means that one of the keys ran out of fields and
44298     ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
44299     ** flag is set, then break the tie by treating key2 as larger.
44300     ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
44301     ** are considered to be equal.  Otherwise, the longer key is the 
44302     ** larger.  As it happens, the pPKey2 will always be the longer
44303     ** if there is a difference.
44304     */
44305     if( pPKey2->flags & UNPACKED_INCRKEY ){
44306       rc = -1;
44307     }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
44308       /* Leave rc==0 */
44309     }else if( idx1<szHdr1 ){
44310       rc = 1;
44311     }
44312   }else if( pKeyInfo->aSortOrder && i<pKeyInfo->nField
44313                && pKeyInfo->aSortOrder[i] ){
44314     rc = -rc;
44315   }
44316
44317   return rc;
44318 }
44319  
44320
44321 /*
44322 ** pCur points at an index entry created using the OP_MakeRecord opcode.
44323 ** Read the rowid (the last field in the record) and store it in *rowid.
44324 ** Return SQLITE_OK if everything works, or an error code otherwise.
44325 */
44326 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(BtCursor *pCur, i64 *rowid){
44327   i64 nCellKey = 0;
44328   int rc;
44329   u32 szHdr;        /* Size of the header */
44330   u32 typeRowid;    /* Serial type of the rowid */
44331   u32 lenRowid;     /* Size of the rowid */
44332   Mem m, v;
44333
44334   sqlite3BtreeKeySize(pCur, &nCellKey);
44335   if( nCellKey<=0 ){
44336     return SQLITE_CORRUPT_BKPT;
44337   }
44338   m.flags = 0;
44339   m.db = 0;
44340   m.zMalloc = 0;
44341   rc = sqlite3VdbeMemFromBtree(pCur, 0, nCellKey, 1, &m);
44342   if( rc ){
44343     return rc;
44344   }
44345   (void)getVarint32((u8*)m.z, szHdr);
44346   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
44347   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
44348   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
44349   *rowid = v.u.i;
44350   sqlite3VdbeMemRelease(&m);
44351   return SQLITE_OK;
44352 }
44353
44354 /*
44355 ** Compare the key of the index entry that cursor pC is point to against
44356 ** the key string in pKey (of length nKey).  Write into *pRes a number
44357 ** that is negative, zero, or positive if pC is less than, equal to,
44358 ** or greater than pKey.  Return SQLITE_OK on success.
44359 **
44360 ** pKey is either created without a rowid or is truncated so that it
44361 ** omits the rowid at the end.  The rowid at the end of the index entry
44362 ** is ignored as well.  Hence, this routine only compares the prefixes 
44363 ** of the keys prior to the final rowid, not the entire key.
44364 **
44365 ** pUnpacked may be an unpacked version of pKey,nKey.  If pUnpacked is
44366 ** supplied it is used in place of pKey,nKey.
44367 */
44368 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
44369   Cursor *pC,                 /* The cursor to compare against */
44370   UnpackedRecord *pUnpacked,  /* Unpacked version of pKey and nKey */
44371   int *res                    /* Write the comparison result here */
44372 ){
44373   i64 nCellKey = 0;
44374   int rc;
44375   BtCursor *pCur = pC->pCursor;
44376   Mem m;
44377
44378   sqlite3BtreeKeySize(pCur, &nCellKey);
44379   if( nCellKey<=0 ){
44380     *res = 0;
44381     return SQLITE_OK;
44382   }
44383   m.db = 0;
44384   m.flags = 0;
44385   m.zMalloc = 0;
44386   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, nCellKey, 1, &m);
44387   if( rc ){
44388     return rc;
44389   }
44390   assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
44391   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
44392   sqlite3VdbeMemRelease(&m);
44393   return SQLITE_OK;
44394 }
44395
44396 /*
44397 ** This routine sets the value to be returned by subsequent calls to
44398 ** sqlite3_changes() on the database handle 'db'. 
44399 */
44400 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
44401   assert( sqlite3_mutex_held(db->mutex) );
44402   db->nChange = nChange;
44403   db->nTotalChange += nChange;
44404 }
44405
44406 /*
44407 ** Set a flag in the vdbe to update the change counter when it is finalised
44408 ** or reset.
44409 */
44410 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
44411   v->changeCntOn = 1;
44412 }
44413
44414 /*
44415 ** Mark every prepared statement associated with a database connection
44416 ** as expired.
44417 **
44418 ** An expired statement means that recompilation of the statement is
44419 ** recommend.  Statements expire when things happen that make their
44420 ** programs obsolete.  Removing user-defined functions or collating
44421 ** sequences, or changing an authorization function are the types of
44422 ** things that make prepared statements obsolete.
44423 */
44424 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
44425   Vdbe *p;
44426   for(p = db->pVdbe; p; p=p->pNext){
44427     p->expired = 1;
44428   }
44429 }
44430
44431 /*
44432 ** Return the database associated with the Vdbe.
44433 */
44434 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
44435   return v->db;
44436 }
44437
44438 /************** End of vdbeaux.c *********************************************/
44439 /************** Begin file vdbeapi.c *****************************************/
44440 /*
44441 ** 2004 May 26
44442 **
44443 ** The author disclaims copyright to this source code.  In place of
44444 ** a legal notice, here is a blessing:
44445 **
44446 **    May you do good and not evil.
44447 **    May you find forgiveness for yourself and forgive others.
44448 **    May you share freely, never taking more than you give.
44449 **
44450 *************************************************************************
44451 **
44452 ** This file contains code use to implement APIs that are part of the
44453 ** VDBE.
44454 **
44455 ** $Id: vdbeapi.c,v 1.141 2008/09/04 12:03:43 shane Exp $
44456 */
44457
44458 #if 0 && defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
44459 /*
44460 ** The following structure contains pointers to the end points of a
44461 ** doubly-linked list of all compiled SQL statements that may be holding
44462 ** buffers eligible for release when the sqlite3_release_memory() interface is
44463 ** invoked. Access to this list is protected by the SQLITE_MUTEX_STATIC_LRU2
44464 ** mutex.
44465 **
44466 ** Statements are added to the end of this list when sqlite3_reset() is
44467 ** called. They are removed either when sqlite3_step() or sqlite3_finalize()
44468 ** is called. When statements are added to this list, the associated 
44469 ** register array (p->aMem[1..p->nMem]) may contain dynamic buffers that
44470 ** can be freed using sqlite3VdbeReleaseMemory().
44471 **
44472 ** When statements are added or removed from this list, the mutex
44473 ** associated with the Vdbe being added or removed (Vdbe.db->mutex) is
44474 ** already held. The LRU2 mutex is then obtained, blocking if necessary,
44475 ** the linked-list pointers manipulated and the LRU2 mutex relinquished.
44476 */
44477 struct StatementLruList {
44478   Vdbe *pFirst;
44479   Vdbe *pLast;
44480 };
44481 static struct StatementLruList sqlite3LruStatements;
44482
44483 /*
44484 ** Check that the list looks to be internally consistent. This is used
44485 ** as part of an assert() statement as follows:
44486 **
44487 **   assert( stmtLruCheck() );
44488 */
44489 #ifndef NDEBUG
44490 static int stmtLruCheck(){
44491   Vdbe *p;
44492   for(p=sqlite3LruStatements.pFirst; p; p=p->pLruNext){
44493     assert(p->pLruNext || p==sqlite3LruStatements.pLast);
44494     assert(!p->pLruNext || p->pLruNext->pLruPrev==p);
44495     assert(p->pLruPrev || p==sqlite3LruStatements.pFirst);
44496     assert(!p->pLruPrev || p->pLruPrev->pLruNext==p);
44497   }
44498   return 1;
44499 }
44500 #endif
44501
44502 /*
44503 ** Add vdbe p to the end of the statement lru list. It is assumed that
44504 ** p is not already part of the list when this is called. The lru list
44505 ** is protected by the SQLITE_MUTEX_STATIC_LRU mutex.
44506 */
44507 static void stmtLruAdd(Vdbe *p){
44508   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
44509
44510   if( p->pLruPrev || p->pLruNext || sqlite3LruStatements.pFirst==p ){
44511     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
44512     return;
44513   }
44514
44515   assert( stmtLruCheck() );
44516
44517   if( !sqlite3LruStatements.pFirst ){
44518     assert( !sqlite3LruStatements.pLast );
44519     sqlite3LruStatements.pFirst = p;
44520     sqlite3LruStatements.pLast = p;
44521   }else{
44522     assert( !sqlite3LruStatements.pLast->pLruNext );
44523     p->pLruPrev = sqlite3LruStatements.pLast;
44524     sqlite3LruStatements.pLast->pLruNext = p;
44525     sqlite3LruStatements.pLast = p;
44526   }
44527
44528   assert( stmtLruCheck() );
44529
44530   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
44531 }
44532
44533 /*
44534 ** Assuming the SQLITE_MUTEX_STATIC_LRU2 mutext is already held, remove
44535 ** statement p from the least-recently-used statement list. If the 
44536 ** statement is not currently part of the list, this call is a no-op.
44537 */
44538 static void stmtLruRemoveNomutex(Vdbe *p){
44539   if( p->pLruPrev || p->pLruNext || p==sqlite3LruStatements.pFirst ){
44540     assert( stmtLruCheck() );
44541     if( p->pLruNext ){
44542       p->pLruNext->pLruPrev = p->pLruPrev;
44543     }else{
44544       sqlite3LruStatements.pLast = p->pLruPrev;
44545     }
44546     if( p->pLruPrev ){
44547       p->pLruPrev->pLruNext = p->pLruNext;
44548     }else{
44549       sqlite3LruStatements.pFirst = p->pLruNext;
44550     }
44551     p->pLruNext = 0;
44552     p->pLruPrev = 0;
44553     assert( stmtLruCheck() );
44554   }
44555 }
44556
44557 /*
44558 ** Assuming the SQLITE_MUTEX_STATIC_LRU2 mutext is not held, remove
44559 ** statement p from the least-recently-used statement list. If the 
44560 ** statement is not currently part of the list, this call is a no-op.
44561 */
44562 static void stmtLruRemove(Vdbe *p){
44563   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
44564   stmtLruRemoveNomutex(p);
44565   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
44566 }
44567
44568 /*
44569 ** Try to release n bytes of memory by freeing buffers associated 
44570 ** with the memory registers of currently unused vdbes.
44571 */
44572 SQLITE_PRIVATE int sqlite3VdbeReleaseMemory(int n){
44573   Vdbe *p;
44574   Vdbe *pNext;
44575   int nFree = 0;
44576
44577   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
44578   for(p=sqlite3LruStatements.pFirst; p && nFree<n; p=pNext){
44579     pNext = p->pLruNext;
44580
44581     /* For each statement handle in the lru list, attempt to obtain the
44582     ** associated database mutex. If it cannot be obtained, continue
44583     ** to the next statement handle. It is not possible to block on
44584     ** the database mutex - that could cause deadlock.
44585     */
44586     if( SQLITE_OK==sqlite3_mutex_try(p->db->mutex) ){
44587       nFree += sqlite3VdbeReleaseBuffers(p);
44588       stmtLruRemoveNomutex(p);
44589       sqlite3_mutex_leave(p->db->mutex);
44590     }
44591   }
44592   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
44593
44594   return nFree;
44595 }
44596
44597 /*
44598 ** Call sqlite3Reprepare() on the statement. Remove it from the
44599 ** lru list before doing so, as Reprepare() will free all the
44600 ** memory register buffers anyway.
44601 */
44602 int vdbeReprepare(Vdbe *p){
44603   stmtLruRemove(p);
44604   return sqlite3Reprepare(p);
44605 }
44606
44607 #else       /* !SQLITE_ENABLE_MEMORY_MANAGEMENT */
44608   #define stmtLruRemove(x)
44609   #define stmtLruAdd(x)
44610   #define vdbeReprepare(x) sqlite3Reprepare(x)
44611 #endif
44612
44613
44614 /*
44615 ** Return TRUE (non-zero) of the statement supplied as an argument needs
44616 ** to be recompiled.  A statement needs to be recompiled whenever the
44617 ** execution environment changes in a way that would alter the program
44618 ** that sqlite3_prepare() generates.  For example, if new functions or
44619 ** collating sequences are registered or if an authorizer function is
44620 ** added or changed.
44621 */
44622 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
44623   Vdbe *p = (Vdbe*)pStmt;
44624   return p==0 || p->expired;
44625 }
44626
44627 /*
44628 ** The following routine destroys a virtual machine that is created by
44629 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
44630 ** success/failure code that describes the result of executing the virtual
44631 ** machine.
44632 **
44633 ** This routine sets the error code and string returned by
44634 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
44635 */
44636 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
44637   int rc;
44638   if( pStmt==0 ){
44639     rc = SQLITE_OK;
44640   }else{
44641     Vdbe *v = (Vdbe*)pStmt;
44642 #ifndef SQLITE_MUTEX_NOOP
44643     sqlite3_mutex *mutex = v->db->mutex;
44644 #endif
44645     sqlite3_mutex_enter(mutex);
44646     stmtLruRemove(v);
44647     rc = sqlite3VdbeFinalize(v);
44648     sqlite3_mutex_leave(mutex);
44649   }
44650   return rc;
44651 }
44652
44653 /*
44654 ** Terminate the current execution of an SQL statement and reset it
44655 ** back to its starting state so that it can be reused. A success code from
44656 ** the prior execution is returned.
44657 **
44658 ** This routine sets the error code and string returned by
44659 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
44660 */
44661 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
44662   int rc;
44663   if( pStmt==0 ){
44664     rc = SQLITE_OK;
44665   }else{
44666     Vdbe *v = (Vdbe*)pStmt;
44667     sqlite3_mutex_enter(v->db->mutex);
44668     rc = sqlite3VdbeReset(v);
44669     stmtLruAdd(v);
44670     sqlite3VdbeMakeReady(v, -1, 0, 0, 0);
44671     assert( (rc & (v->db->errMask))==rc );
44672     sqlite3_mutex_leave(v->db->mutex);
44673   }
44674   return rc;
44675 }
44676
44677 /*
44678 ** Set all the parameters in the compiled SQL statement to NULL.
44679 */
44680 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
44681   int i;
44682   int rc = SQLITE_OK;
44683   Vdbe *p = (Vdbe*)pStmt;
44684 #ifndef SQLITE_MUTEX_NOOP
44685   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
44686 #endif
44687   sqlite3_mutex_enter(mutex);
44688   for(i=0; i<p->nVar; i++){
44689     sqlite3VdbeMemRelease(&p->aVar[i]);
44690     p->aVar[i].flags = MEM_Null;
44691   }
44692   sqlite3_mutex_leave(mutex);
44693   return rc;
44694 }
44695
44696
44697 /**************************** sqlite3_value_  *******************************
44698 ** The following routines extract information from a Mem or sqlite3_value
44699 ** structure.
44700 */
44701 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
44702   Mem *p = (Mem*)pVal;
44703   if( p->flags & (MEM_Blob|MEM_Str) ){
44704     sqlite3VdbeMemExpandBlob(p);
44705     p->flags &= ~MEM_Str;
44706     p->flags |= MEM_Blob;
44707     return p->z;
44708   }else{
44709     return sqlite3_value_text(pVal);
44710   }
44711 }
44712 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
44713   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
44714 }
44715 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
44716   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
44717 }
44718 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
44719   return sqlite3VdbeRealValue((Mem*)pVal);
44720 }
44721 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
44722   return sqlite3VdbeIntValue((Mem*)pVal);
44723 }
44724 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
44725   return sqlite3VdbeIntValue((Mem*)pVal);
44726 }
44727 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
44728   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
44729 }
44730 #ifndef SQLITE_OMIT_UTF16
44731 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
44732   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
44733 }
44734 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
44735   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
44736 }
44737 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
44738   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
44739 }
44740 #endif /* SQLITE_OMIT_UTF16 */
44741 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
44742   return pVal->type;
44743 }
44744
44745 /**************************** sqlite3_result_  *******************************
44746 ** The following routines are used by user-defined functions to specify
44747 ** the function result.
44748 */
44749 SQLITE_API void sqlite3_result_blob(
44750   sqlite3_context *pCtx, 
44751   const void *z, 
44752   int n, 
44753   void (*xDel)(void *)
44754 ){
44755   assert( n>=0 );
44756   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44757   sqlite3VdbeMemSetStr(&pCtx->s, z, n, 0, xDel);
44758 }
44759 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
44760   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44761   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
44762 }
44763 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
44764   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44765   pCtx->isError = SQLITE_ERROR;
44766   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
44767 }
44768 #ifndef SQLITE_OMIT_UTF16
44769 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
44770   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44771   pCtx->isError = SQLITE_ERROR;
44772   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
44773 }
44774 #endif
44775 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
44776   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44777   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
44778 }
44779 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
44780   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44781   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
44782 }
44783 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
44784   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44785   sqlite3VdbeMemSetNull(&pCtx->s);
44786 }
44787 SQLITE_API void sqlite3_result_text(
44788   sqlite3_context *pCtx, 
44789   const char *z, 
44790   int n,
44791   void (*xDel)(void *)
44792 ){
44793   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44794   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, xDel);
44795 }
44796 #ifndef SQLITE_OMIT_UTF16
44797 SQLITE_API void sqlite3_result_text16(
44798   sqlite3_context *pCtx, 
44799   const void *z, 
44800   int n, 
44801   void (*xDel)(void *)
44802 ){
44803   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44804   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, xDel);
44805 }
44806 SQLITE_API void sqlite3_result_text16be(
44807   sqlite3_context *pCtx, 
44808   const void *z, 
44809   int n, 
44810   void (*xDel)(void *)
44811 ){
44812   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44813   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16BE, xDel);
44814 }
44815 SQLITE_API void sqlite3_result_text16le(
44816   sqlite3_context *pCtx, 
44817   const void *z, 
44818   int n, 
44819   void (*xDel)(void *)
44820 ){
44821   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44822   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16LE, xDel);
44823 }
44824 #endif /* SQLITE_OMIT_UTF16 */
44825 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
44826   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44827   sqlite3VdbeMemCopy(&pCtx->s, pValue);
44828 }
44829 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
44830   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44831   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
44832 }
44833 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
44834   pCtx->isError = errCode;
44835 }
44836
44837 /* Force an SQLITE_TOOBIG error. */
44838 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
44839   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44840   pCtx->isError = SQLITE_TOOBIG;
44841   sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1, 
44842                        SQLITE_UTF8, SQLITE_STATIC);
44843 }
44844
44845 /* An SQLITE_NOMEM error. */
44846 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
44847   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44848   sqlite3VdbeMemSetNull(&pCtx->s);
44849   pCtx->isError = SQLITE_NOMEM;
44850   pCtx->s.db->mallocFailed = 1;
44851 }
44852
44853 /*
44854 ** Execute the statement pStmt, either until a row of data is ready, the
44855 ** statement is completely executed or an error occurs.
44856 **
44857 ** This routine implements the bulk of the logic behind the sqlite_step()
44858 ** API.  The only thing omitted is the automatic recompile if a 
44859 ** schema change has occurred.  That detail is handled by the
44860 ** outer sqlite3_step() wrapper procedure.
44861 */
44862 static int sqlite3Step(Vdbe *p){
44863   sqlite3 *db;
44864   int rc;
44865
44866   assert(p);
44867   if( p->magic!=VDBE_MAGIC_RUN ){
44868     return SQLITE_MISUSE;
44869   }
44870
44871   /* Assert that malloc() has not failed */
44872   db = p->db;
44873   if( db->mallocFailed ){
44874     return SQLITE_NOMEM;
44875   }
44876
44877   if( p->pc<=0 && p->expired ){
44878     if( p->rc==SQLITE_OK ){
44879       p->rc = SQLITE_SCHEMA;
44880     }
44881     rc = SQLITE_ERROR;
44882     goto end_of_step;
44883   }
44884   if( sqlite3SafetyOn(db) ){
44885     p->rc = SQLITE_MISUSE;
44886     return SQLITE_MISUSE;
44887   }
44888   if( p->pc<0 ){
44889     /* If there are no other statements currently running, then
44890     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
44891     ** from interrupting a statement that has not yet started.
44892     */
44893     if( db->activeVdbeCnt==0 ){
44894       db->u1.isInterrupted = 0;
44895     }
44896
44897 #ifndef SQLITE_OMIT_TRACE
44898     if( db->xProfile && !db->init.busy ){
44899       double rNow;
44900       sqlite3OsCurrentTime(db->pVfs, &rNow);
44901       p->startTime = (rNow - (int)rNow)*3600.0*24.0*1000000000.0;
44902     }
44903 #endif
44904
44905     db->activeVdbeCnt++;
44906     p->pc = 0;
44907     stmtLruRemove(p);
44908   }
44909 #ifndef SQLITE_OMIT_EXPLAIN
44910   if( p->explain ){
44911     rc = sqlite3VdbeList(p);
44912   }else
44913 #endif /* SQLITE_OMIT_EXPLAIN */
44914   {
44915     rc = sqlite3VdbeExec(p);
44916   }
44917
44918   if( sqlite3SafetyOff(db) ){
44919     rc = SQLITE_MISUSE;
44920   }
44921
44922 #ifndef SQLITE_OMIT_TRACE
44923   /* Invoke the profile callback if there is one
44924   */
44925   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->nOp>0
44926            && p->aOp[0].opcode==OP_Trace && p->aOp[0].p4.z!=0 ){
44927     double rNow;
44928     u64 elapseTime;
44929
44930     sqlite3OsCurrentTime(db->pVfs, &rNow);
44931     elapseTime = (rNow - (int)rNow)*3600.0*24.0*1000000000.0 - p->startTime;
44932     db->xProfile(db->pProfileArg, p->aOp[0].p4.z, elapseTime);
44933   }
44934 #endif
44935
44936   db->errCode = rc;
44937   /*sqlite3Error(p->db, rc, 0);*/
44938   p->rc = sqlite3ApiExit(p->db, p->rc);
44939 end_of_step:
44940   assert( (rc&0xff)==rc );
44941   if( p->zSql && (rc&0xff)<SQLITE_ROW ){
44942     /* This behavior occurs if sqlite3_prepare_v2() was used to build
44943     ** the prepared statement.  Return error codes directly */
44944     p->db->errCode = p->rc;
44945     /* sqlite3Error(p->db, p->rc, 0); */
44946     return p->rc;
44947   }else{
44948     /* This is for legacy sqlite3_prepare() builds and when the code
44949     ** is SQLITE_ROW or SQLITE_DONE */
44950     return rc;
44951   }
44952 }
44953
44954 /*
44955 ** This is the top-level implementation of sqlite3_step().  Call
44956 ** sqlite3Step() to do most of the work.  If a schema error occurs,
44957 ** call sqlite3Reprepare() and try again.
44958 */
44959 #ifdef SQLITE_OMIT_PARSER
44960 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
44961   int rc = SQLITE_MISUSE;
44962   if( pStmt ){
44963     Vdbe *v;
44964     v = (Vdbe*)pStmt;
44965     sqlite3_mutex_enter(v->db->mutex);
44966     rc = sqlite3Step(v);
44967     sqlite3_mutex_leave(v->db->mutex);
44968   }
44969   return rc;
44970 }
44971 #else
44972 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
44973   int rc = SQLITE_MISUSE;
44974   if( pStmt ){
44975     int cnt = 0;
44976     Vdbe *v = (Vdbe*)pStmt;
44977     sqlite3 *db = v->db;
44978     sqlite3_mutex_enter(db->mutex);
44979     while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
44980            && cnt++ < 5
44981            && vdbeReprepare(v) ){
44982       sqlite3_reset(pStmt);
44983       v->expired = 0;
44984     }
44985     if( rc==SQLITE_SCHEMA && v->zSql && db->pErr ){
44986       /* This case occurs after failing to recompile an sql statement. 
44987       ** The error message from the SQL compiler has already been loaded 
44988       ** into the database handle. This block copies the error message 
44989       ** from the database handle into the statement and sets the statement
44990       ** program counter to 0 to ensure that when the statement is 
44991       ** finalized or reset the parser error message is available via
44992       ** sqlite3_errmsg() and sqlite3_errcode().
44993       */
44994       const char *zErr = (const char *)sqlite3_value_text(db->pErr); 
44995       sqlite3DbFree(db, v->zErrMsg);
44996       if( !db->mallocFailed ){
44997         v->zErrMsg = sqlite3DbStrDup(db, zErr);
44998       } else {
44999         v->zErrMsg = 0;
45000         v->rc = SQLITE_NOMEM;
45001       }
45002     }
45003     rc = sqlite3ApiExit(db, rc);
45004     sqlite3_mutex_leave(db->mutex);
45005   }
45006   return rc;
45007 }
45008 #endif
45009
45010 /*
45011 ** Extract the user data from a sqlite3_context structure and return a
45012 ** pointer to it.
45013 */
45014 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
45015   assert( p && p->pFunc );
45016   return p->pFunc->pUserData;
45017 }
45018
45019 /*
45020 ** Extract the user data from a sqlite3_context structure and return a
45021 ** pointer to it.
45022 */
45023 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
45024   assert( p && p->pFunc );
45025   return p->s.db;
45026 }
45027
45028 /*
45029 ** The following is the implementation of an SQL function that always
45030 ** fails with an error message stating that the function is used in the
45031 ** wrong context.  The sqlite3_overload_function() API might construct
45032 ** SQL function that use this routine so that the functions will exist
45033 ** for name resolution but are actually overloaded by the xFindFunction
45034 ** method of virtual tables.
45035 */
45036 SQLITE_PRIVATE void sqlite3InvalidFunction(
45037   sqlite3_context *context,  /* The function calling context */
45038   int argc,                  /* Number of arguments to the function */
45039   sqlite3_value **argv       /* Value of each argument */
45040 ){
45041   const char *zName = context->pFunc->zName;
45042   char *zErr;
45043   zErr = sqlite3MPrintf(0,
45044       "unable to use function %s in the requested context", zName);
45045   sqlite3_result_error(context, zErr, -1);
45046   sqlite3_free(zErr);
45047 }
45048
45049 /*
45050 ** Allocate or return the aggregate context for a user function.  A new
45051 ** context is allocated on the first call.  Subsequent calls return the
45052 ** same context that was returned on prior calls.
45053 */
45054 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
45055   Mem *pMem;
45056   assert( p && p->pFunc && p->pFunc->xStep );
45057   assert( sqlite3_mutex_held(p->s.db->mutex) );
45058   pMem = p->pMem;
45059   if( (pMem->flags & MEM_Agg)==0 ){
45060     if( nByte==0 ){
45061       sqlite3VdbeMemReleaseExternal(pMem);
45062       pMem->flags = MEM_Null;
45063       pMem->z = 0;
45064     }else{
45065       sqlite3VdbeMemGrow(pMem, nByte, 0);
45066       pMem->flags = MEM_Agg;
45067       pMem->u.pDef = p->pFunc;
45068       if( pMem->z ){
45069         memset(pMem->z, 0, nByte);
45070       }
45071     }
45072   }
45073   return (void*)pMem->z;
45074 }
45075
45076 /*
45077 ** Return the auxilary data pointer, if any, for the iArg'th argument to
45078 ** the user-function defined by pCtx.
45079 */
45080 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
45081   VdbeFunc *pVdbeFunc;
45082
45083   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
45084   pVdbeFunc = pCtx->pVdbeFunc;
45085   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
45086     return 0;
45087   }
45088   return pVdbeFunc->apAux[iArg].pAux;
45089 }
45090
45091 /*
45092 ** Set the auxilary data pointer and delete function, for the iArg'th
45093 ** argument to the user-function defined by pCtx. Any previous value is
45094 ** deleted by calling the delete function specified when it was set.
45095 */
45096 SQLITE_API void sqlite3_set_auxdata(
45097   sqlite3_context *pCtx, 
45098   int iArg, 
45099   void *pAux, 
45100   void (*xDelete)(void*)
45101 ){
45102   struct AuxData *pAuxData;
45103   VdbeFunc *pVdbeFunc;
45104   if( iArg<0 ) goto failed;
45105
45106   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
45107   pVdbeFunc = pCtx->pVdbeFunc;
45108   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
45109     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
45110     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
45111     pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
45112     if( !pVdbeFunc ){
45113       goto failed;
45114     }
45115     pCtx->pVdbeFunc = pVdbeFunc;
45116     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
45117     pVdbeFunc->nAux = iArg+1;
45118     pVdbeFunc->pFunc = pCtx->pFunc;
45119   }
45120
45121   pAuxData = &pVdbeFunc->apAux[iArg];
45122   if( pAuxData->pAux && pAuxData->xDelete ){
45123     pAuxData->xDelete(pAuxData->pAux);
45124   }
45125   pAuxData->pAux = pAux;
45126   pAuxData->xDelete = xDelete;
45127   return;
45128
45129 failed:
45130   if( xDelete ){
45131     xDelete(pAux);
45132   }
45133 }
45134
45135 /*
45136 ** Return the number of times the Step function of a aggregate has been 
45137 ** called.
45138 **
45139 ** This function is deprecated.  Do not use it for new code.  It is
45140 ** provide only to avoid breaking legacy code.  New aggregate function
45141 ** implementations should keep their own counts within their aggregate
45142 ** context.
45143 */
45144 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
45145   assert( p && p->pFunc && p->pFunc->xStep );
45146   return p->pMem->n;
45147 }
45148
45149 /*
45150 ** Return the number of columns in the result set for the statement pStmt.
45151 */
45152 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
45153   Vdbe *pVm = (Vdbe *)pStmt;
45154   return pVm ? pVm->nResColumn : 0;
45155 }
45156
45157 /*
45158 ** Return the number of values available from the current row of the
45159 ** currently executing statement pStmt.
45160 */
45161 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
45162   Vdbe *pVm = (Vdbe *)pStmt;
45163   if( pVm==0 || pVm->pResultSet==0 ) return 0;
45164   return pVm->nResColumn;
45165 }
45166
45167
45168 /*
45169 ** Check to see if column iCol of the given statement is valid.  If
45170 ** it is, return a pointer to the Mem for the value of that column.
45171 ** If iCol is not valid, return a pointer to a Mem which has a value
45172 ** of NULL.
45173 */
45174 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
45175   Vdbe *pVm;
45176   int vals;
45177   Mem *pOut;
45178
45179   pVm = (Vdbe *)pStmt;
45180   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
45181     sqlite3_mutex_enter(pVm->db->mutex);
45182     vals = sqlite3_data_count(pStmt);
45183     pOut = &pVm->pResultSet[i];
45184   }else{
45185     static const Mem nullMem = {{0}, 0.0, 0, "", 0, MEM_Null, SQLITE_NULL, 0, 0, 0 };
45186     if( pVm->db ){
45187       sqlite3_mutex_enter(pVm->db->mutex);
45188       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
45189     }
45190     pOut = (Mem*)&nullMem;
45191   }
45192   return pOut;
45193 }
45194
45195 /*
45196 ** This function is called after invoking an sqlite3_value_XXX function on a 
45197 ** column value (i.e. a value returned by evaluating an SQL expression in the
45198 ** select list of a SELECT statement) that may cause a malloc() failure. If 
45199 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
45200 ** code of statement pStmt set to SQLITE_NOMEM.
45201 **
45202 ** Specifically, this is called from within:
45203 **
45204 **     sqlite3_column_int()
45205 **     sqlite3_column_int64()
45206 **     sqlite3_column_text()
45207 **     sqlite3_column_text16()
45208 **     sqlite3_column_real()
45209 **     sqlite3_column_bytes()
45210 **     sqlite3_column_bytes16()
45211 **
45212 ** But not for sqlite3_column_blob(), which never calls malloc().
45213 */
45214 static void columnMallocFailure(sqlite3_stmt *pStmt)
45215 {
45216   /* If malloc() failed during an encoding conversion within an
45217   ** sqlite3_column_XXX API, then set the return code of the statement to
45218   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
45219   ** and _finalize() will return NOMEM.
45220   */
45221   Vdbe *p = (Vdbe *)pStmt;
45222   if( p ){
45223     p->rc = sqlite3ApiExit(p->db, p->rc);
45224     sqlite3_mutex_leave(p->db->mutex);
45225   }
45226 }
45227
45228 /**************************** sqlite3_column_  *******************************
45229 ** The following routines are used to access elements of the current row
45230 ** in the result set.
45231 */
45232 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
45233   const void *val;
45234   val = sqlite3_value_blob( columnMem(pStmt,i) );
45235   /* Even though there is no encoding conversion, value_blob() might
45236   ** need to call malloc() to expand the result of a zeroblob() 
45237   ** expression. 
45238   */
45239   columnMallocFailure(pStmt);
45240   return val;
45241 }
45242 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
45243   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
45244   columnMallocFailure(pStmt);
45245   return val;
45246 }
45247 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
45248   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
45249   columnMallocFailure(pStmt);
45250   return val;
45251 }
45252 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
45253   double val = sqlite3_value_double( columnMem(pStmt,i) );
45254   columnMallocFailure(pStmt);
45255   return val;
45256 }
45257 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
45258   int val = sqlite3_value_int( columnMem(pStmt,i) );
45259   columnMallocFailure(pStmt);
45260   return val;
45261 }
45262 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
45263   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
45264   columnMallocFailure(pStmt);
45265   return val;
45266 }
45267 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
45268   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
45269   columnMallocFailure(pStmt);
45270   return val;
45271 }
45272 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
45273   sqlite3_value *pOut = columnMem(pStmt, i);
45274   columnMallocFailure(pStmt);
45275   return pOut;
45276 }
45277 #ifndef SQLITE_OMIT_UTF16
45278 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
45279   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
45280   columnMallocFailure(pStmt);
45281   return val;
45282 }
45283 #endif /* SQLITE_OMIT_UTF16 */
45284 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
45285   int iType = sqlite3_value_type( columnMem(pStmt,i) );
45286   columnMallocFailure(pStmt);
45287   return iType;
45288 }
45289
45290 /* The following function is experimental and subject to change or
45291 ** removal */
45292 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
45293 **  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
45294 **}
45295 */
45296
45297 /*
45298 ** Convert the N-th element of pStmt->pColName[] into a string using
45299 ** xFunc() then return that string.  If N is out of range, return 0.
45300 **
45301 ** There are up to 5 names for each column.  useType determines which
45302 ** name is returned.  Here are the names:
45303 **
45304 **    0      The column name as it should be displayed for output
45305 **    1      The datatype name for the column
45306 **    2      The name of the database that the column derives from
45307 **    3      The name of the table that the column derives from
45308 **    4      The name of the table column that the result column derives from
45309 **
45310 ** If the result is not a simple column reference (if it is an expression
45311 ** or a constant) then useTypes 2, 3, and 4 return NULL.
45312 */
45313 static const void *columnName(
45314   sqlite3_stmt *pStmt,
45315   int N,
45316   const void *(*xFunc)(Mem*),
45317   int useType
45318 ){
45319   const void *ret = 0;
45320   Vdbe *p = (Vdbe *)pStmt;
45321   int n;
45322   
45323
45324   if( p!=0 ){
45325     n = sqlite3_column_count(pStmt);
45326     if( N<n && N>=0 ){
45327       N += useType*n;
45328       sqlite3_mutex_enter(p->db->mutex);
45329       ret = xFunc(&p->aColName[N]);
45330
45331       /* A malloc may have failed inside of the xFunc() call. If this
45332       ** is the case, clear the mallocFailed flag and return NULL.
45333       */
45334       if( p->db && p->db->mallocFailed ){
45335         p->db->mallocFailed = 0;
45336         ret = 0;
45337       }
45338       sqlite3_mutex_leave(p->db->mutex);
45339     }
45340   }
45341   return ret;
45342 }
45343
45344 /*
45345 ** Return the name of the Nth column of the result set returned by SQL
45346 ** statement pStmt.
45347 */
45348 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
45349   return columnName(
45350       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
45351 }
45352 #ifndef SQLITE_OMIT_UTF16
45353 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
45354   return columnName(
45355       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
45356 }
45357 #endif
45358
45359 /*
45360 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
45361 ** not define OMIT_DECLTYPE.
45362 */
45363 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
45364 # error "Must not define both SQLITE_OMIT_DECLTYPE \
45365          and SQLITE_ENABLE_COLUMN_METADATA"
45366 #endif
45367
45368 #ifndef SQLITE_OMIT_DECLTYPE
45369 /*
45370 ** Return the column declaration type (if applicable) of the 'i'th column
45371 ** of the result set of SQL statement pStmt.
45372 */
45373 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
45374   return columnName(
45375       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
45376 }
45377 #ifndef SQLITE_OMIT_UTF16
45378 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
45379   return columnName(
45380       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
45381 }
45382 #endif /* SQLITE_OMIT_UTF16 */
45383 #endif /* SQLITE_OMIT_DECLTYPE */
45384
45385 #ifdef SQLITE_ENABLE_COLUMN_METADATA
45386 /*
45387 ** Return the name of the database from which a result column derives.
45388 ** NULL is returned if the result column is an expression or constant or
45389 ** anything else which is not an unabiguous reference to a database column.
45390 */
45391 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
45392   return columnName(
45393       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
45394 }
45395 #ifndef SQLITE_OMIT_UTF16
45396 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
45397   return columnName(
45398       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
45399 }
45400 #endif /* SQLITE_OMIT_UTF16 */
45401
45402 /*
45403 ** Return the name of the table from which a result column derives.
45404 ** NULL is returned if the result column is an expression or constant or
45405 ** anything else which is not an unabiguous reference to a database column.
45406 */
45407 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
45408   return columnName(
45409       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
45410 }
45411 #ifndef SQLITE_OMIT_UTF16
45412 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
45413   return columnName(
45414       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
45415 }
45416 #endif /* SQLITE_OMIT_UTF16 */
45417
45418 /*
45419 ** Return the name of the table column from which a result column derives.
45420 ** NULL is returned if the result column is an expression or constant or
45421 ** anything else which is not an unabiguous reference to a database column.
45422 */
45423 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
45424   return columnName(
45425       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
45426 }
45427 #ifndef SQLITE_OMIT_UTF16
45428 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
45429   return columnName(
45430       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
45431 }
45432 #endif /* SQLITE_OMIT_UTF16 */
45433 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
45434
45435
45436 /******************************* sqlite3_bind_  ***************************
45437 ** 
45438 ** Routines used to attach values to wildcards in a compiled SQL statement.
45439 */
45440 /*
45441 ** Unbind the value bound to variable i in virtual machine p. This is the 
45442 ** the same as binding a NULL value to the column. If the "i" parameter is
45443 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
45444 **
45445 ** The error code stored in database p->db is overwritten with the return
45446 ** value in any case.
45447 */
45448 static int vdbeUnbind(Vdbe *p, int i){
45449   Mem *pVar;
45450   if( p==0 || p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
45451     if( p ) sqlite3Error(p->db, SQLITE_MISUSE, 0);
45452     return SQLITE_MISUSE;
45453   }
45454   if( i<1 || i>p->nVar ){
45455     sqlite3Error(p->db, SQLITE_RANGE, 0);
45456     return SQLITE_RANGE;
45457   }
45458   i--;
45459   pVar = &p->aVar[i];
45460   sqlite3VdbeMemRelease(pVar);
45461   pVar->flags = MEM_Null;
45462   sqlite3Error(p->db, SQLITE_OK, 0);
45463   return SQLITE_OK;
45464 }
45465
45466 /*
45467 ** Bind a text or BLOB value.
45468 */
45469 static int bindText(
45470   sqlite3_stmt *pStmt,   /* The statement to bind against */
45471   int i,                 /* Index of the parameter to bind */
45472   const void *zData,     /* Pointer to the data to be bound */
45473   int nData,             /* Number of bytes of data to be bound */
45474   void (*xDel)(void*),   /* Destructor for the data */
45475   int encoding           /* Encoding for the data */
45476 ){
45477   Vdbe *p = (Vdbe *)pStmt;
45478   Mem *pVar;
45479   int rc;
45480
45481   if( p==0 ){
45482     return SQLITE_MISUSE;
45483   }
45484   sqlite3_mutex_enter(p->db->mutex);
45485   rc = vdbeUnbind(p, i);
45486   if( rc==SQLITE_OK && zData!=0 ){
45487     pVar = &p->aVar[i-1];
45488     rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
45489     if( rc==SQLITE_OK && encoding!=0 ){
45490       rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
45491     }
45492     sqlite3Error(p->db, rc, 0);
45493     rc = sqlite3ApiExit(p->db, rc);
45494   }
45495   sqlite3_mutex_leave(p->db->mutex);
45496   return rc;
45497 }
45498
45499
45500 /*
45501 ** Bind a blob value to an SQL statement variable.
45502 */
45503 SQLITE_API int sqlite3_bind_blob(
45504   sqlite3_stmt *pStmt, 
45505   int i, 
45506   const void *zData, 
45507   int nData, 
45508   void (*xDel)(void*)
45509 ){
45510   return bindText(pStmt, i, zData, nData, xDel, 0);
45511 }
45512 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
45513   int rc;
45514   Vdbe *p = (Vdbe *)pStmt;
45515   sqlite3_mutex_enter(p->db->mutex);
45516   rc = vdbeUnbind(p, i);
45517   if( rc==SQLITE_OK ){
45518     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
45519   }
45520   sqlite3_mutex_leave(p->db->mutex);
45521   return rc;
45522 }
45523 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
45524   return sqlite3_bind_int64(p, i, (i64)iValue);
45525 }
45526 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
45527   int rc;
45528   Vdbe *p = (Vdbe *)pStmt;
45529   sqlite3_mutex_enter(p->db->mutex);
45530   rc = vdbeUnbind(p, i);
45531   if( rc==SQLITE_OK ){
45532     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
45533   }
45534   sqlite3_mutex_leave(p->db->mutex);
45535   return rc;
45536 }
45537 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
45538   int rc;
45539   Vdbe *p = (Vdbe*)pStmt;
45540   sqlite3_mutex_enter(p->db->mutex);
45541   rc = vdbeUnbind(p, i);
45542   sqlite3_mutex_leave(p->db->mutex);
45543   return rc;
45544 }
45545 SQLITE_API int sqlite3_bind_text( 
45546   sqlite3_stmt *pStmt, 
45547   int i, 
45548   const char *zData, 
45549   int nData, 
45550   void (*xDel)(void*)
45551 ){
45552   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
45553 }
45554 #ifndef SQLITE_OMIT_UTF16
45555 SQLITE_API int sqlite3_bind_text16(
45556   sqlite3_stmt *pStmt, 
45557   int i, 
45558   const void *zData, 
45559   int nData, 
45560   void (*xDel)(void*)
45561 ){
45562   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
45563 }
45564 #endif /* SQLITE_OMIT_UTF16 */
45565 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
45566   int rc;
45567   Vdbe *p = (Vdbe *)pStmt;
45568   sqlite3_mutex_enter(p->db->mutex);
45569   rc = vdbeUnbind(p, i);
45570   if( rc==SQLITE_OK ){
45571     rc = sqlite3VdbeMemCopy(&p->aVar[i-1], pValue);
45572     if( rc==SQLITE_OK ){
45573       rc = sqlite3VdbeChangeEncoding(&p->aVar[i-1], ENC(p->db));
45574     }
45575   }
45576   rc = sqlite3ApiExit(p->db, rc);
45577   sqlite3_mutex_leave(p->db->mutex);
45578   return rc;
45579 }
45580 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
45581   int rc;
45582   Vdbe *p = (Vdbe *)pStmt;
45583   sqlite3_mutex_enter(p->db->mutex);
45584   rc = vdbeUnbind(p, i);
45585   if( rc==SQLITE_OK ){
45586     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
45587   }
45588   sqlite3_mutex_leave(p->db->mutex);
45589   return rc;
45590 }
45591
45592 /*
45593 ** Return the number of wildcards that can be potentially bound to.
45594 ** This routine is added to support DBD::SQLite.  
45595 */
45596 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
45597   Vdbe *p = (Vdbe*)pStmt;
45598   return p ? p->nVar : 0;
45599 }
45600
45601 /*
45602 ** Create a mapping from variable numbers to variable names
45603 ** in the Vdbe.azVar[] array, if such a mapping does not already
45604 ** exist.
45605 */
45606 static void createVarMap(Vdbe *p){
45607   if( !p->okVar ){
45608     sqlite3_mutex_enter(p->db->mutex);
45609     if( !p->okVar ){
45610       int j;
45611       Op *pOp;
45612       for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
45613         if( pOp->opcode==OP_Variable ){
45614           assert( pOp->p1>0 && pOp->p1<=p->nVar );
45615           p->azVar[pOp->p1-1] = pOp->p4.z;
45616         }
45617       }
45618       p->okVar = 1;
45619     }
45620     sqlite3_mutex_leave(p->db->mutex);
45621   }
45622 }
45623
45624 /*
45625 ** Return the name of a wildcard parameter.  Return NULL if the index
45626 ** is out of range or if the wildcard is unnamed.
45627 **
45628 ** The result is always UTF-8.
45629 */
45630 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
45631   Vdbe *p = (Vdbe*)pStmt;
45632   if( p==0 || i<1 || i>p->nVar ){
45633     return 0;
45634   }
45635   createVarMap(p);
45636   return p->azVar[i-1];
45637 }
45638
45639 /*
45640 ** Given a wildcard parameter name, return the index of the variable
45641 ** with that name.  If there is no variable with the given name,
45642 ** return 0.
45643 */
45644 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
45645   Vdbe *p = (Vdbe*)pStmt;
45646   int i;
45647   if( p==0 ){
45648     return 0;
45649   }
45650   createVarMap(p); 
45651   if( zName ){
45652     for(i=0; i<p->nVar; i++){
45653       const char *z = p->azVar[i];
45654       if( z && strcmp(z,zName)==0 ){
45655         return i+1;
45656       }
45657     }
45658   }
45659   return 0;
45660 }
45661
45662 /*
45663 ** Transfer all bindings from the first statement over to the second.
45664 ** If the two statements contain a different number of bindings, then
45665 ** an SQLITE_ERROR is returned.
45666 */
45667 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
45668   Vdbe *pFrom = (Vdbe*)pFromStmt;
45669   Vdbe *pTo = (Vdbe*)pToStmt;
45670   int i, rc = SQLITE_OK;
45671   if( (pFrom->magic!=VDBE_MAGIC_RUN && pFrom->magic!=VDBE_MAGIC_HALT)
45672     || (pTo->magic!=VDBE_MAGIC_RUN && pTo->magic!=VDBE_MAGIC_HALT)
45673     || pTo->db!=pFrom->db ){
45674     return SQLITE_MISUSE;
45675   }
45676   if( pFrom->nVar!=pTo->nVar ){
45677     return SQLITE_ERROR;
45678   }
45679   sqlite3_mutex_enter(pTo->db->mutex);
45680   for(i=0; rc==SQLITE_OK && i<pFrom->nVar; i++){
45681     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
45682   }
45683   sqlite3_mutex_leave(pTo->db->mutex);
45684   assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
45685   return rc;
45686 }
45687
45688 /*
45689 ** Deprecated external interface.  Internal/core SQLite code
45690 ** should call sqlite3TransferBindings.
45691 */
45692 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
45693   return sqlite3TransferBindings(pFromStmt, pToStmt);
45694 }
45695
45696 /*
45697 ** Return the sqlite3* database handle to which the prepared statement given
45698 ** in the argument belongs.  This is the same database handle that was
45699 ** the first argument to the sqlite3_prepare() that was used to create
45700 ** the statement in the first place.
45701 */
45702 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
45703   return pStmt ? ((Vdbe*)pStmt)->db : 0;
45704 }
45705
45706 /*
45707 ** Return a pointer to the next prepared statement after pStmt associated
45708 ** with database connection pDb.  If pStmt is NULL, return the first
45709 ** prepared statement for the database connection.  Return NULL if there
45710 ** are no more.
45711 */
45712 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
45713   sqlite3_stmt *pNext;
45714   sqlite3_mutex_enter(pDb->mutex);
45715   if( pStmt==0 ){
45716     pNext = (sqlite3_stmt*)pDb->pVdbe;
45717   }else{
45718     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
45719   }
45720   sqlite3_mutex_leave(pDb->mutex);
45721   return pNext;
45722 }
45723
45724 /************** End of vdbeapi.c *********************************************/
45725 /************** Begin file vdbe.c ********************************************/
45726 /*
45727 ** 2001 September 15
45728 **
45729 ** The author disclaims copyright to this source code.  In place of
45730 ** a legal notice, here is a blessing:
45731 **
45732 **    May you do good and not evil.
45733 **    May you find forgiveness for yourself and forgive others.
45734 **    May you share freely, never taking more than you give.
45735 **
45736 *************************************************************************
45737 ** The code in this file implements execution method of the 
45738 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
45739 ** handles housekeeping details such as creating and deleting
45740 ** VDBE instances.  This file is solely interested in executing
45741 ** the VDBE program.
45742 **
45743 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
45744 ** to a VDBE.
45745 **
45746 ** The SQL parser generates a program which is then executed by
45747 ** the VDBE to do the work of the SQL statement.  VDBE programs are 
45748 ** similar in form to assembly language.  The program consists of
45749 ** a linear sequence of operations.  Each operation has an opcode 
45750 ** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4 
45751 ** is a null-terminated string.  Operand P5 is an unsigned character.
45752 ** Few opcodes use all 5 operands.
45753 **
45754 ** Computation results are stored on a set of registers numbered beginning
45755 ** with 1 and going up to Vdbe.nMem.  Each register can store
45756 ** either an integer, a null-terminated string, a floating point
45757 ** number, or the SQL "NULL" value.  An implicit conversion from one
45758 ** type to the other occurs as necessary.
45759 ** 
45760 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
45761 ** function which does the work of interpreting a VDBE program.
45762 ** But other routines are also provided to help in building up
45763 ** a program instruction by instruction.
45764 **
45765 ** Various scripts scan this source file in order to generate HTML
45766 ** documentation, headers files, or other derived files.  The formatting
45767 ** of the code in this file is, therefore, important.  See other comments
45768 ** in this file for details.  If in doubt, do not deviate from existing
45769 ** commenting and indentation practices when changing or adding code.
45770 **
45771 ** $Id: vdbe.c,v 1.779 2008/09/22 06:13:32 danielk1977 Exp $
45772 */
45773
45774 /*
45775 ** The following global variable is incremented every time a cursor
45776 ** moves, either by the OP_MoveXX, OP_Next, or OP_Prev opcodes.  The test
45777 ** procedures use this information to make sure that indices are
45778 ** working correctly.  This variable has no function other than to
45779 ** help verify the correct operation of the library.
45780 */
45781 #ifdef SQLITE_TEST
45782 SQLITE_API int sqlite3_search_count = 0;
45783 #endif
45784
45785 /*
45786 ** When this global variable is positive, it gets decremented once before
45787 ** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
45788 ** field of the sqlite3 structure is set in order to simulate and interrupt.
45789 **
45790 ** This facility is used for testing purposes only.  It does not function
45791 ** in an ordinary build.
45792 */
45793 #ifdef SQLITE_TEST
45794 SQLITE_API int sqlite3_interrupt_count = 0;
45795 #endif
45796
45797 /*
45798 ** The next global variable is incremented each type the OP_Sort opcode
45799 ** is executed.  The test procedures use this information to make sure that
45800 ** sorting is occurring or not occurring at appropriate times.   This variable
45801 ** has no function other than to help verify the correct operation of the
45802 ** library.
45803 */
45804 #ifdef SQLITE_TEST
45805 SQLITE_API int sqlite3_sort_count = 0;
45806 #endif
45807
45808 /*
45809 ** The next global variable records the size of the largest MEM_Blob
45810 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
45811 ** use this information to make sure that the zero-blob functionality
45812 ** is working correctly.   This variable has no function other than to
45813 ** help verify the correct operation of the library.
45814 */
45815 #ifdef SQLITE_TEST
45816 SQLITE_API int sqlite3_max_blobsize = 0;
45817 static void updateMaxBlobsize(Mem *p){
45818   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
45819     sqlite3_max_blobsize = p->n;
45820   }
45821 }
45822 #endif
45823
45824 /*
45825 ** Test a register to see if it exceeds the current maximum blob size.
45826 ** If it does, record the new maximum blob size.
45827 */
45828 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
45829 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
45830 #else
45831 # define UPDATE_MAX_BLOBSIZE(P)
45832 #endif
45833
45834 /*
45835 ** Convert the given register into a string if it isn't one
45836 ** already. Return non-zero if a malloc() fails.
45837 */
45838 #define Stringify(P, enc) \
45839    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
45840      { goto no_mem; }
45841
45842 /*
45843 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
45844 ** a pointer to a dynamically allocated string where some other entity
45845 ** is responsible for deallocating that string.  Because the register
45846 ** does not control the string, it might be deleted without the register
45847 ** knowing it.
45848 **
45849 ** This routine converts an ephemeral string into a dynamically allocated
45850 ** string that the register itself controls.  In other words, it
45851 ** converts an MEM_Ephem string into an MEM_Dyn string.
45852 */
45853 #define Deephemeralize(P) \
45854    if( ((P)->flags&MEM_Ephem)!=0 \
45855        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
45856
45857 /*
45858 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
45859 ** P if required.
45860 */
45861 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
45862
45863 /*
45864 ** Argument pMem points at a register that will be passed to a
45865 ** user-defined function or returned to the user as the result of a query.
45866 ** The second argument, 'db_enc' is the text encoding used by the vdbe for
45867 ** register variables.  This routine sets the pMem->enc and pMem->type
45868 ** variables used by the sqlite3_value_*() routines.
45869 */
45870 #define storeTypeInfo(A,B) _storeTypeInfo(A)
45871 static void _storeTypeInfo(Mem *pMem){
45872   int flags = pMem->flags;
45873   if( flags & MEM_Null ){
45874     pMem->type = SQLITE_NULL;
45875   }
45876   else if( flags & MEM_Int ){
45877     pMem->type = SQLITE_INTEGER;
45878   }
45879   else if( flags & MEM_Real ){
45880     pMem->type = SQLITE_FLOAT;
45881   }
45882   else if( flags & MEM_Str ){
45883     pMem->type = SQLITE_TEXT;
45884   }else{
45885     pMem->type = SQLITE_BLOB;
45886   }
45887 }
45888
45889 /*
45890 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
45891 ** created by mkopcodeh.awk during compilation.  Data is obtained
45892 ** from the comments following the "case OP_xxxx:" statements in
45893 ** this file.  
45894 */
45895 static const unsigned char opcodeProperty[] = OPFLG_INITIALIZER;
45896
45897 /*
45898 ** Return true if an opcode has any of the OPFLG_xxx properties
45899 ** specified by mask.
45900 */
45901 SQLITE_PRIVATE int sqlite3VdbeOpcodeHasProperty(int opcode, int mask){
45902   assert( opcode>0 && opcode<sizeof(opcodeProperty) );
45903   return (opcodeProperty[opcode]&mask)!=0;
45904 }
45905
45906 /*
45907 ** Allocate cursor number iCur.  Return a pointer to it.  Return NULL
45908 ** if we run out of memory.
45909 */
45910 static Cursor *allocateCursor(
45911   Vdbe *p, 
45912   int iCur, 
45913   Op *pOp,
45914   int iDb, 
45915   int isBtreeCursor
45916 ){
45917   /* Find the memory cell that will be used to store the blob of memory
45918   ** required for this Cursor structure. It is convenient to use a 
45919   ** vdbe memory cell to manage the memory allocation required for a
45920   ** Cursor structure for the following reasons:
45921   **
45922   **   * Sometimes cursor numbers are used for a couple of different
45923   **     purposes in a vdbe program. The different uses might require
45924   **     different sized allocations. Memory cells provide growable
45925   **     allocations.
45926   **
45927   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
45928   **     be freed lazily via the sqlite3_release_memory() API. This
45929   **     minimizes the number of malloc calls made by the system.
45930   **
45931   ** Memory cells for cursors are allocated at the top of the address
45932   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
45933   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
45934   */
45935   Mem *pMem = &p->aMem[p->nMem-iCur];
45936
45937   int nByte;
45938   Cursor *pCx = 0;
45939   /* If the opcode of pOp is OP_SetNumColumns, then pOp->p2 contains
45940   ** the number of fields in the records contained in the table or
45941   ** index being opened. Use this to reserve space for the 
45942   ** Cursor.aType[] array.
45943   */
45944   int nField = 0;
45945   if( pOp->opcode==OP_SetNumColumns || pOp->opcode==OP_OpenEphemeral ){
45946     nField = pOp->p2;
45947   }
45948   nByte = 
45949       sizeof(Cursor) + 
45950       (isBtreeCursor?sqlite3BtreeCursorSize():0) + 
45951       2*nField*sizeof(u32);
45952
45953   assert( iCur<p->nCursor );
45954   if( p->apCsr[iCur] ){
45955     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
45956     p->apCsr[iCur] = 0;
45957   }
45958   if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
45959     p->apCsr[iCur] = pCx = (Cursor *)pMem->z;
45960     memset(pMem->z, 0, nByte);
45961     pCx->iDb = iDb;
45962     pCx->nField = nField;
45963     if( nField ){
45964       pCx->aType = (u32 *)&pMem->z[sizeof(Cursor)];
45965     }
45966     if( isBtreeCursor ){
45967       pCx->pCursor = (BtCursor *)&pMem->z[sizeof(Cursor)+2*nField*sizeof(u32)];
45968     }
45969   }
45970   return pCx;
45971 }
45972
45973 /*
45974 ** Try to convert a value into a numeric representation if we can
45975 ** do so without loss of information.  In other words, if the string
45976 ** looks like a number, convert it into a number.  If it does not
45977 ** look like a number, leave it alone.
45978 */
45979 static void applyNumericAffinity(Mem *pRec){
45980   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
45981     int realnum;
45982     sqlite3VdbeMemNulTerminate(pRec);
45983     if( (pRec->flags&MEM_Str)
45984          && sqlite3IsNumber(pRec->z, &realnum, pRec->enc) ){
45985       i64 value;
45986       sqlite3VdbeChangeEncoding(pRec, SQLITE_UTF8);
45987       if( !realnum && sqlite3Atoi64(pRec->z, &value) ){
45988         pRec->u.i = value;
45989         MemSetTypeFlag(pRec, MEM_Int);
45990       }else{
45991         sqlite3VdbeMemRealify(pRec);
45992       }
45993     }
45994   }
45995 }
45996
45997 /*
45998 ** Processing is determine by the affinity parameter:
45999 **
46000 ** SQLITE_AFF_INTEGER:
46001 ** SQLITE_AFF_REAL:
46002 ** SQLITE_AFF_NUMERIC:
46003 **    Try to convert pRec to an integer representation or a 
46004 **    floating-point representation if an integer representation
46005 **    is not possible.  Note that the integer representation is
46006 **    always preferred, even if the affinity is REAL, because
46007 **    an integer representation is more space efficient on disk.
46008 **
46009 ** SQLITE_AFF_TEXT:
46010 **    Convert pRec to a text representation.
46011 **
46012 ** SQLITE_AFF_NONE:
46013 **    No-op.  pRec is unchanged.
46014 */
46015 static void applyAffinity(
46016   Mem *pRec,          /* The value to apply affinity to */
46017   char affinity,      /* The affinity to be applied */
46018   u8 enc              /* Use this text encoding */
46019 ){
46020   if( affinity==SQLITE_AFF_TEXT ){
46021     /* Only attempt the conversion to TEXT if there is an integer or real
46022     ** representation (blob and NULL do not get converted) but no string
46023     ** representation.
46024     */
46025     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
46026       sqlite3VdbeMemStringify(pRec, enc);
46027     }
46028     pRec->flags &= ~(MEM_Real|MEM_Int);
46029   }else if( affinity!=SQLITE_AFF_NONE ){
46030     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
46031              || affinity==SQLITE_AFF_NUMERIC );
46032     applyNumericAffinity(pRec);
46033     if( pRec->flags & MEM_Real ){
46034       sqlite3VdbeIntegerAffinity(pRec);
46035     }
46036   }
46037 }
46038
46039 /*
46040 ** Try to convert the type of a function argument or a result column
46041 ** into a numeric representation.  Use either INTEGER or REAL whichever
46042 ** is appropriate.  But only do the conversion if it is possible without
46043 ** loss of information and return the revised type of the argument.
46044 **
46045 ** This is an EXPERIMENTAL api and is subject to change or removal.
46046 */
46047 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
46048   Mem *pMem = (Mem*)pVal;
46049   applyNumericAffinity(pMem);
46050   storeTypeInfo(pMem, 0);
46051   return pMem->type;
46052 }
46053
46054 /*
46055 ** Exported version of applyAffinity(). This one works on sqlite3_value*, 
46056 ** not the internal Mem* type.
46057 */
46058 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
46059   sqlite3_value *pVal, 
46060   u8 affinity, 
46061   u8 enc
46062 ){
46063   applyAffinity((Mem *)pVal, affinity, enc);
46064 }
46065
46066 #ifdef SQLITE_DEBUG
46067 /*
46068 ** Write a nice string representation of the contents of cell pMem
46069 ** into buffer zBuf, length nBuf.
46070 */
46071 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
46072   char *zCsr = zBuf;
46073   int f = pMem->flags;
46074
46075   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
46076
46077   if( f&MEM_Blob ){
46078     int i;
46079     char c;
46080     if( f & MEM_Dyn ){
46081       c = 'z';
46082       assert( (f & (MEM_Static|MEM_Ephem))==0 );
46083     }else if( f & MEM_Static ){
46084       c = 't';
46085       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
46086     }else if( f & MEM_Ephem ){
46087       c = 'e';
46088       assert( (f & (MEM_Static|MEM_Dyn))==0 );
46089     }else{
46090       c = 's';
46091     }
46092
46093     sqlite3_snprintf(100, zCsr, "%c", c);
46094     zCsr += strlen(zCsr);
46095     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
46096     zCsr += strlen(zCsr);
46097     for(i=0; i<16 && i<pMem->n; i++){
46098       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
46099       zCsr += strlen(zCsr);
46100     }
46101     for(i=0; i<16 && i<pMem->n; i++){
46102       char z = pMem->z[i];
46103       if( z<32 || z>126 ) *zCsr++ = '.';
46104       else *zCsr++ = z;
46105     }
46106
46107     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
46108     zCsr += strlen(zCsr);
46109     if( f & MEM_Zero ){
46110       sqlite3_snprintf(100, zCsr,"+%lldz",pMem->u.i);
46111       zCsr += strlen(zCsr);
46112     }
46113     *zCsr = '\0';
46114   }else if( f & MEM_Str ){
46115     int j, k;
46116     zBuf[0] = ' ';
46117     if( f & MEM_Dyn ){
46118       zBuf[1] = 'z';
46119       assert( (f & (MEM_Static|MEM_Ephem))==0 );
46120     }else if( f & MEM_Static ){
46121       zBuf[1] = 't';
46122       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
46123     }else if( f & MEM_Ephem ){
46124       zBuf[1] = 'e';
46125       assert( (f & (MEM_Static|MEM_Dyn))==0 );
46126     }else{
46127       zBuf[1] = 's';
46128     }
46129     k = 2;
46130     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
46131     k += strlen(&zBuf[k]);
46132     zBuf[k++] = '[';
46133     for(j=0; j<15 && j<pMem->n; j++){
46134       u8 c = pMem->z[j];
46135       if( c>=0x20 && c<0x7f ){
46136         zBuf[k++] = c;
46137       }else{
46138         zBuf[k++] = '.';
46139       }
46140     }
46141     zBuf[k++] = ']';
46142     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
46143     k += strlen(&zBuf[k]);
46144     zBuf[k++] = 0;
46145   }
46146 }
46147 #endif
46148
46149 #ifdef SQLITE_DEBUG
46150 /*
46151 ** Print the value of a register for tracing purposes:
46152 */
46153 static void memTracePrint(FILE *out, Mem *p){
46154   if( p->flags & MEM_Null ){
46155     fprintf(out, " NULL");
46156   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
46157     fprintf(out, " si:%lld", p->u.i);
46158   }else if( p->flags & MEM_Int ){
46159     fprintf(out, " i:%lld", p->u.i);
46160   }else if( p->flags & MEM_Real ){
46161     fprintf(out, " r:%g", p->r);
46162   }else{
46163     char zBuf[200];
46164     sqlite3VdbeMemPrettyPrint(p, zBuf);
46165     fprintf(out, " ");
46166     fprintf(out, "%s", zBuf);
46167   }
46168 }
46169 static void registerTrace(FILE *out, int iReg, Mem *p){
46170   fprintf(out, "REG[%d] = ", iReg);
46171   memTracePrint(out, p);
46172   fprintf(out, "\n");
46173 }
46174 #endif
46175
46176 #ifdef SQLITE_DEBUG
46177 #  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
46178 #else
46179 #  define REGISTER_TRACE(R,M)
46180 #endif
46181
46182
46183 #ifdef VDBE_PROFILE
46184
46185 /* 
46186 ** hwtime.h contains inline assembler code for implementing 
46187 ** high-performance timing routines.
46188 */
46189 /************** Include hwtime.h in the middle of vdbe.c *********************/
46190 /************** Begin file hwtime.h ******************************************/
46191 /*
46192 ** 2008 May 27
46193 **
46194 ** The author disclaims copyright to this source code.  In place of
46195 ** a legal notice, here is a blessing:
46196 **
46197 **    May you do good and not evil.
46198 **    May you find forgiveness for yourself and forgive others.
46199 **    May you share freely, never taking more than you give.
46200 **
46201 ******************************************************************************
46202 **
46203 ** This file contains inline asm code for retrieving "high-performance"
46204 ** counters for x86 class CPUs.
46205 **
46206 ** $Id: hwtime.h,v 1.3 2008/08/01 14:33:15 shane Exp $
46207 */
46208 #ifndef _HWTIME_H_
46209 #define _HWTIME_H_
46210
46211 /*
46212 ** The following routine only works on pentium-class (or newer) processors.
46213 ** It uses the RDTSC opcode to read the cycle count value out of the
46214 ** processor and returns that value.  This can be used for high-res
46215 ** profiling.
46216 */
46217 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
46218       (defined(i386) || defined(__i386__) || defined(_M_IX86))
46219
46220   #if defined(__GNUC__)
46221
46222   __inline__ sqlite_uint64 sqlite3Hwtime(void){
46223      unsigned int lo, hi;
46224      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
46225      return (sqlite_uint64)hi << 32 | lo;
46226   }
46227
46228   #elif defined(_MSC_VER)
46229
46230   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
46231      __asm {
46232         rdtsc
46233         ret       ; return value at EDX:EAX
46234      }
46235   }
46236
46237   #endif
46238
46239 #elif (defined(__GNUC__) && defined(__x86_64__))
46240
46241   __inline__ sqlite_uint64 sqlite3Hwtime(void){
46242       unsigned long val;
46243       __asm__ __volatile__ ("rdtsc" : "=A" (val));
46244       return val;
46245   }
46246  
46247 #elif (defined(__GNUC__) && defined(__ppc__))
46248
46249   __inline__ sqlite_uint64 sqlite3Hwtime(void){
46250       unsigned long long retval;
46251       unsigned long junk;
46252       __asm__ __volatile__ ("\n\
46253           1:      mftbu   %1\n\
46254                   mftb    %L0\n\
46255                   mftbu   %0\n\
46256                   cmpw    %0,%1\n\
46257                   bne     1b"
46258                   : "=r" (retval), "=r" (junk));
46259       return retval;
46260   }
46261
46262 #else
46263
46264   #error Need implementation of sqlite3Hwtime() for your platform.
46265
46266   /*
46267   ** To compile without implementing sqlite3Hwtime() for your platform,
46268   ** you can remove the above #error and use the following
46269   ** stub function.  You will lose timing support for many
46270   ** of the debugging and testing utilities, but it should at
46271   ** least compile and run.
46272   */
46273 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
46274
46275 #endif
46276
46277 #endif /* !defined(_HWTIME_H_) */
46278
46279 /************** End of hwtime.h **********************************************/
46280 /************** Continuing where we left off in vdbe.c ***********************/
46281
46282 #endif
46283
46284 /*
46285 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
46286 ** sqlite3_interrupt() routine has been called.  If it has been, then
46287 ** processing of the VDBE program is interrupted.
46288 **
46289 ** This macro added to every instruction that does a jump in order to
46290 ** implement a loop.  This test used to be on every single instruction,
46291 ** but that meant we more testing that we needed.  By only testing the
46292 ** flag on jump instructions, we get a (small) speed improvement.
46293 */
46294 #define CHECK_FOR_INTERRUPT \
46295    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
46296
46297 #ifdef SQLITE_DEBUG
46298 static int fileExists(sqlite3 *db, const char *zFile){
46299   int res = 0;
46300   int rc = SQLITE_OK;
46301 #ifdef SQLITE_TEST
46302   /* If we are currently testing IO errors, then do not call OsAccess() to
46303   ** test for the presence of zFile. This is because any IO error that
46304   ** occurs here will not be reported, causing the test to fail.
46305   */
46306   extern int sqlite3_io_error_pending;
46307   if( sqlite3_io_error_pending<=0 )
46308 #endif
46309     rc = sqlite3OsAccess(db->pVfs, zFile, SQLITE_ACCESS_EXISTS, &res);
46310   return (res && rc==SQLITE_OK);
46311 }
46312 #endif
46313
46314 /*
46315 ** Execute as much of a VDBE program as we can then return.
46316 **
46317 ** sqlite3VdbeMakeReady() must be called before this routine in order to
46318 ** close the program with a final OP_Halt and to set up the callbacks
46319 ** and the error message pointer.
46320 **
46321 ** Whenever a row or result data is available, this routine will either
46322 ** invoke the result callback (if there is one) or return with
46323 ** SQLITE_ROW.
46324 **
46325 ** If an attempt is made to open a locked database, then this routine
46326 ** will either invoke the busy callback (if there is one) or it will
46327 ** return SQLITE_BUSY.
46328 **
46329 ** If an error occurs, an error message is written to memory obtained
46330 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
46331 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
46332 **
46333 ** If the callback ever returns non-zero, then the program exits
46334 ** immediately.  There will be no error message but the p->rc field is
46335 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
46336 **
46337 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
46338 ** routine to return SQLITE_ERROR.
46339 **
46340 ** Other fatal errors return SQLITE_ERROR.
46341 **
46342 ** After this routine has finished, sqlite3VdbeFinalize() should be
46343 ** used to clean up the mess that was left behind.
46344 */
46345 SQLITE_PRIVATE int sqlite3VdbeExec(
46346   Vdbe *p                    /* The VDBE */
46347 ){
46348   int pc;                    /* The program counter */
46349   Op *pOp;                   /* Current operation */
46350   int rc = SQLITE_OK;        /* Value to return */
46351   sqlite3 *db = p->db;       /* The database */
46352   u8 encoding = ENC(db);     /* The database encoding */
46353   Mem *pIn1, *pIn2, *pIn3;   /* Input operands */
46354   Mem *pOut;                 /* Output operand */
46355   u8 opProperty;
46356   int iCompare = 0;          /* Result of last OP_Compare operation */
46357   int *aPermute = 0;         /* Permuation of columns for OP_Compare */
46358 #ifdef VDBE_PROFILE
46359   u64 start;                 /* CPU clock count at start of opcode */
46360   int origPc;                /* Program counter at start of opcode */
46361 #endif
46362 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
46363   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
46364 #endif
46365   UnpackedRecord aTempRec[16]; /* Space to hold a transient UnpackedRecord */
46366
46367
46368   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
46369   assert( db->magic==SQLITE_MAGIC_BUSY );
46370   sqlite3BtreeMutexArrayEnter(&p->aMutex);
46371   if( p->rc==SQLITE_NOMEM ){
46372     /* This happens if a malloc() inside a call to sqlite3_column_text() or
46373     ** sqlite3_column_text16() failed.  */
46374     goto no_mem;
46375   }
46376   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
46377   p->rc = SQLITE_OK;
46378   assert( p->explain==0 );
46379   p->pResultSet = 0;
46380   db->busyHandler.nBusy = 0;
46381   CHECK_FOR_INTERRUPT;
46382   sqlite3VdbeIOTraceSql(p);
46383 #ifdef SQLITE_DEBUG
46384   sqlite3BeginBenignMalloc();
46385   if( p->pc==0 
46386    && ((p->db->flags & SQLITE_VdbeListing) || fileExists(db, "vdbe_explain"))
46387   ){
46388     int i;
46389     printf("VDBE Program Listing:\n");
46390     sqlite3VdbePrintSql(p);
46391     for(i=0; i<p->nOp; i++){
46392       sqlite3VdbePrintOp(stdout, i, &p->aOp[i]);
46393     }
46394   }
46395   if( fileExists(db, "vdbe_trace") ){
46396     p->trace = stdout;
46397   }
46398   sqlite3EndBenignMalloc();
46399 #endif
46400   for(pc=p->pc; rc==SQLITE_OK; pc++){
46401     assert( pc>=0 && pc<p->nOp );
46402     if( db->mallocFailed ) goto no_mem;
46403 #ifdef VDBE_PROFILE
46404     origPc = pc;
46405     start = sqlite3Hwtime();
46406 #endif
46407     pOp = &p->aOp[pc];
46408
46409     /* Only allow tracing if SQLITE_DEBUG is defined.
46410     */
46411 #ifdef SQLITE_DEBUG
46412     if( p->trace ){
46413       if( pc==0 ){
46414         printf("VDBE Execution Trace:\n");
46415         sqlite3VdbePrintSql(p);
46416       }
46417       sqlite3VdbePrintOp(p->trace, pc, pOp);
46418     }
46419     if( p->trace==0 && pc==0 ){
46420       sqlite3BeginBenignMalloc();
46421       if( fileExists(db, "vdbe_sqltrace") ){
46422         sqlite3VdbePrintSql(p);
46423       }
46424       sqlite3EndBenignMalloc();
46425     }
46426 #endif
46427       
46428
46429     /* Check to see if we need to simulate an interrupt.  This only happens
46430     ** if we have a special test build.
46431     */
46432 #ifdef SQLITE_TEST
46433     if( sqlite3_interrupt_count>0 ){
46434       sqlite3_interrupt_count--;
46435       if( sqlite3_interrupt_count==0 ){
46436         sqlite3_interrupt(db);
46437       }
46438     }
46439 #endif
46440
46441 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
46442     /* Call the progress callback if it is configured and the required number
46443     ** of VDBE ops have been executed (either since this invocation of
46444     ** sqlite3VdbeExec() or since last time the progress callback was called).
46445     ** If the progress callback returns non-zero, exit the virtual machine with
46446     ** a return code SQLITE_ABORT.
46447     */
46448     if( db->xProgress ){
46449       if( db->nProgressOps==nProgressOps ){
46450         int prc;
46451         if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
46452         prc =db->xProgress(db->pProgressArg);
46453         if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
46454         if( prc!=0 ){
46455           rc = SQLITE_INTERRUPT;
46456           goto vdbe_error_halt;
46457         }
46458         nProgressOps = 0;
46459       }
46460       nProgressOps++;
46461     }
46462 #endif
46463
46464     /* Do common setup processing for any opcode that is marked
46465     ** with the "out2-prerelease" tag.  Such opcodes have a single
46466     ** output which is specified by the P2 parameter.  The P2 register
46467     ** is initialized to a NULL.
46468     */
46469     opProperty = opcodeProperty[pOp->opcode];
46470     if( (opProperty & OPFLG_OUT2_PRERELEASE)!=0 ){
46471       assert( pOp->p2>0 );
46472       assert( pOp->p2<=p->nMem );
46473       pOut = &p->aMem[pOp->p2];
46474       sqlite3VdbeMemReleaseExternal(pOut);
46475       pOut->flags = MEM_Null;
46476     }else
46477  
46478     /* Do common setup for opcodes marked with one of the following
46479     ** combinations of properties.
46480     **
46481     **           in1
46482     **           in1 in2
46483     **           in1 in2 out3
46484     **           in1 in3
46485     **
46486     ** Variables pIn1, pIn2, and pIn3 are made to point to appropriate
46487     ** registers for inputs.  Variable pOut points to the output register.
46488     */
46489     if( (opProperty & OPFLG_IN1)!=0 ){
46490       assert( pOp->p1>0 );
46491       assert( pOp->p1<=p->nMem );
46492       pIn1 = &p->aMem[pOp->p1];
46493       REGISTER_TRACE(pOp->p1, pIn1);
46494       if( (opProperty & OPFLG_IN2)!=0 ){
46495         assert( pOp->p2>0 );
46496         assert( pOp->p2<=p->nMem );
46497         pIn2 = &p->aMem[pOp->p2];
46498         REGISTER_TRACE(pOp->p2, pIn2);
46499         if( (opProperty & OPFLG_OUT3)!=0 ){
46500           assert( pOp->p3>0 );
46501           assert( pOp->p3<=p->nMem );
46502           pOut = &p->aMem[pOp->p3];
46503         }
46504       }else if( (opProperty & OPFLG_IN3)!=0 ){
46505         assert( pOp->p3>0 );
46506         assert( pOp->p3<=p->nMem );
46507         pIn3 = &p->aMem[pOp->p3];
46508         REGISTER_TRACE(pOp->p3, pIn3);
46509       }
46510     }else if( (opProperty & OPFLG_IN2)!=0 ){
46511       assert( pOp->p2>0 );
46512       assert( pOp->p2<=p->nMem );
46513       pIn2 = &p->aMem[pOp->p2];
46514       REGISTER_TRACE(pOp->p2, pIn2);
46515     }else if( (opProperty & OPFLG_IN3)!=0 ){
46516       assert( pOp->p3>0 );
46517       assert( pOp->p3<=p->nMem );
46518       pIn3 = &p->aMem[pOp->p3];
46519       REGISTER_TRACE(pOp->p3, pIn3);
46520     }
46521
46522     switch( pOp->opcode ){
46523
46524 /*****************************************************************************
46525 ** What follows is a massive switch statement where each case implements a
46526 ** separate instruction in the virtual machine.  If we follow the usual
46527 ** indentation conventions, each case should be indented by 6 spaces.  But
46528 ** that is a lot of wasted space on the left margin.  So the code within
46529 ** the switch statement will break with convention and be flush-left. Another
46530 ** big comment (similar to this one) will mark the point in the code where
46531 ** we transition back to normal indentation.
46532 **
46533 ** The formatting of each case is important.  The makefile for SQLite
46534 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
46535 ** file looking for lines that begin with "case OP_".  The opcodes.h files
46536 ** will be filled with #defines that give unique integer values to each
46537 ** opcode and the opcodes.c file is filled with an array of strings where
46538 ** each string is the symbolic name for the corresponding opcode.  If the
46539 ** case statement is followed by a comment of the form "/# same as ... #/"
46540 ** that comment is used to determine the particular value of the opcode.
46541 **
46542 ** Other keywords in the comment that follows each case are used to
46543 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
46544 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
46545 ** the mkopcodeh.awk script for additional information.
46546 **
46547 ** Documentation about VDBE opcodes is generated by scanning this file
46548 ** for lines of that contain "Opcode:".  That line and all subsequent
46549 ** comment lines are used in the generation of the opcode.html documentation
46550 ** file.
46551 **
46552 ** SUMMARY:
46553 **
46554 **     Formatting is important to scripts that scan this file.
46555 **     Do not deviate from the formatting style currently in use.
46556 **
46557 *****************************************************************************/
46558
46559 /* Opcode:  Goto * P2 * * *
46560 **
46561 ** An unconditional jump to address P2.
46562 ** The next instruction executed will be 
46563 ** the one at index P2 from the beginning of
46564 ** the program.
46565 */
46566 case OP_Goto: {             /* jump */
46567   CHECK_FOR_INTERRUPT;
46568   pc = pOp->p2 - 1;
46569   break;
46570 }
46571
46572 /* Opcode:  Gosub P1 P2 * * *
46573 **
46574 ** Write the current address onto register P1
46575 ** and then jump to address P2.
46576 */
46577 case OP_Gosub: {            /* jump */
46578   assert( pOp->p1>0 );
46579   assert( pOp->p1<=p->nMem );
46580   pIn1 = &p->aMem[pOp->p1];
46581   assert( (pIn1->flags & MEM_Dyn)==0 );
46582   pIn1->flags = MEM_Int;
46583   pIn1->u.i = pc;
46584   REGISTER_TRACE(pOp->p1, pIn1);
46585   pc = pOp->p2 - 1;
46586   break;
46587 }
46588
46589 /* Opcode:  Return P1 * * * *
46590 **
46591 ** Jump to the next instruction after the address in register P1.
46592 */
46593 case OP_Return: {           /* in1 */
46594   assert( pIn1->flags & MEM_Int );
46595   pc = pIn1->u.i;
46596   break;
46597 }
46598
46599 /* Opcode:  Yield P1 * * * *
46600 **
46601 ** Swap the program counter with the value in register P1.
46602 */
46603 case OP_Yield: {
46604   int pcDest;
46605   assert( pOp->p1>0 );
46606   assert( pOp->p1<=p->nMem );
46607   pIn1 = &p->aMem[pOp->p1];
46608   assert( (pIn1->flags & MEM_Dyn)==0 );
46609   pIn1->flags = MEM_Int;
46610   pcDest = pIn1->u.i;
46611   pIn1->u.i = pc;
46612   REGISTER_TRACE(pOp->p1, pIn1);
46613   pc = pcDest;
46614   break;
46615 }
46616
46617
46618 /* Opcode:  Halt P1 P2 * P4 *
46619 **
46620 ** Exit immediately.  All open cursors, Fifos, etc are closed
46621 ** automatically.
46622 **
46623 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
46624 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
46625 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
46626 ** whether or not to rollback the current transaction.  Do not rollback
46627 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
46628 ** then back out all changes that have occurred during this execution of the
46629 ** VDBE, but do not rollback the transaction. 
46630 **
46631 ** If P4 is not null then it is an error message string.
46632 **
46633 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
46634 ** every program.  So a jump past the last instruction of the program
46635 ** is the same as executing Halt.
46636 */
46637 case OP_Halt: {
46638   p->rc = pOp->p1;
46639   p->pc = pc;
46640   p->errorAction = pOp->p2;
46641   if( pOp->p4.z ){
46642     sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
46643   }
46644   rc = sqlite3VdbeHalt(p);
46645   assert( rc==SQLITE_BUSY || rc==SQLITE_OK );
46646   if( rc==SQLITE_BUSY ){
46647     p->rc = rc = SQLITE_BUSY;
46648   }else{
46649     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
46650   }
46651   goto vdbe_return;
46652 }
46653
46654 /* Opcode: Integer P1 P2 * * *
46655 **
46656 ** The 32-bit integer value P1 is written into register P2.
46657 */
46658 case OP_Integer: {         /* out2-prerelease */
46659   pOut->flags = MEM_Int;
46660   pOut->u.i = pOp->p1;
46661   break;
46662 }
46663
46664 /* Opcode: Int64 * P2 * P4 *
46665 **
46666 ** P4 is a pointer to a 64-bit integer value.
46667 ** Write that value into register P2.
46668 */
46669 case OP_Int64: {           /* out2-prerelease */
46670   assert( pOp->p4.pI64!=0 );
46671   pOut->flags = MEM_Int;
46672   pOut->u.i = *pOp->p4.pI64;
46673   break;
46674 }
46675
46676 /* Opcode: Real * P2 * P4 *
46677 **
46678 ** P4 is a pointer to a 64-bit floating point value.
46679 ** Write that value into register P2.
46680 */
46681 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
46682   pOut->flags = MEM_Real;
46683   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
46684   pOut->r = *pOp->p4.pReal;
46685   break;
46686 }
46687
46688 /* Opcode: String8 * P2 * P4 *
46689 **
46690 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
46691 ** into an OP_String before it is executed for the first time.
46692 */
46693 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
46694   assert( pOp->p4.z!=0 );
46695   pOp->opcode = OP_String;
46696   pOp->p1 = strlen(pOp->p4.z);
46697
46698 #ifndef SQLITE_OMIT_UTF16
46699   if( encoding!=SQLITE_UTF8 ){
46700     sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
46701     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
46702     if( SQLITE_OK!=sqlite3VdbeMemMakeWriteable(pOut) ) goto no_mem;
46703     pOut->zMalloc = 0;
46704     pOut->flags |= MEM_Static;
46705     pOut->flags &= ~MEM_Dyn;
46706     if( pOp->p4type==P4_DYNAMIC ){
46707       sqlite3DbFree(db, pOp->p4.z);
46708     }
46709     pOp->p4type = P4_DYNAMIC;
46710     pOp->p4.z = pOut->z;
46711     pOp->p1 = pOut->n;
46712     if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
46713       goto too_big;
46714     }
46715     UPDATE_MAX_BLOBSIZE(pOut);
46716     break;
46717   }
46718 #endif
46719   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
46720     goto too_big;
46721   }
46722   /* Fall through to the next case, OP_String */
46723 }
46724   
46725 /* Opcode: String P1 P2 * P4 *
46726 **
46727 ** The string value P4 of length P1 (bytes) is stored in register P2.
46728 */
46729 case OP_String: {          /* out2-prerelease */
46730   assert( pOp->p4.z!=0 );
46731   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
46732   pOut->z = pOp->p4.z;
46733   pOut->n = pOp->p1;
46734   pOut->enc = encoding;
46735   UPDATE_MAX_BLOBSIZE(pOut);
46736   break;
46737 }
46738
46739 /* Opcode: Null * P2 * * *
46740 **
46741 ** Write a NULL into register P2.
46742 */
46743 case OP_Null: {           /* out2-prerelease */
46744   break;
46745 }
46746
46747
46748 #ifndef SQLITE_OMIT_BLOB_LITERAL
46749 /* Opcode: Blob P1 P2 * P4
46750 **
46751 ** P4 points to a blob of data P1 bytes long.  Store this
46752 ** blob in register P2. This instruction is not coded directly
46753 ** by the compiler. Instead, the compiler layer specifies
46754 ** an OP_HexBlob opcode, with the hex string representation of
46755 ** the blob as P4. This opcode is transformed to an OP_Blob
46756 ** the first time it is executed.
46757 */
46758 case OP_Blob: {                /* out2-prerelease */
46759   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
46760   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
46761   pOut->enc = encoding;
46762   UPDATE_MAX_BLOBSIZE(pOut);
46763   break;
46764 }
46765 #endif /* SQLITE_OMIT_BLOB_LITERAL */
46766
46767 /* Opcode: Variable P1 P2 * * *
46768 **
46769 ** The value of variable P1 is written into register P2. A variable is
46770 ** an unknown in the original SQL string as handed to sqlite3_compile().
46771 ** Any occurrence of the '?' character in the original SQL is considered
46772 ** a variable.  Variables in the SQL string are number from left to
46773 ** right beginning with 1.  The values of variables are set using the
46774 ** sqlite3_bind() API.
46775 */
46776 case OP_Variable: {           /* out2-prerelease */
46777   int j = pOp->p1 - 1;
46778   Mem *pVar;
46779   assert( j>=0 && j<p->nVar );
46780
46781   pVar = &p->aVar[j];
46782   if( sqlite3VdbeMemTooBig(pVar) ){
46783     goto too_big;
46784   }
46785   sqlite3VdbeMemShallowCopy(pOut, &p->aVar[j], MEM_Static);
46786   UPDATE_MAX_BLOBSIZE(pOut);
46787   break;
46788 }
46789
46790 /* Opcode: Move P1 P2 P3 * *
46791 **
46792 ** Move the values in register P1..P1+P3-1 over into
46793 ** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
46794 ** left holding a NULL.  It is an error for register ranges
46795 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
46796 */
46797 case OP_Move: {
46798   char *zMalloc;
46799   int n = pOp->p3;
46800   int p1 = pOp->p1;
46801   int p2 = pOp->p2;
46802   assert( n>0 );
46803   assert( p1>0 );
46804   assert( p1+n<p->nMem );
46805   pIn1 = &p->aMem[p1];
46806   assert( p2>0 );
46807   assert( p2+n<p->nMem );
46808   pOut = &p->aMem[p2];
46809   assert( p1+n<=p2 || p2+n<=p1 );
46810   while( n-- ){
46811     zMalloc = pOut->zMalloc;
46812     pOut->zMalloc = 0;
46813     sqlite3VdbeMemMove(pOut, pIn1);
46814     pIn1->zMalloc = zMalloc;
46815     REGISTER_TRACE(p2++, pOut);
46816     pIn1++;
46817     pOut++;
46818   }
46819   break;
46820 }
46821
46822 /* Opcode: Copy P1 P2 * * *
46823 **
46824 ** Make a copy of register P1 into register P2.
46825 **
46826 ** This instruction makes a deep copy of the value.  A duplicate
46827 ** is made of any string or blob constant.  See also OP_SCopy.
46828 */
46829 case OP_Copy: {
46830   assert( pOp->p1>0 );
46831   assert( pOp->p1<=p->nMem );
46832   pIn1 = &p->aMem[pOp->p1];
46833   assert( pOp->p2>0 );
46834   assert( pOp->p2<=p->nMem );
46835   pOut = &p->aMem[pOp->p2];
46836   assert( pOut!=pIn1 );
46837   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
46838   Deephemeralize(pOut);
46839   REGISTER_TRACE(pOp->p2, pOut);
46840   break;
46841 }
46842
46843 /* Opcode: SCopy P1 P2 * * *
46844 **
46845 ** Make a shallow copy of register P1 into register P2.
46846 **
46847 ** This instruction makes a shallow copy of the value.  If the value
46848 ** is a string or blob, then the copy is only a pointer to the
46849 ** original and hence if the original changes so will the copy.
46850 ** Worse, if the original is deallocated, the copy becomes invalid.
46851 ** Thus the program must guarantee that the original will not change
46852 ** during the lifetime of the copy.  Use OP_Copy to make a complete
46853 ** copy.
46854 */
46855 case OP_SCopy: {
46856   assert( pOp->p1>0 );
46857   assert( pOp->p1<=p->nMem );
46858   pIn1 = &p->aMem[pOp->p1];
46859   REGISTER_TRACE(pOp->p1, pIn1);
46860   assert( pOp->p2>0 );
46861   assert( pOp->p2<=p->nMem );
46862   pOut = &p->aMem[pOp->p2];
46863   assert( pOut!=pIn1 );
46864   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
46865   REGISTER_TRACE(pOp->p2, pOut);
46866   break;
46867 }
46868
46869 /* Opcode: ResultRow P1 P2 * * *
46870 **
46871 ** The registers P1 through P1+P2-1 contain a single row of
46872 ** results. This opcode causes the sqlite3_step() call to terminate
46873 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
46874 ** structure to provide access to the top P1 values as the result
46875 ** row.
46876 */
46877 case OP_ResultRow: {
46878   Mem *pMem;
46879   int i;
46880   assert( p->nResColumn==pOp->p2 );
46881   assert( pOp->p1>0 );
46882   assert( pOp->p1+pOp->p2<=p->nMem );
46883
46884   /* Invalidate all ephemeral cursor row caches */
46885   p->cacheCtr = (p->cacheCtr + 2)|1;
46886
46887   /* Make sure the results of the current row are \000 terminated
46888   ** and have an assigned type.  The results are de-ephemeralized as
46889   ** as side effect.
46890   */
46891   pMem = p->pResultSet = &p->aMem[pOp->p1];
46892   for(i=0; i<pOp->p2; i++){
46893     sqlite3VdbeMemNulTerminate(&pMem[i]);
46894     storeTypeInfo(&pMem[i], encoding);
46895     REGISTER_TRACE(pOp->p1+i, &pMem[i]);
46896   }
46897   if( db->mallocFailed ) goto no_mem;
46898
46899   /* Return SQLITE_ROW
46900   */
46901   p->nCallback++;
46902   p->pc = pc + 1;
46903   rc = SQLITE_ROW;
46904   goto vdbe_return;
46905 }
46906
46907 /* Opcode: Concat P1 P2 P3 * *
46908 **
46909 ** Add the text in register P1 onto the end of the text in
46910 ** register P2 and store the result in register P3.
46911 ** If either the P1 or P2 text are NULL then store NULL in P3.
46912 **
46913 **   P3 = P2 || P1
46914 **
46915 ** It is illegal for P1 and P3 to be the same register. Sometimes,
46916 ** if P3 is the same register as P2, the implementation is able
46917 ** to avoid a memcpy().
46918 */
46919 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
46920   i64 nByte;
46921
46922   assert( pIn1!=pOut );
46923   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
46924     sqlite3VdbeMemSetNull(pOut);
46925     break;
46926   }
46927   ExpandBlob(pIn1);
46928   Stringify(pIn1, encoding);
46929   ExpandBlob(pIn2);
46930   Stringify(pIn2, encoding);
46931   nByte = pIn1->n + pIn2->n;
46932   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
46933     goto too_big;
46934   }
46935   MemSetTypeFlag(pOut, MEM_Str);
46936   if( sqlite3VdbeMemGrow(pOut, nByte+2, pOut==pIn2) ){
46937     goto no_mem;
46938   }
46939   if( pOut!=pIn2 ){
46940     memcpy(pOut->z, pIn2->z, pIn2->n);
46941   }
46942   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
46943   pOut->z[nByte] = 0;
46944   pOut->z[nByte+1] = 0;
46945   pOut->flags |= MEM_Term;
46946   pOut->n = nByte;
46947   pOut->enc = encoding;
46948   UPDATE_MAX_BLOBSIZE(pOut);
46949   break;
46950 }
46951
46952 /* Opcode: Add P1 P2 P3 * *
46953 **
46954 ** Add the value in register P1 to the value in register P2
46955 ** and store the result in register P3.
46956 ** If either input is NULL, the result is NULL.
46957 */
46958 /* Opcode: Multiply P1 P2 P3 * *
46959 **
46960 **
46961 ** Multiply the value in register P1 by the value in register P2
46962 ** and store the result in register P3.
46963 ** If either input is NULL, the result is NULL.
46964 */
46965 /* Opcode: Subtract P1 P2 P3 * *
46966 **
46967 ** Subtract the value in register P1 from the value in register P2
46968 ** and store the result in register P3.
46969 ** If either input is NULL, the result is NULL.
46970 */
46971 /* Opcode: Divide P1 P2 P3 * *
46972 **
46973 ** Divide the value in register P1 by the value in register P2
46974 ** and store the result in register P3.  If the value in register P2
46975 ** is zero, then the result is NULL.
46976 ** If either input is NULL, the result is NULL.
46977 */
46978 /* Opcode: Remainder P1 P2 P3 * *
46979 **
46980 ** Compute the remainder after integer division of the value in
46981 ** register P1 by the value in register P2 and store the result in P3. 
46982 ** If the value in register P2 is zero the result is NULL.
46983 ** If either operand is NULL, the result is NULL.
46984 */
46985 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
46986 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
46987 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
46988 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
46989 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
46990   int flags;
46991   applyNumericAffinity(pIn1);
46992   applyNumericAffinity(pIn2);
46993   flags = pIn1->flags | pIn2->flags;
46994   if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
46995   if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
46996     i64 a, b;
46997     a = pIn1->u.i;
46998     b = pIn2->u.i;
46999     switch( pOp->opcode ){
47000       case OP_Add:         b += a;       break;
47001       case OP_Subtract:    b -= a;       break;
47002       case OP_Multiply:    b *= a;       break;
47003       case OP_Divide: {
47004         if( a==0 ) goto arithmetic_result_is_null;
47005         /* Dividing the largest possible negative 64-bit integer (1<<63) by 
47006         ** -1 returns an integer too large to store in a 64-bit data-type. On
47007         ** some architectures, the value overflows to (1<<63). On others,
47008         ** a SIGFPE is issued. The following statement normalizes this
47009         ** behavior so that all architectures behave as if integer 
47010         ** overflow occurred.
47011         */
47012         if( a==-1 && b==SMALLEST_INT64 ) a = 1;
47013         b /= a;
47014         break;
47015       }
47016       default: {
47017         if( a==0 ) goto arithmetic_result_is_null;
47018         if( a==-1 ) a = 1;
47019         b %= a;
47020         break;
47021       }
47022     }
47023     pOut->u.i = b;
47024     MemSetTypeFlag(pOut, MEM_Int);
47025   }else{
47026     double a, b;
47027     a = sqlite3VdbeRealValue(pIn1);
47028     b = sqlite3VdbeRealValue(pIn2);
47029     switch( pOp->opcode ){
47030       case OP_Add:         b += a;       break;
47031       case OP_Subtract:    b -= a;       break;
47032       case OP_Multiply:    b *= a;       break;
47033       case OP_Divide: {
47034         if( a==0.0 ) goto arithmetic_result_is_null;
47035         b /= a;
47036         break;
47037       }
47038       default: {
47039         i64 ia = (i64)a;
47040         i64 ib = (i64)b;
47041         if( ia==0 ) goto arithmetic_result_is_null;
47042         if( ia==-1 ) ia = 1;
47043         b = ib % ia;
47044         break;
47045       }
47046     }
47047     if( sqlite3IsNaN(b) ){
47048       goto arithmetic_result_is_null;
47049     }
47050     pOut->r = b;
47051     MemSetTypeFlag(pOut, MEM_Real);
47052     if( (flags & MEM_Real)==0 ){
47053       sqlite3VdbeIntegerAffinity(pOut);
47054     }
47055   }
47056   break;
47057
47058 arithmetic_result_is_null:
47059   sqlite3VdbeMemSetNull(pOut);
47060   break;
47061 }
47062
47063 /* Opcode: CollSeq * * P4
47064 **
47065 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
47066 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
47067 ** be returned. This is used by the built-in min(), max() and nullif()
47068 ** functions.
47069 **
47070 ** The interface used by the implementation of the aforementioned functions
47071 ** to retrieve the collation sequence set by this opcode is not available
47072 ** publicly, only to user functions defined in func.c.
47073 */
47074 case OP_CollSeq: {
47075   assert( pOp->p4type==P4_COLLSEQ );
47076   break;
47077 }
47078
47079 /* Opcode: Function P1 P2 P3 P4 P5
47080 **
47081 ** Invoke a user function (P4 is a pointer to a Function structure that
47082 ** defines the function) with P5 arguments taken from register P2 and
47083 ** successors.  The result of the function is stored in register P3.
47084 ** Register P3 must not be one of the function inputs.
47085 **
47086 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
47087 ** function was determined to be constant at compile time. If the first
47088 ** argument was constant then bit 0 of P1 is set. This is used to determine
47089 ** whether meta data associated with a user function argument using the
47090 ** sqlite3_set_auxdata() API may be safely retained until the next
47091 ** invocation of this opcode.
47092 **
47093 ** See also: AggStep and AggFinal
47094 */
47095 case OP_Function: {
47096   int i;
47097   Mem *pArg;
47098   sqlite3_context ctx;
47099   sqlite3_value **apVal;
47100   int n = pOp->p5;
47101
47102   apVal = p->apArg;
47103   assert( apVal || n==0 );
47104
47105   assert( n==0 || (pOp->p2>0 && pOp->p2+n<=p->nMem) );
47106   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
47107   pArg = &p->aMem[pOp->p2];
47108   for(i=0; i<n; i++, pArg++){
47109     apVal[i] = pArg;
47110     storeTypeInfo(pArg, encoding);
47111     REGISTER_TRACE(pOp->p2, pArg);
47112   }
47113
47114   assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
47115   if( pOp->p4type==P4_FUNCDEF ){
47116     ctx.pFunc = pOp->p4.pFunc;
47117     ctx.pVdbeFunc = 0;
47118   }else{
47119     ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
47120     ctx.pFunc = ctx.pVdbeFunc->pFunc;
47121   }
47122
47123   assert( pOp->p3>0 && pOp->p3<=p->nMem );
47124   pOut = &p->aMem[pOp->p3];
47125   ctx.s.flags = MEM_Null;
47126   ctx.s.db = db;
47127   ctx.s.xDel = 0;
47128   ctx.s.zMalloc = 0;
47129
47130   /* The output cell may already have a buffer allocated. Move
47131   ** the pointer to ctx.s so in case the user-function can use
47132   ** the already allocated buffer instead of allocating a new one.
47133   */
47134   sqlite3VdbeMemMove(&ctx.s, pOut);
47135   MemSetTypeFlag(&ctx.s, MEM_Null);
47136
47137   ctx.isError = 0;
47138   if( ctx.pFunc->needCollSeq ){
47139     assert( pOp>p->aOp );
47140     assert( pOp[-1].p4type==P4_COLLSEQ );
47141     assert( pOp[-1].opcode==OP_CollSeq );
47142     ctx.pColl = pOp[-1].p4.pColl;
47143   }
47144   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
47145   (*ctx.pFunc->xFunc)(&ctx, n, apVal);
47146   if( sqlite3SafetyOn(db) ){
47147     sqlite3VdbeMemRelease(&ctx.s);
47148     goto abort_due_to_misuse;
47149   }
47150   if( db->mallocFailed ){
47151     /* Even though a malloc() has failed, the implementation of the
47152     ** user function may have called an sqlite3_result_XXX() function
47153     ** to return a value. The following call releases any resources
47154     ** associated with such a value.
47155     **
47156     ** Note: Maybe MemRelease() should be called if sqlite3SafetyOn()
47157     ** fails also (the if(...) statement above). But if people are
47158     ** misusing sqlite, they have bigger problems than a leaked value.
47159     */
47160     sqlite3VdbeMemRelease(&ctx.s);
47161     goto no_mem;
47162   }
47163
47164   /* If any auxiliary data functions have been called by this user function,
47165   ** immediately call the destructor for any non-static values.
47166   */
47167   if( ctx.pVdbeFunc ){
47168     sqlite3VdbeDeleteAuxData(ctx.pVdbeFunc, pOp->p1);
47169     pOp->p4.pVdbeFunc = ctx.pVdbeFunc;
47170     pOp->p4type = P4_VDBEFUNC;
47171   }
47172
47173   /* If the function returned an error, throw an exception */
47174   if( ctx.isError ){
47175     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s));
47176     rc = ctx.isError;
47177   }
47178
47179   /* Copy the result of the function into register P3 */
47180   sqlite3VdbeChangeEncoding(&ctx.s, encoding);
47181   sqlite3VdbeMemMove(pOut, &ctx.s);
47182   if( sqlite3VdbeMemTooBig(pOut) ){
47183     goto too_big;
47184   }
47185   REGISTER_TRACE(pOp->p3, pOut);
47186   UPDATE_MAX_BLOBSIZE(pOut);
47187   break;
47188 }
47189
47190 /* Opcode: BitAnd P1 P2 P3 * *
47191 **
47192 ** Take the bit-wise AND of the values in register P1 and P2 and
47193 ** store the result in register P3.
47194 ** If either input is NULL, the result is NULL.
47195 */
47196 /* Opcode: BitOr P1 P2 P3 * *
47197 **
47198 ** Take the bit-wise OR of the values in register P1 and P2 and
47199 ** store the result in register P3.
47200 ** If either input is NULL, the result is NULL.
47201 */
47202 /* Opcode: ShiftLeft P1 P2 P3 * *
47203 **
47204 ** Shift the integer value in register P2 to the left by the
47205 ** number of bits specified by the integer in regiser P1.
47206 ** Store the result in register P3.
47207 ** If either input is NULL, the result is NULL.
47208 */
47209 /* Opcode: ShiftRight P1 P2 P3 * *
47210 **
47211 ** Shift the integer value in register P2 to the right by the
47212 ** number of bits specified by the integer in register P1.
47213 ** Store the result in register P3.
47214 ** If either input is NULL, the result is NULL.
47215 */
47216 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
47217 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
47218 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
47219 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
47220   i64 a, b;
47221
47222   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
47223     sqlite3VdbeMemSetNull(pOut);
47224     break;
47225   }
47226   a = sqlite3VdbeIntValue(pIn2);
47227   b = sqlite3VdbeIntValue(pIn1);
47228   switch( pOp->opcode ){
47229     case OP_BitAnd:      a &= b;     break;
47230     case OP_BitOr:       a |= b;     break;
47231     case OP_ShiftLeft:   a <<= b;    break;
47232     default:  assert( pOp->opcode==OP_ShiftRight );
47233                          a >>= b;    break;
47234   }
47235   pOut->u.i = a;
47236   MemSetTypeFlag(pOut, MEM_Int);
47237   break;
47238 }
47239
47240 /* Opcode: AddImm  P1 P2 * * *
47241 ** 
47242 ** Add the constant P2 to the value in register P1.
47243 ** The result is always an integer.
47244 **
47245 ** To force any register to be an integer, just add 0.
47246 */
47247 case OP_AddImm: {            /* in1 */
47248   sqlite3VdbeMemIntegerify(pIn1);
47249   pIn1->u.i += pOp->p2;
47250   break;
47251 }
47252
47253 /* Opcode: ForceInt P1 P2 P3 * *
47254 **
47255 ** Convert value in register P1 into an integer.  If the value 
47256 ** in P1 is not numeric (meaning that is is a NULL or a string that
47257 ** does not look like an integer or floating point number) then
47258 ** jump to P2.  If the value in P1 is numeric then
47259 ** convert it into the least integer that is greater than or equal to its
47260 ** current value if P3==0, or to the least integer that is strictly
47261 ** greater than its current value if P3==1.
47262 */
47263 case OP_ForceInt: {            /* jump, in1 */
47264   i64 v;
47265   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
47266   if( (pIn1->flags & (MEM_Int|MEM_Real))==0 ){
47267     pc = pOp->p2 - 1;
47268     break;
47269   }
47270   if( pIn1->flags & MEM_Int ){
47271     v = pIn1->u.i + (pOp->p3!=0);
47272   }else{
47273     assert( pIn1->flags & MEM_Real );
47274     v = (sqlite3_int64)pIn1->r;
47275     if( pIn1->r>(double)v ) v++;
47276     if( pOp->p3 && pIn1->r==(double)v ) v++;
47277   }
47278   pIn1->u.i = v;
47279   MemSetTypeFlag(pIn1, MEM_Int);
47280   break;
47281 }
47282
47283 /* Opcode: MustBeInt P1 P2 * * *
47284 ** 
47285 ** Force the value in register P1 to be an integer.  If the value
47286 ** in P1 is not an integer and cannot be converted into an integer
47287 ** without data loss, then jump immediately to P2, or if P2==0
47288 ** raise an SQLITE_MISMATCH exception.
47289 */
47290 case OP_MustBeInt: {            /* jump, in1 */
47291   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
47292   if( (pIn1->flags & MEM_Int)==0 ){
47293     if( pOp->p2==0 ){
47294       rc = SQLITE_MISMATCH;
47295       goto abort_due_to_error;
47296     }else{
47297       pc = pOp->p2 - 1;
47298     }
47299   }else{
47300     MemSetTypeFlag(pIn1, MEM_Int);
47301   }
47302   break;
47303 }
47304
47305 /* Opcode: RealAffinity P1 * * * *
47306 **
47307 ** If register P1 holds an integer convert it to a real value.
47308 **
47309 ** This opcode is used when extracting information from a column that
47310 ** has REAL affinity.  Such column values may still be stored as
47311 ** integers, for space efficiency, but after extraction we want them
47312 ** to have only a real value.
47313 */
47314 case OP_RealAffinity: {                  /* in1 */
47315   if( pIn1->flags & MEM_Int ){
47316     sqlite3VdbeMemRealify(pIn1);
47317   }
47318   break;
47319 }
47320
47321 #ifndef SQLITE_OMIT_CAST
47322 /* Opcode: ToText P1 * * * *
47323 **
47324 ** Force the value in register P1 to be text.
47325 ** If the value is numeric, convert it to a string using the
47326 ** equivalent of printf().  Blob values are unchanged and
47327 ** are afterwards simply interpreted as text.
47328 **
47329 ** A NULL value is not changed by this routine.  It remains NULL.
47330 */
47331 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
47332   if( pIn1->flags & MEM_Null ) break;
47333   assert( MEM_Str==(MEM_Blob>>3) );
47334   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
47335   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
47336   rc = ExpandBlob(pIn1);
47337   assert( pIn1->flags & MEM_Str || db->mallocFailed );
47338   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob);
47339   UPDATE_MAX_BLOBSIZE(pIn1);
47340   break;
47341 }
47342
47343 /* Opcode: ToBlob P1 * * * *
47344 **
47345 ** Force the value in register P1 to be a BLOB.
47346 ** If the value is numeric, convert it to a string first.
47347 ** Strings are simply reinterpreted as blobs with no change
47348 ** to the underlying data.
47349 **
47350 ** A NULL value is not changed by this routine.  It remains NULL.
47351 */
47352 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
47353   if( pIn1->flags & MEM_Null ) break;
47354   if( (pIn1->flags & MEM_Blob)==0 ){
47355     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
47356     assert( pIn1->flags & MEM_Str || db->mallocFailed );
47357   }
47358   MemSetTypeFlag(pIn1, MEM_Blob);
47359   UPDATE_MAX_BLOBSIZE(pIn1);
47360   break;
47361 }
47362
47363 /* Opcode: ToNumeric P1 * * * *
47364 **
47365 ** Force the value in register P1 to be numeric (either an
47366 ** integer or a floating-point number.)
47367 ** If the value is text or blob, try to convert it to an using the
47368 ** equivalent of atoi() or atof() and store 0 if no such conversion 
47369 ** is possible.
47370 **
47371 ** A NULL value is not changed by this routine.  It remains NULL.
47372 */
47373 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
47374   if( (pIn1->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
47375     sqlite3VdbeMemNumerify(pIn1);
47376   }
47377   break;
47378 }
47379 #endif /* SQLITE_OMIT_CAST */
47380
47381 /* Opcode: ToInt P1 * * * *
47382 **
47383 ** Force the value in register P1 be an integer.  If
47384 ** The value is currently a real number, drop its fractional part.
47385 ** If the value is text or blob, try to convert it to an integer using the
47386 ** equivalent of atoi() and store 0 if no such conversion is possible.
47387 **
47388 ** A NULL value is not changed by this routine.  It remains NULL.
47389 */
47390 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
47391   if( (pIn1->flags & MEM_Null)==0 ){
47392     sqlite3VdbeMemIntegerify(pIn1);
47393   }
47394   break;
47395 }
47396
47397 #ifndef SQLITE_OMIT_CAST
47398 /* Opcode: ToReal P1 * * * *
47399 **
47400 ** Force the value in register P1 to be a floating point number.
47401 ** If The value is currently an integer, convert it.
47402 ** If the value is text or blob, try to convert it to an integer using the
47403 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
47404 **
47405 ** A NULL value is not changed by this routine.  It remains NULL.
47406 */
47407 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
47408   if( (pIn1->flags & MEM_Null)==0 ){
47409     sqlite3VdbeMemRealify(pIn1);
47410   }
47411   break;
47412 }
47413 #endif /* SQLITE_OMIT_CAST */
47414
47415 /* Opcode: Lt P1 P2 P3 P4 P5
47416 **
47417 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
47418 ** jump to address P2.  
47419 **
47420 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
47421 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL 
47422 ** bit is clear then fall thru if either operand is NULL.
47423 **
47424 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
47425 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
47426 ** to coerce both inputs according to this affinity before the
47427 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
47428 ** affinity is used. Note that the affinity conversions are stored
47429 ** back into the input registers P1 and P3.  So this opcode can cause
47430 ** persistent changes to registers P1 and P3.
47431 **
47432 ** Once any conversions have taken place, and neither value is NULL, 
47433 ** the values are compared. If both values are blobs then memcmp() is
47434 ** used to determine the results of the comparison.  If both values
47435 ** are text, then the appropriate collating function specified in
47436 ** P4 is  used to do the comparison.  If P4 is not specified then
47437 ** memcmp() is used to compare text string.  If both values are
47438 ** numeric, then a numeric comparison is used. If the two values
47439 ** are of different types, then numbers are considered less than
47440 ** strings and strings are considered less than blobs.
47441 **
47442 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
47443 ** store a boolean result (either 0, or 1, or NULL) in register P2.
47444 */
47445 /* Opcode: Ne P1 P2 P3 P4 P5
47446 **
47447 ** This works just like the Lt opcode except that the jump is taken if
47448 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
47449 ** additional information.
47450 */
47451 /* Opcode: Eq P1 P2 P3 P4 P5
47452 **
47453 ** This works just like the Lt opcode except that the jump is taken if
47454 ** the operands in registers P1 and P3 are equal.
47455 ** See the Lt opcode for additional information.
47456 */
47457 /* Opcode: Le P1 P2 P3 P4 P5
47458 **
47459 ** This works just like the Lt opcode except that the jump is taken if
47460 ** the content of register P3 is less than or equal to the content of
47461 ** register P1.  See the Lt opcode for additional information.
47462 */
47463 /* Opcode: Gt P1 P2 P3 P4 P5
47464 **
47465 ** This works just like the Lt opcode except that the jump is taken if
47466 ** the content of register P3 is greater than the content of
47467 ** register P1.  See the Lt opcode for additional information.
47468 */
47469 /* Opcode: Ge P1 P2 P3 P4 P5
47470 **
47471 ** This works just like the Lt opcode except that the jump is taken if
47472 ** the content of register P3 is greater than or equal to the content of
47473 ** register P1.  See the Lt opcode for additional information.
47474 */
47475 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
47476 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
47477 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
47478 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
47479 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
47480 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
47481   int flags;
47482   int res;
47483   char affinity;
47484
47485   flags = pIn1->flags|pIn3->flags;
47486
47487   if( flags&MEM_Null ){
47488     /* If either operand is NULL then the result is always NULL.
47489     ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
47490     */
47491     if( pOp->p5 & SQLITE_STOREP2 ){
47492       pOut = &p->aMem[pOp->p2];
47493       MemSetTypeFlag(pOut, MEM_Null);
47494       REGISTER_TRACE(pOp->p2, pOut);
47495     }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
47496       pc = pOp->p2-1;
47497     }
47498     break;
47499   }
47500
47501   affinity = pOp->p5 & SQLITE_AFF_MASK;
47502   if( affinity ){
47503     applyAffinity(pIn1, affinity, encoding);
47504     applyAffinity(pIn3, affinity, encoding);
47505   }
47506
47507   assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
47508   ExpandBlob(pIn1);
47509   ExpandBlob(pIn3);
47510   res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
47511   switch( pOp->opcode ){
47512     case OP_Eq:    res = res==0;     break;
47513     case OP_Ne:    res = res!=0;     break;
47514     case OP_Lt:    res = res<0;      break;
47515     case OP_Le:    res = res<=0;     break;
47516     case OP_Gt:    res = res>0;      break;
47517     default:       res = res>=0;     break;
47518   }
47519
47520   if( pOp->p5 & SQLITE_STOREP2 ){
47521     pOut = &p->aMem[pOp->p2];
47522     MemSetTypeFlag(pOut, MEM_Int);
47523     pOut->u.i = res;
47524     REGISTER_TRACE(pOp->p2, pOut);
47525   }else if( res ){
47526     pc = pOp->p2-1;
47527   }
47528   break;
47529 }
47530
47531 /* Opcode: Permutation * * * P4 *
47532 **
47533 ** Set the permuation used by the OP_Compare operator to be the array
47534 ** of integers in P4.
47535 **
47536 ** The permutation is only valid until the next OP_Permutation, OP_Compare,
47537 ** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
47538 ** immediately prior to the OP_Compare.
47539 */
47540 case OP_Permutation: {
47541   assert( pOp->p4type==P4_INTARRAY );
47542   assert( pOp->p4.ai );
47543   aPermute = pOp->p4.ai;
47544   break;
47545 }
47546
47547 /* Opcode: Compare P1 P2 P3 P4 *
47548 **
47549 ** Compare to vectors of registers in reg(P1)..reg(P1+P3-1) (all this
47550 ** one "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
47551 ** the comparison for use by the next OP_Jump instruct.
47552 **
47553 ** P4 is a KeyInfo structure that defines collating sequences and sort
47554 ** orders for the comparison.  The permutation applies to registers
47555 ** only.  The KeyInfo elements are used sequentially.
47556 **
47557 ** The comparison is a sort comparison, so NULLs compare equal,
47558 ** NULLs are less than numbers, numbers are less than strings,
47559 ** and strings are less than blobs.
47560 */
47561 case OP_Compare: {
47562   int n = pOp->p3;
47563   int i, p1, p2;
47564   const KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
47565   assert( n>0 );
47566   assert( pKeyInfo!=0 );
47567   p1 = pOp->p1;
47568   assert( p1>0 && p1+n-1<p->nMem );
47569   p2 = pOp->p2;
47570   assert( p2>0 && p2+n-1<p->nMem );
47571   for(i=0; i<n; i++){
47572     int idx = aPermute ? aPermute[i] : i;
47573     CollSeq *pColl;    /* Collating sequence to use on this term */
47574     int bRev;          /* True for DESCENDING sort order */
47575     REGISTER_TRACE(p1+idx, &p->aMem[p1+idx]);
47576     REGISTER_TRACE(p2+idx, &p->aMem[p2+idx]);
47577     assert( i<pKeyInfo->nField );
47578     pColl = pKeyInfo->aColl[i];
47579     bRev = pKeyInfo->aSortOrder[i];
47580     iCompare = sqlite3MemCompare(&p->aMem[p1+idx], &p->aMem[p2+idx], pColl);
47581     if( iCompare ){
47582       if( bRev ) iCompare = -iCompare;
47583       break;
47584     }
47585   }
47586   aPermute = 0;
47587   break;
47588 }
47589
47590 /* Opcode: Jump P1 P2 P3 * *
47591 **
47592 ** Jump to the instruction at address P1, P2, or P3 depending on whether
47593 ** in the most recent OP_Compare instruction the P1 vector was less than
47594 ** equal to, or greater than the P2 vector, respectively.
47595 */
47596 case OP_Jump: {             /* jump */
47597   if( iCompare<0 ){
47598     pc = pOp->p1 - 1;
47599   }else if( iCompare==0 ){
47600     pc = pOp->p2 - 1;
47601   }else{
47602     pc = pOp->p3 - 1;
47603   }
47604   break;
47605 }
47606
47607 /* Opcode: And P1 P2 P3 * *
47608 **
47609 ** Take the logical AND of the values in registers P1 and P2 and
47610 ** write the result into register P3.
47611 **
47612 ** If either P1 or P2 is 0 (false) then the result is 0 even if
47613 ** the other input is NULL.  A NULL and true or two NULLs give
47614 ** a NULL output.
47615 */
47616 /* Opcode: Or P1 P2 P3 * *
47617 **
47618 ** Take the logical OR of the values in register P1 and P2 and
47619 ** store the answer in register P3.
47620 **
47621 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
47622 ** even if the other input is NULL.  A NULL and false or two NULLs
47623 ** give a NULL output.
47624 */
47625 case OP_And:              /* same as TK_AND, in1, in2, out3 */
47626 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
47627   int v1, v2;    /* 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
47628
47629   if( pIn1->flags & MEM_Null ){
47630     v1 = 2;
47631   }else{
47632     v1 = sqlite3VdbeIntValue(pIn1)!=0;
47633   }
47634   if( pIn2->flags & MEM_Null ){
47635     v2 = 2;
47636   }else{
47637     v2 = sqlite3VdbeIntValue(pIn2)!=0;
47638   }
47639   if( pOp->opcode==OP_And ){
47640     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
47641     v1 = and_logic[v1*3+v2];
47642   }else{
47643     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
47644     v1 = or_logic[v1*3+v2];
47645   }
47646   if( v1==2 ){
47647     MemSetTypeFlag(pOut, MEM_Null);
47648   }else{
47649     pOut->u.i = v1;
47650     MemSetTypeFlag(pOut, MEM_Int);
47651   }
47652   break;
47653 }
47654
47655 /* Opcode: Not P1 * * * *
47656 **
47657 ** Interpret the value in register P1 as a boolean value.  Replace it
47658 ** with its complement.  If the value in register P1 is NULL its value
47659 ** is unchanged.
47660 */
47661 case OP_Not: {                /* same as TK_NOT, in1 */
47662   if( pIn1->flags & MEM_Null ) break;  /* Do nothing to NULLs */
47663   sqlite3VdbeMemIntegerify(pIn1);
47664   pIn1->u.i = !pIn1->u.i;
47665   assert( pIn1->flags&MEM_Int );
47666   break;
47667 }
47668
47669 /* Opcode: BitNot P1 * * * *
47670 **
47671 ** Interpret the content of register P1 as an integer.  Replace it
47672 ** with its ones-complement.  If the value is originally NULL, leave
47673 ** it unchanged.
47674 */
47675 case OP_BitNot: {             /* same as TK_BITNOT, in1 */
47676   if( pIn1->flags & MEM_Null ) break;  /* Do nothing to NULLs */
47677   sqlite3VdbeMemIntegerify(pIn1);
47678   pIn1->u.i = ~pIn1->u.i;
47679   assert( pIn1->flags&MEM_Int );
47680   break;
47681 }
47682
47683 /* Opcode: If P1 P2 P3 * *
47684 **
47685 ** Jump to P2 if the value in register P1 is true.  The value is
47686 ** is considered true if it is numeric and non-zero.  If the value
47687 ** in P1 is NULL then take the jump if P3 is true.
47688 */
47689 /* Opcode: IfNot P1 P2 P3 * *
47690 **
47691 ** Jump to P2 if the value in register P1 is False.  The value is
47692 ** is considered true if it has a numeric value of zero.  If the value
47693 ** in P1 is NULL then take the jump if P3 is true.
47694 */
47695 case OP_If:                 /* jump, in1 */
47696 case OP_IfNot: {            /* jump, in1 */
47697   int c;
47698   if( pIn1->flags & MEM_Null ){
47699     c = pOp->p3;
47700   }else{
47701 #ifdef SQLITE_OMIT_FLOATING_POINT
47702     c = sqlite3VdbeIntValue(pIn1);
47703 #else
47704     c = sqlite3VdbeRealValue(pIn1)!=0.0;
47705 #endif
47706     if( pOp->opcode==OP_IfNot ) c = !c;
47707   }
47708   if( c ){
47709     pc = pOp->p2-1;
47710   }
47711   break;
47712 }
47713
47714 /* Opcode: IsNull P1 P2 P3 * *
47715 **
47716 ** Jump to P2 if the value in register P1 is NULL.  If P3 is greater
47717 ** than zero, then check all values reg(P1), reg(P1+1), 
47718 ** reg(P1+2), ..., reg(P1+P3-1).
47719 */
47720 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
47721   int n = pOp->p3;
47722   assert( pOp->p3==0 || pOp->p1>0 );
47723   do{
47724     if( (pIn1->flags & MEM_Null)!=0 ){
47725       pc = pOp->p2 - 1;
47726       break;
47727     }
47728     pIn1++;
47729   }while( --n > 0 );
47730   break;
47731 }
47732
47733 /* Opcode: NotNull P1 P2 * * *
47734 **
47735 ** Jump to P2 if the value in register P1 is not NULL.  
47736 */
47737 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
47738   if( (pIn1->flags & MEM_Null)==0 ){
47739     pc = pOp->p2 - 1;
47740   }
47741   break;
47742 }
47743
47744 /* Opcode: SetNumColumns * P2 * * *
47745 **
47746 ** This opcode sets the number of columns for the cursor opened by the
47747 ** following instruction to P2.
47748 **
47749 ** An OP_SetNumColumns is only useful if it occurs immediately before 
47750 ** one of the following opcodes:
47751 **
47752 **     OpenRead
47753 **     OpenWrite
47754 **     OpenPseudo
47755 **
47756 ** If the OP_Column opcode is to be executed on a cursor, then
47757 ** this opcode must be present immediately before the opcode that
47758 ** opens the cursor.
47759 */
47760 case OP_SetNumColumns: {
47761   break;
47762 }
47763
47764 /* Opcode: Column P1 P2 P3 P4 *
47765 **
47766 ** Interpret the data that cursor P1 points to as a structure built using
47767 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
47768 ** information about the format of the data.)  Extract the P2-th column
47769 ** from this record.  If there are less that (P2+1) 
47770 ** values in the record, extract a NULL.
47771 **
47772 ** The value extracted is stored in register P3.
47773 **
47774 ** If the KeyAsData opcode has previously executed on this cursor, then the
47775 ** field might be extracted from the key rather than the data.
47776 **
47777 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
47778 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
47779 ** the result.
47780 */
47781 case OP_Column: {
47782   u32 payloadSize;   /* Number of bytes in the record */
47783   int p1 = pOp->p1;  /* P1 value of the opcode */
47784   int p2 = pOp->p2;  /* column number to retrieve */
47785   Cursor *pC = 0;    /* The VDBE cursor */
47786   char *zRec;        /* Pointer to complete record-data */
47787   BtCursor *pCrsr;   /* The BTree cursor */
47788   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
47789   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
47790   u32 nField;        /* number of fields in the record */
47791   int len;           /* The length of the serialized data for the column */
47792   int i;             /* Loop counter */
47793   char *zData;       /* Part of the record being decoded */
47794   Mem *pDest;        /* Where to write the extracted value */
47795   Mem sMem;          /* For storing the record being decoded */
47796
47797   sMem.flags = 0;
47798   sMem.db = 0;
47799   sMem.zMalloc = 0;
47800   assert( p1<p->nCursor );
47801   assert( pOp->p3>0 && pOp->p3<=p->nMem );
47802   pDest = &p->aMem[pOp->p3];
47803   MemSetTypeFlag(pDest, MEM_Null);
47804
47805   /* This block sets the variable payloadSize to be the total number of
47806   ** bytes in the record.
47807   **
47808   ** zRec is set to be the complete text of the record if it is available.
47809   ** The complete record text is always available for pseudo-tables
47810   ** If the record is stored in a cursor, the complete record text
47811   ** might be available in the  pC->aRow cache.  Or it might not be.
47812   ** If the data is unavailable,  zRec is set to NULL.
47813   **
47814   ** We also compute the number of columns in the record.  For cursors,
47815   ** the number of columns is stored in the Cursor.nField element.
47816   */
47817   pC = p->apCsr[p1];
47818   assert( pC!=0 );
47819 #ifndef SQLITE_OMIT_VIRTUALTABLE
47820   assert( pC->pVtabCursor==0 );
47821 #endif
47822   if( pC->pCursor!=0 ){
47823     /* The record is stored in a B-Tree */
47824     rc = sqlite3VdbeCursorMoveto(pC);
47825     if( rc ) goto abort_due_to_error;
47826     zRec = 0;
47827     pCrsr = pC->pCursor;
47828     if( pC->nullRow ){
47829       payloadSize = 0;
47830     }else if( pC->cacheStatus==p->cacheCtr ){
47831       payloadSize = pC->payloadSize;
47832       zRec = (char*)pC->aRow;
47833     }else if( pC->isIndex ){
47834       i64 payloadSize64;
47835       sqlite3BtreeKeySize(pCrsr, &payloadSize64);
47836       payloadSize = payloadSize64;
47837     }else{
47838       sqlite3BtreeDataSize(pCrsr, &payloadSize);
47839     }
47840     nField = pC->nField;
47841   }else{
47842     assert( pC->pseudoTable );
47843     /* The record is the sole entry of a pseudo-table */
47844     payloadSize = pC->nData;
47845     zRec = pC->pData;
47846     pC->cacheStatus = CACHE_STALE;
47847     assert( payloadSize==0 || zRec!=0 );
47848     nField = pC->nField;
47849     pCrsr = 0;
47850   }
47851
47852   /* If payloadSize is 0, then just store a NULL */
47853   if( payloadSize==0 ){
47854     assert( pDest->flags&MEM_Null );
47855     goto op_column_out;
47856   }
47857   if( payloadSize>db->aLimit[SQLITE_LIMIT_LENGTH] ){
47858     goto too_big;
47859   }
47860
47861   assert( p2<nField );
47862
47863   /* Read and parse the table header.  Store the results of the parse
47864   ** into the record header cache fields of the cursor.
47865   */
47866   aType = pC->aType;
47867   if( pC->cacheStatus==p->cacheCtr ){
47868     aOffset = pC->aOffset;
47869   }else{
47870     u8 *zIdx;        /* Index into header */
47871     u8 *zEndHdr;     /* Pointer to first byte after the header */
47872     u32 offset;      /* Offset into the data */
47873     int szHdrSz;     /* Size of the header size field at start of record */
47874     int avail;       /* Number of bytes of available data */
47875
47876     assert(aType);
47877     pC->aOffset = aOffset = &aType[nField];
47878     pC->payloadSize = payloadSize;
47879     pC->cacheStatus = p->cacheCtr;
47880
47881     /* Figure out how many bytes are in the header */
47882     if( zRec ){
47883       zData = zRec;
47884     }else{
47885       if( pC->isIndex ){
47886         zData = (char*)sqlite3BtreeKeyFetch(pCrsr, &avail);
47887       }else{
47888         zData = (char*)sqlite3BtreeDataFetch(pCrsr, &avail);
47889       }
47890       /* If KeyFetch()/DataFetch() managed to get the entire payload,
47891       ** save the payload in the pC->aRow cache.  That will save us from
47892       ** having to make additional calls to fetch the content portion of
47893       ** the record.
47894       */
47895       if( avail>=payloadSize ){
47896         zRec = zData;
47897         pC->aRow = (u8*)zData;
47898       }else{
47899         pC->aRow = 0;
47900       }
47901     }
47902     /* The following assert is true in all cases accept when
47903     ** the database file has been corrupted externally.
47904     **    assert( zRec!=0 || avail>=payloadSize || avail>=9 ); */
47905     szHdrSz = getVarint32((u8*)zData, offset);
47906
47907     /* The KeyFetch() or DataFetch() above are fast and will get the entire
47908     ** record header in most cases.  But they will fail to get the complete
47909     ** record header if the record header does not fit on a single page
47910     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
47911     ** acquire the complete header text.
47912     */
47913     if( !zRec && avail<offset ){
47914       sMem.flags = 0;
47915       sMem.db = 0;
47916       rc = sqlite3VdbeMemFromBtree(pCrsr, 0, offset, pC->isIndex, &sMem);
47917       if( rc!=SQLITE_OK ){
47918         goto op_column_out;
47919       }
47920       zData = sMem.z;
47921     }
47922     zEndHdr = (u8 *)&zData[offset];
47923     zIdx = (u8 *)&zData[szHdrSz];
47924
47925     /* Scan the header and use it to fill in the aType[] and aOffset[]
47926     ** arrays.  aType[i] will contain the type integer for the i-th
47927     ** column and aOffset[i] will contain the offset from the beginning
47928     ** of the record to the start of the data for the i-th column
47929     */
47930     for(i=0; i<nField; i++){
47931       if( zIdx<zEndHdr ){
47932         aOffset[i] = offset;
47933         zIdx += getVarint32(zIdx, aType[i]);
47934         offset += sqlite3VdbeSerialTypeLen(aType[i]);
47935       }else{
47936         /* If i is less that nField, then there are less fields in this
47937         ** record than SetNumColumns indicated there are columns in the
47938         ** table. Set the offset for any extra columns not present in
47939         ** the record to 0. This tells code below to store a NULL
47940         ** instead of deserializing a value from the record.
47941         */
47942         aOffset[i] = 0;
47943       }
47944     }
47945     sqlite3VdbeMemRelease(&sMem);
47946     sMem.flags = MEM_Null;
47947
47948     /* If we have read more header data than was contained in the header,
47949     ** or if the end of the last field appears to be past the end of the
47950     ** record, or if the end of the last field appears to be before the end
47951     ** of the record (when all fields present), then we must be dealing 
47952     ** with a corrupt database.
47953     */
47954     if( zIdx>zEndHdr || offset>payloadSize 
47955      || (zIdx==zEndHdr && offset!=payloadSize) ){
47956       rc = SQLITE_CORRUPT_BKPT;
47957       goto op_column_out;
47958     }
47959   }
47960
47961   /* Get the column information. If aOffset[p2] is non-zero, then 
47962   ** deserialize the value from the record. If aOffset[p2] is zero,
47963   ** then there are not enough fields in the record to satisfy the
47964   ** request.  In this case, set the value NULL or to P4 if P4 is
47965   ** a pointer to a Mem object.
47966   */
47967   if( aOffset[p2] ){
47968     assert( rc==SQLITE_OK );
47969     if( zRec ){
47970       sqlite3VdbeMemReleaseExternal(pDest);
47971       sqlite3VdbeSerialGet((u8 *)&zRec[aOffset[p2]], aType[p2], pDest);
47972     }else{
47973       len = sqlite3VdbeSerialTypeLen(aType[p2]);
47974       sqlite3VdbeMemMove(&sMem, pDest);
47975       rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, pC->isIndex, &sMem);
47976       if( rc!=SQLITE_OK ){
47977         goto op_column_out;
47978       }
47979       zData = sMem.z;
47980       sqlite3VdbeSerialGet((u8*)zData, aType[p2], pDest);
47981     }
47982     pDest->enc = encoding;
47983   }else{
47984     if( pOp->p4type==P4_MEM ){
47985       sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
47986     }else{
47987       assert( pDest->flags&MEM_Null );
47988     }
47989   }
47990
47991   /* If we dynamically allocated space to hold the data (in the
47992   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
47993   ** dynamically allocated space over to the pDest structure.
47994   ** This prevents a memory copy.
47995   */
47996   if( sMem.zMalloc ){
47997     assert( sMem.z==sMem.zMalloc );
47998     assert( !(pDest->flags & MEM_Dyn) );
47999     assert( !(pDest->flags & (MEM_Blob|MEM_Str)) || pDest->z==sMem.z );
48000     pDest->flags &= ~(MEM_Ephem|MEM_Static);
48001     pDest->flags |= MEM_Term;
48002     pDest->z = sMem.z;
48003     pDest->zMalloc = sMem.zMalloc;
48004   }
48005
48006   rc = sqlite3VdbeMemMakeWriteable(pDest);
48007
48008 op_column_out:
48009   UPDATE_MAX_BLOBSIZE(pDest);
48010   REGISTER_TRACE(pOp->p3, pDest);
48011   break;
48012 }
48013
48014 /* Opcode: Affinity P1 P2 * P4 *
48015 **
48016 ** Apply affinities to a range of P2 registers starting with P1.
48017 **
48018 ** P4 is a string that is P2 characters long. The nth character of the
48019 ** string indicates the column affinity that should be used for the nth
48020 ** memory cell in the range.
48021 */
48022 case OP_Affinity: {
48023   char *zAffinity = pOp->p4.z;
48024   Mem *pData0 = &p->aMem[pOp->p1];
48025   Mem *pLast = &pData0[pOp->p2-1];
48026   Mem *pRec;
48027
48028   for(pRec=pData0; pRec<=pLast; pRec++){
48029     ExpandBlob(pRec);
48030     applyAffinity(pRec, zAffinity[pRec-pData0], encoding);
48031   }
48032   break;
48033 }
48034
48035 /* Opcode: MakeRecord P1 P2 P3 P4 *
48036 **
48037 ** Convert P2 registers beginning with P1 into a single entry
48038 ** suitable for use as a data record in a database table or as a key
48039 ** in an index.  The details of the format are irrelevant as long as
48040 ** the OP_Column opcode can decode the record later.
48041 ** Refer to source code comments for the details of the record
48042 ** format.
48043 **
48044 ** P4 may be a string that is P2 characters long.  The nth character of the
48045 ** string indicates the column affinity that should be used for the nth
48046 ** field of the index key.
48047 **
48048 ** The mapping from character to affinity is given by the SQLITE_AFF_
48049 ** macros defined in sqliteInt.h.
48050 **
48051 ** If P4 is NULL then all index fields have the affinity NONE.
48052 */
48053 case OP_MakeRecord: {
48054   /* Assuming the record contains N fields, the record format looks
48055   ** like this:
48056   **
48057   ** ------------------------------------------------------------------------
48058   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 | 
48059   ** ------------------------------------------------------------------------
48060   **
48061   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
48062   ** and so froth.
48063   **
48064   ** Each type field is a varint representing the serial type of the 
48065   ** corresponding data element (see sqlite3VdbeSerialType()). The
48066   ** hdr-size field is also a varint which is the offset from the beginning
48067   ** of the record to data0.
48068   */
48069   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
48070   Mem *pRec;             /* The new record */
48071   u64 nData = 0;         /* Number of bytes of data space */
48072   int nHdr = 0;          /* Number of bytes of header space */
48073   u64 nByte = 0;         /* Data space required for this record */
48074   int nZero = 0;         /* Number of zero bytes at the end of the record */
48075   int nVarint;           /* Number of bytes in a varint */
48076   u32 serial_type;       /* Type field */
48077   Mem *pData0;           /* First field to be combined into the record */
48078   Mem *pLast;            /* Last field of the record */
48079   int nField;            /* Number of fields in the record */
48080   char *zAffinity;       /* The affinity string for the record */
48081   int file_format;       /* File format to use for encoding */
48082   int i;                 /* Space used in zNewRecord[] */
48083
48084   nField = pOp->p1;
48085   zAffinity = pOp->p4.z;
48086   assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=p->nMem );
48087   pData0 = &p->aMem[nField];
48088   nField = pOp->p2;
48089   pLast = &pData0[nField-1];
48090   file_format = p->minWriteFileFormat;
48091
48092   /* Loop through the elements that will make up the record to figure
48093   ** out how much space is required for the new record.
48094   */
48095   for(pRec=pData0; pRec<=pLast; pRec++){
48096     int len;
48097     if( zAffinity ){
48098       applyAffinity(pRec, zAffinity[pRec-pData0], encoding);
48099     }
48100     if( pRec->flags&MEM_Zero && pRec->n>0 ){
48101       sqlite3VdbeMemExpandBlob(pRec);
48102     }
48103     serial_type = sqlite3VdbeSerialType(pRec, file_format);
48104     len = sqlite3VdbeSerialTypeLen(serial_type);
48105     nData += len;
48106     nHdr += sqlite3VarintLen(serial_type);
48107     if( pRec->flags & MEM_Zero ){
48108       /* Only pure zero-filled BLOBs can be input to this Opcode.
48109       ** We do not allow blobs with a prefix and a zero-filled tail. */
48110       nZero += pRec->u.i;
48111     }else if( len ){
48112       nZero = 0;
48113     }
48114   }
48115
48116   /* Add the initial header varint and total the size */
48117   nHdr += nVarint = sqlite3VarintLen(nHdr);
48118   if( nVarint<sqlite3VarintLen(nHdr) ){
48119     nHdr++;
48120   }
48121   nByte = nHdr+nData-nZero;
48122   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
48123     goto too_big;
48124   }
48125
48126   /* Make sure the output register has a buffer large enough to store 
48127   ** the new record. The output register (pOp->p3) is not allowed to
48128   ** be one of the input registers (because the following call to
48129   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
48130   */
48131   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
48132   pOut = &p->aMem[pOp->p3];
48133   if( sqlite3VdbeMemGrow(pOut, nByte, 0) ){
48134     goto no_mem;
48135   }
48136   zNewRecord = (u8 *)pOut->z;
48137
48138   /* Write the record */
48139   i = putVarint32(zNewRecord, nHdr);
48140   for(pRec=pData0; pRec<=pLast; pRec++){
48141     serial_type = sqlite3VdbeSerialType(pRec, file_format);
48142     i += putVarint32(&zNewRecord[i], serial_type);      /* serial type */
48143   }
48144   for(pRec=pData0; pRec<=pLast; pRec++){  /* serial data */
48145     i += sqlite3VdbeSerialPut(&zNewRecord[i], nByte-i, pRec, file_format);
48146   }
48147   assert( i==nByte );
48148
48149   assert( pOp->p3>0 && pOp->p3<=p->nMem );
48150   pOut->n = nByte;
48151   pOut->flags = MEM_Blob | MEM_Dyn;
48152   pOut->xDel = 0;
48153   if( nZero ){
48154     pOut->u.i = nZero;
48155     pOut->flags |= MEM_Zero;
48156   }
48157   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
48158   REGISTER_TRACE(pOp->p3, pOut);
48159   UPDATE_MAX_BLOBSIZE(pOut);
48160   break;
48161 }
48162
48163 /* Opcode: Statement P1 * * * *
48164 **
48165 ** Begin an individual statement transaction which is part of a larger
48166 ** transaction.  This is needed so that the statement
48167 ** can be rolled back after an error without having to roll back the
48168 ** entire transaction.  The statement transaction will automatically
48169 ** commit when the VDBE halts.
48170 **
48171 ** If the database connection is currently in autocommit mode (that 
48172 ** is to say, if it is in between BEGIN and COMMIT)
48173 ** and if there are no other active statements on the same database
48174 ** connection, then this operation is a no-op.  No statement transaction
48175 ** is needed since any error can use the normal ROLLBACK process to
48176 ** undo changes.
48177 **
48178 ** If a statement transaction is started, then a statement journal file
48179 ** will be allocated and initialized.
48180 **
48181 ** The statement is begun on the database file with index P1.  The main
48182 ** database file has an index of 0 and the file used for temporary tables
48183 ** has an index of 1.
48184 */
48185 case OP_Statement: {
48186   if( db->autoCommit==0 || db->activeVdbeCnt>1 ){
48187     int i = pOp->p1;
48188     Btree *pBt;
48189     assert( i>=0 && i<db->nDb );
48190     assert( db->aDb[i].pBt!=0 );
48191     pBt = db->aDb[i].pBt;
48192     assert( sqlite3BtreeIsInTrans(pBt) );
48193     assert( (p->btreeMask & (1<<i))!=0 );
48194     if( !sqlite3BtreeIsInStmt(pBt) ){
48195       rc = sqlite3BtreeBeginStmt(pBt);
48196       p->openedStatement = 1;
48197     }
48198   }
48199   break;
48200 }
48201
48202 /* Opcode: AutoCommit P1 P2 * * *
48203 **
48204 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
48205 ** back any currently active btree transactions. If there are any active
48206 ** VMs (apart from this one), then the COMMIT or ROLLBACK statement fails.
48207 **
48208 ** This instruction causes the VM to halt.
48209 */
48210 case OP_AutoCommit: {
48211   u8 i = pOp->p1;
48212   u8 rollback = pOp->p2;
48213
48214   assert( i==1 || i==0 );
48215   assert( i==1 || rollback==0 );
48216
48217   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
48218
48219   if( db->activeVdbeCnt>1 && i && !db->autoCommit ){
48220     /* If this instruction implements a COMMIT or ROLLBACK, other VMs are
48221     ** still running, and a transaction is active, return an error indicating
48222     ** that the other VMs must complete first. 
48223     */
48224     sqlite3SetString(&p->zErrMsg, db, "cannot %s transaction - "
48225         "SQL statements in progress",
48226         rollback ? "rollback" : "commit");
48227     rc = SQLITE_ERROR;
48228   }else if( i!=db->autoCommit ){
48229     if( pOp->p2 ){
48230       assert( i==1 );
48231       sqlite3RollbackAll(db);
48232       db->autoCommit = 1;
48233     }else{
48234       db->autoCommit = i;
48235       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
48236         p->pc = pc;
48237         db->autoCommit = 1-i;
48238         p->rc = rc = SQLITE_BUSY;
48239         goto vdbe_return;
48240       }
48241     }
48242     if( p->rc==SQLITE_OK ){
48243       rc = SQLITE_DONE;
48244     }else{
48245       rc = SQLITE_ERROR;
48246     }
48247     goto vdbe_return;
48248   }else{
48249     sqlite3SetString(&p->zErrMsg, db,
48250         (!i)?"cannot start a transaction within a transaction":(
48251         (rollback)?"cannot rollback - no transaction is active":
48252                    "cannot commit - no transaction is active"));
48253          
48254     rc = SQLITE_ERROR;
48255   }
48256   break;
48257 }
48258
48259 /* Opcode: Transaction P1 P2 * * *
48260 **
48261 ** Begin a transaction.  The transaction ends when a Commit or Rollback
48262 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
48263 ** transaction might also be rolled back if an error is encountered.
48264 **
48265 ** P1 is the index of the database file on which the transaction is
48266 ** started.  Index 0 is the main database file and index 1 is the
48267 ** file used for temporary tables.  Indices of 2 or more are used for
48268 ** attached databases.
48269 **
48270 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
48271 ** obtained on the database file when a write-transaction is started.  No
48272 ** other process can start another write transaction while this transaction is
48273 ** underway.  Starting a write transaction also creates a rollback journal. A
48274 ** write transaction must be started before any changes can be made to the
48275 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
48276 ** on the file.
48277 **
48278 ** If P2 is zero, then a read-lock is obtained on the database file.
48279 */
48280 case OP_Transaction: {
48281   int i = pOp->p1;
48282   Btree *pBt;
48283
48284   assert( i>=0 && i<db->nDb );
48285   assert( (p->btreeMask & (1<<i))!=0 );
48286   pBt = db->aDb[i].pBt;
48287
48288   if( pBt ){
48289     rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
48290     if( rc==SQLITE_BUSY ){
48291       p->pc = pc;
48292       p->rc = rc = SQLITE_BUSY;
48293       goto vdbe_return;
48294     }
48295     if( rc!=SQLITE_OK && rc!=SQLITE_READONLY /* && rc!=SQLITE_BUSY */ ){
48296       goto abort_due_to_error;
48297     }
48298   }
48299   break;
48300 }
48301
48302 /* Opcode: ReadCookie P1 P2 P3 * *
48303 **
48304 ** Read cookie number P3 from database P1 and write it into register P2.
48305 ** P3==0 is the schema version.  P3==1 is the database format.
48306 ** P3==2 is the recommended pager cache size, and so forth.  P1==0 is
48307 ** the main database file and P1==1 is the database file used to store
48308 ** temporary tables.
48309 **
48310 ** If P1 is negative, then this is a request to read the size of a
48311 ** databases free-list. P3 must be set to 1 in this case. The actual
48312 ** database accessed is ((P1+1)*-1). For example, a P1 parameter of -1
48313 ** corresponds to database 0 ("main"), a P1 of -2 is database 1 ("temp").
48314 **
48315 ** There must be a read-lock on the database (either a transaction
48316 ** must be started or there must be an open cursor) before
48317 ** executing this instruction.
48318 */
48319 case OP_ReadCookie: {               /* out2-prerelease */
48320   int iMeta;
48321   int iDb = pOp->p1;
48322   int iCookie = pOp->p3;
48323
48324   assert( pOp->p3<SQLITE_N_BTREE_META );
48325   if( iDb<0 ){
48326     iDb = (-1*(iDb+1));
48327     iCookie *= -1;
48328   }
48329   assert( iDb>=0 && iDb<db->nDb );
48330   assert( db->aDb[iDb].pBt!=0 );
48331   assert( (p->btreeMask & (1<<iDb))!=0 );
48332   /* The indexing of meta values at the schema layer is off by one from
48333   ** the indexing in the btree layer.  The btree considers meta[0] to
48334   ** be the number of free pages in the database (a read-only value)
48335   ** and meta[1] to be the schema cookie.  The schema layer considers
48336   ** meta[1] to be the schema cookie.  So we have to shift the index
48337   ** by one in the following statement.
48338   */
48339   rc = sqlite3BtreeGetMeta(db->aDb[iDb].pBt, 1 + iCookie, (u32 *)&iMeta);
48340   pOut->u.i = iMeta;
48341   MemSetTypeFlag(pOut, MEM_Int);
48342   break;
48343 }
48344
48345 /* Opcode: SetCookie P1 P2 P3 * *
48346 **
48347 ** Write the content of register P3 (interpreted as an integer)
48348 ** into cookie number P2 of database P1.
48349 ** P2==0 is the schema version.  P2==1 is the database format.
48350 ** P2==2 is the recommended pager cache size, and so forth.  P1==0 is
48351 ** the main database file and P1==1 is the database file used to store
48352 ** temporary tables.
48353 **
48354 ** A transaction must be started before executing this opcode.
48355 */
48356 case OP_SetCookie: {       /* in3 */
48357   Db *pDb;
48358   assert( pOp->p2<SQLITE_N_BTREE_META );
48359   assert( pOp->p1>=0 && pOp->p1<db->nDb );
48360   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
48361   pDb = &db->aDb[pOp->p1];
48362   assert( pDb->pBt!=0 );
48363   sqlite3VdbeMemIntegerify(pIn3);
48364   /* See note about index shifting on OP_ReadCookie */
48365   rc = sqlite3BtreeUpdateMeta(pDb->pBt, 1+pOp->p2, (int)pIn3->u.i);
48366   if( pOp->p2==0 ){
48367     /* When the schema cookie changes, record the new cookie internally */
48368     pDb->pSchema->schema_cookie = pIn3->u.i;
48369     db->flags |= SQLITE_InternChanges;
48370   }else if( pOp->p2==1 ){
48371     /* Record changes in the file format */
48372     pDb->pSchema->file_format = pIn3->u.i;
48373   }
48374   if( pOp->p1==1 ){
48375     /* Invalidate all prepared statements whenever the TEMP database
48376     ** schema is changed.  Ticket #1644 */
48377     sqlite3ExpirePreparedStatements(db);
48378   }
48379   break;
48380 }
48381
48382 /* Opcode: VerifyCookie P1 P2 *
48383 **
48384 ** Check the value of global database parameter number 0 (the
48385 ** schema version) and make sure it is equal to P2.  
48386 ** P1 is the database number which is 0 for the main database file
48387 ** and 1 for the file holding temporary tables and some higher number
48388 ** for auxiliary databases.
48389 **
48390 ** The cookie changes its value whenever the database schema changes.
48391 ** This operation is used to detect when that the cookie has changed
48392 ** and that the current process needs to reread the schema.
48393 **
48394 ** Either a transaction needs to have been started or an OP_Open needs
48395 ** to be executed (to establish a read lock) before this opcode is
48396 ** invoked.
48397 */
48398 case OP_VerifyCookie: {
48399   int iMeta;
48400   Btree *pBt;
48401   assert( pOp->p1>=0 && pOp->p1<db->nDb );
48402   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
48403   pBt = db->aDb[pOp->p1].pBt;
48404   if( pBt ){
48405     rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&iMeta);
48406   }else{
48407     rc = SQLITE_OK;
48408     iMeta = 0;
48409   }
48410   if( rc==SQLITE_OK && iMeta!=pOp->p2 ){
48411     sqlite3DbFree(db, p->zErrMsg);
48412     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
48413     /* If the schema-cookie from the database file matches the cookie 
48414     ** stored with the in-memory representation of the schema, do
48415     ** not reload the schema from the database file.
48416     **
48417     ** If virtual-tables are in use, this is not just an optimization.
48418     ** Often, v-tables store their data in other SQLite tables, which
48419     ** are queried from within xNext() and other v-table methods using
48420     ** prepared queries. If such a query is out-of-date, we do not want to
48421     ** discard the database schema, as the user code implementing the
48422     ** v-table would have to be ready for the sqlite3_vtab structure itself
48423     ** to be invalidated whenever sqlite3_step() is called from within 
48424     ** a v-table method.
48425     */
48426     if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
48427       sqlite3ResetInternalSchema(db, pOp->p1);
48428     }
48429
48430     sqlite3ExpirePreparedStatements(db);
48431     rc = SQLITE_SCHEMA;
48432   }
48433   break;
48434 }
48435
48436 /* Opcode: OpenRead P1 P2 P3 P4 P5
48437 **
48438 ** Open a read-only cursor for the database table whose root page is
48439 ** P2 in a database file.  The database file is determined by P3. 
48440 ** P3==0 means the main database, P3==1 means the database used for 
48441 ** temporary tables, and P3>1 means used the corresponding attached
48442 ** database.  Give the new cursor an identifier of P1.  The P1
48443 ** values need not be contiguous but all P1 values should be small integers.
48444 ** It is an error for P1 to be negative.
48445 **
48446 ** If P5!=0 then use the content of register P2 as the root page, not
48447 ** the value of P2 itself.
48448 **
48449 ** There will be a read lock on the database whenever there is an
48450 ** open cursor.  If the database was unlocked prior to this instruction
48451 ** then a read lock is acquired as part of this instruction.  A read
48452 ** lock allows other processes to read the database but prohibits
48453 ** any other process from modifying the database.  The read lock is
48454 ** released when all cursors are closed.  If this instruction attempts
48455 ** to get a read lock but fails, the script terminates with an
48456 ** SQLITE_BUSY error code.
48457 **
48458 ** The P4 value is a pointer to a KeyInfo structure that defines the
48459 ** content and collating sequence of indices.  P4 is NULL for cursors
48460 ** that are not pointing to indices.
48461 **
48462 ** See also OpenWrite.
48463 */
48464 /* Opcode: OpenWrite P1 P2 P3 P4 P5
48465 **
48466 ** Open a read/write cursor named P1 on the table or index whose root
48467 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
48468 ** root page.
48469 **
48470 ** The P4 value is a pointer to a KeyInfo structure that defines the
48471 ** content and collating sequence of indices.  P4 is NULL for cursors
48472 ** that are not pointing to indices.
48473 **
48474 ** This instruction works just like OpenRead except that it opens the cursor
48475 ** in read/write mode.  For a given table, there can be one or more read-only
48476 ** cursors or a single read/write cursor but not both.
48477 **
48478 ** See also OpenRead.
48479 */
48480 case OP_OpenRead:
48481 case OP_OpenWrite: {
48482   int i = pOp->p1;
48483   int p2 = pOp->p2;
48484   int iDb = pOp->p3;
48485   int wrFlag;
48486   Btree *pX;
48487   Cursor *pCur;
48488   Db *pDb;
48489   
48490   assert( iDb>=0 && iDb<db->nDb );
48491   assert( (p->btreeMask & (1<<iDb))!=0 );
48492   pDb = &db->aDb[iDb];
48493   pX = pDb->pBt;
48494   assert( pX!=0 );
48495   if( pOp->opcode==OP_OpenWrite ){
48496     wrFlag = 1;
48497     if( pDb->pSchema->file_format < p->minWriteFileFormat ){
48498       p->minWriteFileFormat = pDb->pSchema->file_format;
48499     }
48500   }else{
48501     wrFlag = 0;
48502   }
48503   if( pOp->p5 ){
48504     assert( p2>0 );
48505     assert( p2<=p->nMem );
48506     pIn2 = &p->aMem[p2];
48507     sqlite3VdbeMemIntegerify(pIn2);
48508     p2 = pIn2->u.i;
48509     assert( p2>=2 );
48510   }
48511   assert( i>=0 );
48512   pCur = allocateCursor(p, i, &pOp[-1], iDb, 1);
48513   if( pCur==0 ) goto no_mem;
48514   pCur->nullRow = 1;
48515   rc = sqlite3BtreeCursor(pX, p2, wrFlag, pOp->p4.p, pCur->pCursor);
48516   if( pOp->p4type==P4_KEYINFO ){
48517     pCur->pKeyInfo = pOp->p4.pKeyInfo;
48518     pCur->pKeyInfo->enc = ENC(p->db);
48519   }else{
48520     pCur->pKeyInfo = 0;
48521   }
48522   switch( rc ){
48523     case SQLITE_BUSY: {
48524       p->pc = pc;
48525       p->rc = rc = SQLITE_BUSY;
48526       goto vdbe_return;
48527     }
48528     case SQLITE_OK: {
48529       int flags = sqlite3BtreeFlags(pCur->pCursor);
48530       /* Sanity checking.  Only the lower four bits of the flags byte should
48531       ** be used.  Bit 3 (mask 0x08) is unpredictable.  The lower 3 bits
48532       ** (mask 0x07) should be either 5 (intkey+leafdata for tables) or
48533       ** 2 (zerodata for indices).  If these conditions are not met it can
48534       ** only mean that we are dealing with a corrupt database file
48535       */
48536       if( (flags & 0xf0)!=0 || ((flags & 0x07)!=5 && (flags & 0x07)!=2) ){
48537         rc = SQLITE_CORRUPT_BKPT;
48538         goto abort_due_to_error;
48539       }
48540       pCur->isTable = (flags & BTREE_INTKEY)!=0;
48541       pCur->isIndex = (flags & BTREE_ZERODATA)!=0;
48542       /* If P4==0 it means we are expected to open a table.  If P4!=0 then
48543       ** we expect to be opening an index.  If this is not what happened,
48544       ** then the database is corrupt
48545       */
48546       if( (pCur->isTable && pOp->p4type==P4_KEYINFO)
48547        || (pCur->isIndex && pOp->p4type!=P4_KEYINFO) ){
48548         rc = SQLITE_CORRUPT_BKPT;
48549         goto abort_due_to_error;
48550       }
48551       break;
48552     }
48553     case SQLITE_EMPTY: {
48554       pCur->isTable = pOp->p4type!=P4_KEYINFO;
48555       pCur->isIndex = !pCur->isTable;
48556       pCur->pCursor = 0;
48557       rc = SQLITE_OK;
48558       break;
48559     }
48560     default: {
48561       goto abort_due_to_error;
48562     }
48563   }
48564   break;
48565 }
48566
48567 /* Opcode: OpenEphemeral P1 P2 * P4 *
48568 **
48569 ** Open a new cursor P1 to a transient table.
48570 ** The cursor is always opened read/write even if 
48571 ** the main database is read-only.  The transient or virtual
48572 ** table is deleted automatically when the cursor is closed.
48573 **
48574 ** P2 is the number of columns in the virtual table.
48575 ** The cursor points to a BTree table if P4==0 and to a BTree index
48576 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
48577 ** that defines the format of keys in the index.
48578 **
48579 ** This opcode was once called OpenTemp.  But that created
48580 ** confusion because the term "temp table", might refer either
48581 ** to a TEMP table at the SQL level, or to a table opened by
48582 ** this opcode.  Then this opcode was call OpenVirtual.  But
48583 ** that created confusion with the whole virtual-table idea.
48584 */
48585 case OP_OpenEphemeral: {
48586   int i = pOp->p1;
48587   Cursor *pCx;
48588   static const int openFlags = 
48589       SQLITE_OPEN_READWRITE |
48590       SQLITE_OPEN_CREATE |
48591       SQLITE_OPEN_EXCLUSIVE |
48592       SQLITE_OPEN_DELETEONCLOSE |
48593       SQLITE_OPEN_TRANSIENT_DB;
48594
48595   assert( i>=0 );
48596   pCx = allocateCursor(p, i, pOp, -1, 1);
48597   if( pCx==0 ) goto no_mem;
48598   pCx->nullRow = 1;
48599   rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, openFlags,
48600                            &pCx->pBt);
48601   if( rc==SQLITE_OK ){
48602     rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
48603   }
48604   if( rc==SQLITE_OK ){
48605     /* If a transient index is required, create it by calling
48606     ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
48607     ** opening it. If a transient table is required, just use the
48608     ** automatically created table with root-page 1 (an INTKEY table).
48609     */
48610     if( pOp->p4.pKeyInfo ){
48611       int pgno;
48612       assert( pOp->p4type==P4_KEYINFO );
48613       rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_ZERODATA); 
48614       if( rc==SQLITE_OK ){
48615         assert( pgno==MASTER_ROOT+1 );
48616         rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, 
48617                                 (KeyInfo*)pOp->p4.z, pCx->pCursor);
48618         pCx->pKeyInfo = pOp->p4.pKeyInfo;
48619         pCx->pKeyInfo->enc = ENC(p->db);
48620       }
48621       pCx->isTable = 0;
48622     }else{
48623       rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, pCx->pCursor);
48624       pCx->isTable = 1;
48625     }
48626   }
48627   pCx->isIndex = !pCx->isTable;
48628   break;
48629 }
48630
48631 /* Opcode: OpenPseudo P1 P2 * * *
48632 **
48633 ** Open a new cursor that points to a fake table that contains a single
48634 ** row of data.  Any attempt to write a second row of data causes the
48635 ** first row to be deleted.  All data is deleted when the cursor is
48636 ** closed.
48637 **
48638 ** A pseudo-table created by this opcode is useful for holding the
48639 ** NEW or OLD tables in a trigger.  Also used to hold the a single
48640 ** row output from the sorter so that the row can be decomposed into
48641 ** individual columns using the OP_Column opcode.
48642 **
48643 ** When OP_Insert is executed to insert a row in to the pseudo table,
48644 ** the pseudo-table cursor may or may not make it's own copy of the
48645 ** original row data. If P2 is 0, then the pseudo-table will copy the
48646 ** original row data. Otherwise, a pointer to the original memory cell
48647 ** is stored. In this case, the vdbe program must ensure that the 
48648 ** memory cell containing the row data is not overwritten until the
48649 ** pseudo table is closed (or a new row is inserted into it).
48650 */
48651 case OP_OpenPseudo: {
48652   int i = pOp->p1;
48653   Cursor *pCx;
48654   assert( i>=0 );
48655   pCx = allocateCursor(p, i, &pOp[-1], -1, 0);
48656   if( pCx==0 ) goto no_mem;
48657   pCx->nullRow = 1;
48658   pCx->pseudoTable = 1;
48659   pCx->ephemPseudoTable = pOp->p2;
48660   pCx->isTable = 1;
48661   pCx->isIndex = 0;
48662   break;
48663 }
48664
48665 /* Opcode: Close P1 * * * *
48666 **
48667 ** Close a cursor previously opened as P1.  If P1 is not
48668 ** currently open, this instruction is a no-op.
48669 */
48670 case OP_Close: {
48671   int i = pOp->p1;
48672   assert( i>=0 && i<p->nCursor );
48673   sqlite3VdbeFreeCursor(p, p->apCsr[i]);
48674   p->apCsr[i] = 0;
48675   break;
48676 }
48677
48678 /* Opcode: MoveGe P1 P2 P3 P4 *
48679 **
48680 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
48681 ** use the integer value in register P3 as a key. If cursor P1 refers 
48682 ** to an SQL index, then P3 is the first in an array of P4 registers 
48683 ** that are used as an unpacked index key. 
48684 **
48685 ** Reposition cursor P1 so that  it points to the smallest entry that 
48686 ** is greater than or equal to the key value. If there are no records 
48687 ** greater than or equal to the key and P2 is not zero, then jump to P2.
48688 **
48689 ** A special feature of this opcode (and different from the
48690 ** related OP_MoveGt, OP_MoveLt, and OP_MoveLe) is that if P2 is
48691 ** zero and P1 is an SQL table (a b-tree with integer keys) then
48692 ** the seek is deferred until it is actually needed.  It might be
48693 ** the case that the cursor is never accessed.  By deferring the
48694 ** seek, we avoid unnecessary seeks.
48695 **
48696 ** See also: Found, NotFound, Distinct, MoveLt, MoveGt, MoveLe
48697 */
48698 /* Opcode: MoveGt P1 P2 P3 P4 *
48699 **
48700 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
48701 ** use the integer value in register P3 as a key. If cursor P1 refers 
48702 ** to an SQL index, then P3 is the first in an array of P4 registers 
48703 ** that are used as an unpacked index key. 
48704 **
48705 ** Reposition cursor P1 so that  it points to the smallest entry that 
48706 ** is greater than the key value. If there are no records greater than 
48707 ** the key and P2 is not zero, then jump to P2.
48708 **
48709 ** See also: Found, NotFound, Distinct, MoveLt, MoveGe, MoveLe
48710 */
48711 /* Opcode: MoveLt P1 P2 P3 P4 * 
48712 **
48713 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
48714 ** use the integer value in register P3 as a key. If cursor P1 refers 
48715 ** to an SQL index, then P3 is the first in an array of P4 registers 
48716 ** that are used as an unpacked index key. 
48717 **
48718 ** Reposition cursor P1 so that  it points to the largest entry that 
48719 ** is less than the key value. If there are no records less than 
48720 ** the key and P2 is not zero, then jump to P2.
48721 **
48722 ** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLe
48723 */
48724 /* Opcode: MoveLe P1 P2 P3 P4 *
48725 **
48726 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
48727 ** use the integer value in register P3 as a key. If cursor P1 refers 
48728 ** to an SQL index, then P3 is the first in an array of P4 registers 
48729 ** that are used as an unpacked index key. 
48730 **
48731 ** Reposition cursor P1 so that it points to the largest entry that 
48732 ** is less than or equal to the key value. If there are no records 
48733 ** less than or equal to the key and P2 is not zero, then jump to P2.
48734 **
48735 ** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLt
48736 */
48737 case OP_MoveLt:         /* jump, in3 */
48738 case OP_MoveLe:         /* jump, in3 */
48739 case OP_MoveGe:         /* jump, in3 */
48740 case OP_MoveGt: {       /* jump, in3 */
48741   int i = pOp->p1;
48742   Cursor *pC;
48743
48744   assert( i>=0 && i<p->nCursor );
48745   pC = p->apCsr[i];
48746   assert( pC!=0 );
48747   if( pC->pCursor!=0 ){
48748     int res, oc;
48749     oc = pOp->opcode;
48750     pC->nullRow = 0;
48751     if( pC->isTable ){
48752       i64 iKey = sqlite3VdbeIntValue(pIn3);
48753       if( pOp->p2==0 ){
48754         assert( pOp->opcode==OP_MoveGe );
48755         pC->movetoTarget = iKey;
48756         pC->rowidIsValid = 0;
48757         pC->deferredMoveto = 1;
48758         break;
48759       }
48760       rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)iKey, 0, &res);
48761       if( rc!=SQLITE_OK ){
48762         goto abort_due_to_error;
48763       }
48764       pC->lastRowid = iKey;
48765       pC->rowidIsValid = res==0;
48766     }else{
48767       UnpackedRecord r;
48768       int nField = pOp->p4.i;
48769       assert( pOp->p4type==P4_INT32 );
48770       assert( nField>0 );
48771       r.pKeyInfo = pC->pKeyInfo;
48772       r.nField = nField;
48773       if( oc==OP_MoveGt || oc==OP_MoveLe ){
48774         r.flags = UNPACKED_INCRKEY;
48775       }else{
48776         r.flags = 0;
48777       }
48778       r.aMem = &p->aMem[pOp->p3];
48779       rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, &r, 0, 0, &res);
48780       if( rc!=SQLITE_OK ){
48781         goto abort_due_to_error;
48782       }
48783       pC->rowidIsValid = 0;
48784     }
48785     pC->deferredMoveto = 0;
48786     pC->cacheStatus = CACHE_STALE;
48787 #ifdef SQLITE_TEST
48788     sqlite3_search_count++;
48789 #endif
48790     if( oc==OP_MoveGe || oc==OP_MoveGt ){
48791       if( res<0 ){
48792         rc = sqlite3BtreeNext(pC->pCursor, &res);
48793         if( rc!=SQLITE_OK ) goto abort_due_to_error;
48794         pC->rowidIsValid = 0;
48795       }else{
48796         res = 0;
48797       }
48798     }else{
48799       assert( oc==OP_MoveLt || oc==OP_MoveLe );
48800       if( res>=0 ){
48801         rc = sqlite3BtreePrevious(pC->pCursor, &res);
48802         if( rc!=SQLITE_OK ) goto abort_due_to_error;
48803         pC->rowidIsValid = 0;
48804       }else{
48805         /* res might be negative because the table is empty.  Check to
48806         ** see if this is the case.
48807         */
48808         res = sqlite3BtreeEof(pC->pCursor);
48809       }
48810     }
48811     assert( pOp->p2>0 );
48812     if( res ){
48813       pc = pOp->p2 - 1;
48814     }
48815   }else if( !pC->pseudoTable ){
48816     /* This happens when attempting to open the sqlite3_master table
48817     ** for read access returns SQLITE_EMPTY. In this case always
48818     ** take the jump (since there are no records in the table).
48819     */
48820     pc = pOp->p2 - 1;
48821   }
48822   break;
48823 }
48824
48825 /* Opcode: Found P1 P2 P3 * *
48826 **
48827 ** Register P3 holds a blob constructed by MakeRecord.  P1 is an index.
48828 ** If an entry that matches the value in register p3 exists in P1 then
48829 ** jump to P2.  If the P3 value does not match any entry in P1
48830 ** then fall thru.  The P1 cursor is left pointing at the matching entry
48831 ** if it exists.
48832 **
48833 ** This instruction is used to implement the IN operator where the
48834 ** left-hand side is a SELECT statement.  P1 may be a true index, or it
48835 ** may be a temporary index that holds the results of the SELECT
48836 ** statement.   This instruction is also used to implement the
48837 ** DISTINCT keyword in SELECT statements.
48838 **
48839 ** This instruction checks if index P1 contains a record for which 
48840 ** the first N serialized values exactly match the N serialized values
48841 ** in the record in register P3, where N is the total number of values in
48842 ** the P3 record (the P3 record is a prefix of the P1 record). 
48843 **
48844 ** See also: NotFound, IsUnique, NotExists
48845 */
48846 /* Opcode: NotFound P1 P2 P3 * *
48847 **
48848 ** Register P3 holds a blob constructed by MakeRecord.  P1 is
48849 ** an index.  If no entry exists in P1 that matches the blob then jump
48850 ** to P2.  If an entry does existing, fall through.  The cursor is left
48851 ** pointing to the entry that matches.
48852 **
48853 ** See also: Found, NotExists, IsUnique
48854 */
48855 case OP_NotFound:       /* jump, in3 */
48856 case OP_Found: {        /* jump, in3 */
48857   int i = pOp->p1;
48858   int alreadyExists = 0;
48859   Cursor *pC;
48860   assert( i>=0 && i<p->nCursor );
48861   assert( p->apCsr[i]!=0 );
48862   if( (pC = p->apCsr[i])->pCursor!=0 ){
48863     int res;
48864     UnpackedRecord *pIdxKey;
48865
48866     assert( pC->isTable==0 );
48867     assert( pIn3->flags & MEM_Blob );
48868     pIdxKey = sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z,
48869                                       aTempRec, sizeof(aTempRec));
48870     if( pIdxKey==0 ){
48871       goto no_mem;
48872     }
48873     if( pOp->opcode==OP_Found ){
48874       pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
48875     }
48876     rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, pIdxKey, 0, 0, &res);
48877     sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
48878     if( rc!=SQLITE_OK ){
48879       break;
48880     }
48881     alreadyExists = (res==0);
48882     pC->deferredMoveto = 0;
48883     pC->cacheStatus = CACHE_STALE;
48884   }
48885   if( pOp->opcode==OP_Found ){
48886     if( alreadyExists ) pc = pOp->p2 - 1;
48887   }else{
48888     if( !alreadyExists ) pc = pOp->p2 - 1;
48889   }
48890   break;
48891 }
48892
48893 /* Opcode: IsUnique P1 P2 P3 P4 *
48894 **
48895 ** The P3 register contains an integer record number.  Call this
48896 ** record number R.  The P4 register contains an index key created
48897 ** using MakeRecord.  Call it K.
48898 **
48899 ** P1 is an index.  So it has no data and its key consists of a
48900 ** record generated by OP_MakeRecord where the last field is the 
48901 ** rowid of the entry that the index refers to.
48902 ** 
48903 ** This instruction asks if there is an entry in P1 where the
48904 ** fields matches K but the rowid is different from R.
48905 ** If there is no such entry, then there is an immediate
48906 ** jump to P2.  If any entry does exist where the index string
48907 ** matches K but the record number is not R, then the record
48908 ** number for that entry is written into P3 and control
48909 ** falls through to the next instruction.
48910 **
48911 ** See also: NotFound, NotExists, Found
48912 */
48913 case OP_IsUnique: {        /* jump, in3 */
48914   int i = pOp->p1;
48915   Cursor *pCx;
48916   BtCursor *pCrsr;
48917   Mem *pK;
48918   i64 R;
48919
48920   /* Pop the value R off the top of the stack
48921   */
48922   assert( pOp->p4type==P4_INT32 );
48923   assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
48924   pK = &p->aMem[pOp->p4.i];
48925   sqlite3VdbeMemIntegerify(pIn3);
48926   R = pIn3->u.i;
48927   assert( i>=0 && i<p->nCursor );
48928   pCx = p->apCsr[i];
48929   assert( pCx!=0 );
48930   pCrsr = pCx->pCursor;
48931   if( pCrsr!=0 ){
48932     int res;
48933     i64 v;                     /* The record number that matches K */
48934     UnpackedRecord *pIdxKey;   /* Unpacked version of P4 */
48935
48936     /* Make sure K is a string and make zKey point to K
48937     */
48938     assert( pK->flags & MEM_Blob );
48939     pIdxKey = sqlite3VdbeRecordUnpack(pCx->pKeyInfo, pK->n, pK->z,
48940                                       aTempRec, sizeof(aTempRec));
48941     if( pIdxKey==0 ){
48942       goto no_mem;
48943     }
48944     pIdxKey->flags |= UNPACKED_IGNORE_ROWID;
48945
48946     /* Search for an entry in P1 where all but the last rowid match K
48947     ** If there is no such entry, jump immediately to P2.
48948     */
48949     assert( pCx->deferredMoveto==0 );
48950     pCx->cacheStatus = CACHE_STALE;
48951     rc = sqlite3BtreeMovetoUnpacked(pCrsr, pIdxKey, 0, 0, &res);
48952     if( rc!=SQLITE_OK ){
48953       sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
48954       goto abort_due_to_error;
48955     }
48956     if( res<0 ){
48957       rc = sqlite3BtreeNext(pCrsr, &res);
48958       if( res ){
48959         pc = pOp->p2 - 1;
48960         sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
48961         break;
48962       }
48963     }
48964     rc = sqlite3VdbeIdxKeyCompare(pCx, pIdxKey, &res); 
48965     sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
48966     if( rc!=SQLITE_OK ) goto abort_due_to_error;
48967     if( res>0 ){
48968       pc = pOp->p2 - 1;
48969       break;
48970     }
48971
48972     /* At this point, pCrsr is pointing to an entry in P1 where all but
48973     ** the final entry (the rowid) matches K.  Check to see if the
48974     ** final rowid column is different from R.  If it equals R then jump
48975     ** immediately to P2.
48976     */
48977     rc = sqlite3VdbeIdxRowid(pCrsr, &v);
48978     if( rc!=SQLITE_OK ){
48979       goto abort_due_to_error;
48980     }
48981     if( v==R ){
48982       pc = pOp->p2 - 1;
48983       break;
48984     }
48985
48986     /* The final varint of the key is different from R.  Store it back
48987     ** into register R3.  (The record number of an entry that violates
48988     ** a UNIQUE constraint.)
48989     */
48990     pIn3->u.i = v;
48991     assert( pIn3->flags&MEM_Int );
48992   }
48993   break;
48994 }
48995
48996 /* Opcode: NotExists P1 P2 P3 * *
48997 **
48998 ** Use the content of register P3 as a integer key.  If a record 
48999 ** with that key does not exist in table of P1, then jump to P2. 
49000 ** If the record does exist, then fall thru.  The cursor is left 
49001 ** pointing to the record if it exists.
49002 **
49003 ** The difference between this operation and NotFound is that this
49004 ** operation assumes the key is an integer and that P1 is a table whereas
49005 ** NotFound assumes key is a blob constructed from MakeRecord and
49006 ** P1 is an index.
49007 **
49008 ** See also: Found, NotFound, IsUnique
49009 */
49010 case OP_NotExists: {        /* jump, in3 */
49011   int i = pOp->p1;
49012   Cursor *pC;
49013   BtCursor *pCrsr;
49014   assert( i>=0 && i<p->nCursor );
49015   assert( p->apCsr[i]!=0 );
49016   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
49017     int res;
49018     u64 iKey;
49019     assert( pIn3->flags & MEM_Int );
49020     assert( p->apCsr[i]->isTable );
49021     iKey = intToKey(pIn3->u.i);
49022     rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0,&res);
49023     pC->lastRowid = pIn3->u.i;
49024     pC->rowidIsValid = res==0;
49025     pC->nullRow = 0;
49026     pC->cacheStatus = CACHE_STALE;
49027     /* res might be uninitialized if rc!=SQLITE_OK.  But if rc!=SQLITE_OK
49028     ** processing is about to abort so we really do not care whether or not
49029     ** the following jump is taken.  (In other words, do not stress over
49030     ** the error that valgrind sometimes shows on the next statement when
49031     ** running ioerr.test and similar failure-recovery test scripts.) */
49032     if( res!=0 ){
49033       pc = pOp->p2 - 1;
49034       assert( pC->rowidIsValid==0 );
49035     }
49036   }else if( !pC->pseudoTable ){
49037     /* This happens when an attempt to open a read cursor on the 
49038     ** sqlite_master table returns SQLITE_EMPTY.
49039     */
49040     assert( pC->isTable );
49041     pc = pOp->p2 - 1;
49042     assert( pC->rowidIsValid==0 );
49043   }
49044   break;
49045 }
49046
49047 /* Opcode: Sequence P1 P2 * * *
49048 **
49049 ** Find the next available sequence number for cursor P1.
49050 ** Write the sequence number into register P2.
49051 ** The sequence number on the cursor is incremented after this
49052 ** instruction.  
49053 */
49054 case OP_Sequence: {           /* out2-prerelease */
49055   int i = pOp->p1;
49056   assert( i>=0 && i<p->nCursor );
49057   assert( p->apCsr[i]!=0 );
49058   pOut->u.i = p->apCsr[i]->seqCount++;
49059   MemSetTypeFlag(pOut, MEM_Int);
49060   break;
49061 }
49062
49063
49064 /* Opcode: NewRowid P1 P2 P3 * *
49065 **
49066 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
49067 ** The record number is not previously used as a key in the database
49068 ** table that cursor P1 points to.  The new record number is written
49069 ** written to register P2.
49070 **
49071 ** If P3>0 then P3 is a register that holds the largest previously
49072 ** generated record number.  No new record numbers are allowed to be less
49073 ** than this value.  When this value reaches its maximum, a SQLITE_FULL
49074 ** error is generated.  The P3 register is updated with the generated
49075 ** record number.  This P3 mechanism is used to help implement the
49076 ** AUTOINCREMENT feature.
49077 */
49078 case OP_NewRowid: {           /* out2-prerelease */
49079   int i = pOp->p1;
49080   i64 v = 0;
49081   Cursor *pC;
49082   assert( i>=0 && i<p->nCursor );
49083   assert( p->apCsr[i]!=0 );
49084   if( (pC = p->apCsr[i])->pCursor==0 ){
49085     /* The zero initialization above is all that is needed */
49086   }else{
49087     /* The next rowid or record number (different terms for the same
49088     ** thing) is obtained in a two-step algorithm.
49089     **
49090     ** First we attempt to find the largest existing rowid and add one
49091     ** to that.  But if the largest existing rowid is already the maximum
49092     ** positive integer, we have to fall through to the second
49093     ** probabilistic algorithm
49094     **
49095     ** The second algorithm is to select a rowid at random and see if
49096     ** it already exists in the table.  If it does not exist, we have
49097     ** succeeded.  If the random rowid does exist, we select a new one
49098     ** and try again, up to 1000 times.
49099     **
49100     ** For a table with less than 2 billion entries, the probability
49101     ** of not finding a unused rowid is about 1.0e-300.  This is a 
49102     ** non-zero probability, but it is still vanishingly small and should
49103     ** never cause a problem.  You are much, much more likely to have a
49104     ** hardware failure than for this algorithm to fail.
49105     **
49106     ** The analysis in the previous paragraph assumes that you have a good
49107     ** source of random numbers.  Is a library function like lrand48()
49108     ** good enough?  Maybe. Maybe not. It's hard to know whether there
49109     ** might be subtle bugs is some implementations of lrand48() that
49110     ** could cause problems. To avoid uncertainty, SQLite uses its own 
49111     ** random number generator based on the RC4 algorithm.
49112     **
49113     ** To promote locality of reference for repetitive inserts, the
49114     ** first few attempts at choosing a random rowid pick values just a little
49115     ** larger than the previous rowid.  This has been shown experimentally
49116     ** to double the speed of the COPY operation.
49117     */
49118     int res, rx=SQLITE_OK, cnt;
49119     i64 x;
49120     cnt = 0;
49121     if( (sqlite3BtreeFlags(pC->pCursor)&(BTREE_INTKEY|BTREE_ZERODATA)) !=
49122           BTREE_INTKEY ){
49123       rc = SQLITE_CORRUPT_BKPT;
49124       goto abort_due_to_error;
49125     }
49126     assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_INTKEY)!=0 );
49127     assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_ZERODATA)==0 );
49128
49129 #ifdef SQLITE_32BIT_ROWID
49130 #   define MAX_ROWID 0x7fffffff
49131 #else
49132     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
49133     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
49134     ** to provide the constant while making all compilers happy.
49135     */
49136 #   define MAX_ROWID  ( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
49137 #endif
49138
49139     if( !pC->useRandomRowid ){
49140       if( pC->nextRowidValid ){
49141         v = pC->nextRowid;
49142       }else{
49143         rc = sqlite3BtreeLast(pC->pCursor, &res);
49144         if( rc!=SQLITE_OK ){
49145           goto abort_due_to_error;
49146         }
49147         if( res ){
49148           v = 1;
49149         }else{
49150           sqlite3BtreeKeySize(pC->pCursor, &v);
49151           v = keyToInt(v);
49152           if( v==MAX_ROWID ){
49153             pC->useRandomRowid = 1;
49154           }else{
49155             v++;
49156           }
49157         }
49158       }
49159
49160 #ifndef SQLITE_OMIT_AUTOINCREMENT
49161       if( pOp->p3 ){
49162         Mem *pMem;
49163         assert( pOp->p3>0 && pOp->p3<=p->nMem ); /* P3 is a valid memory cell */
49164         pMem = &p->aMem[pOp->p3];
49165         REGISTER_TRACE(pOp->p3, pMem);
49166         sqlite3VdbeMemIntegerify(pMem);
49167         assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
49168         if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
49169           rc = SQLITE_FULL;
49170           goto abort_due_to_error;
49171         }
49172         if( v<pMem->u.i+1 ){
49173           v = pMem->u.i + 1;
49174         }
49175         pMem->u.i = v;
49176       }
49177 #endif
49178
49179       if( v<MAX_ROWID ){
49180         pC->nextRowidValid = 1;
49181         pC->nextRowid = v+1;
49182       }else{
49183         pC->nextRowidValid = 0;
49184       }
49185     }
49186     if( pC->useRandomRowid ){
49187       assert( pOp->p3==0 );  /* SQLITE_FULL must have occurred prior to this */
49188       v = db->priorNewRowid;
49189       cnt = 0;
49190       do{
49191         if( cnt==0 && (v&0xffffff)==v ){
49192           v++;
49193         }else{
49194           sqlite3_randomness(sizeof(v), &v);
49195           if( cnt<5 ) v &= 0xffffff;
49196         }
49197         if( v==0 ) continue;
49198         x = intToKey(v);
49199         rx = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)x, 0, &res);
49200         cnt++;
49201       }while( cnt<100 && rx==SQLITE_OK && res==0 );
49202       db->priorNewRowid = v;
49203       if( rx==SQLITE_OK && res==0 ){
49204         rc = SQLITE_FULL;
49205         goto abort_due_to_error;
49206       }
49207     }
49208     pC->rowidIsValid = 0;
49209     pC->deferredMoveto = 0;
49210     pC->cacheStatus = CACHE_STALE;
49211   }
49212   MemSetTypeFlag(pOut, MEM_Int);
49213   pOut->u.i = v;
49214   break;
49215 }
49216
49217 /* Opcode: Insert P1 P2 P3 P4 P5
49218 **
49219 ** Write an entry into the table of cursor P1.  A new entry is
49220 ** created if it doesn't already exist or the data for an existing
49221 ** entry is overwritten.  The data is the value stored register
49222 ** number P2. The key is stored in register P3. The key must
49223 ** be an integer.
49224 **
49225 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
49226 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
49227 ** then rowid is stored for subsequent return by the
49228 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
49229 **
49230 ** Parameter P4 may point to a string containing the table-name, or
49231 ** may be NULL. If it is not NULL, then the update-hook 
49232 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
49233 **
49234 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
49235 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
49236 ** and register P2 becomes ephemeral.  If the cursor is changed, the
49237 ** value of register P2 will then change.  Make sure this does not
49238 ** cause any problems.)
49239 **
49240 ** This instruction only works on tables.  The equivalent instruction
49241 ** for indices is OP_IdxInsert.
49242 */
49243 case OP_Insert: {
49244   Mem *pData = &p->aMem[pOp->p2];
49245   Mem *pKey = &p->aMem[pOp->p3];
49246
49247   i64 iKey;   /* The integer ROWID or key for the record to be inserted */
49248   int i = pOp->p1;
49249   Cursor *pC;
49250   assert( i>=0 && i<p->nCursor );
49251   pC = p->apCsr[i];
49252   assert( pC!=0 );
49253   assert( pC->pCursor!=0 || pC->pseudoTable );
49254   assert( pKey->flags & MEM_Int );
49255   assert( pC->isTable );
49256   REGISTER_TRACE(pOp->p2, pData);
49257   REGISTER_TRACE(pOp->p3, pKey);
49258
49259   iKey = intToKey(pKey->u.i);
49260   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
49261   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = pKey->u.i;
49262   if( pC->nextRowidValid && pKey->u.i>=pC->nextRowid ){
49263     pC->nextRowidValid = 0;
49264   }
49265   if( pData->flags & MEM_Null ){
49266     pData->z = 0;
49267     pData->n = 0;
49268   }else{
49269     assert( pData->flags & (MEM_Blob|MEM_Str) );
49270   }
49271   if( pC->pseudoTable ){
49272     if( !pC->ephemPseudoTable ){
49273       sqlite3DbFree(db, pC->pData);
49274     }
49275     pC->iKey = iKey;
49276     pC->nData = pData->n;
49277     if( pData->z==pData->zMalloc || pC->ephemPseudoTable ){
49278       pC->pData = pData->z;
49279       if( !pC->ephemPseudoTable ){
49280         pData->flags &= ~MEM_Dyn;
49281         pData->flags |= MEM_Ephem;
49282         pData->zMalloc = 0;
49283       }
49284     }else{
49285       pC->pData = sqlite3Malloc( pC->nData+2 );
49286       if( !pC->pData ) goto no_mem;
49287       memcpy(pC->pData, pData->z, pC->nData);
49288       pC->pData[pC->nData] = 0;
49289       pC->pData[pC->nData+1] = 0;
49290     }
49291     pC->nullRow = 0;
49292   }else{
49293     int nZero;
49294     if( pData->flags & MEM_Zero ){
49295       nZero = pData->u.i;
49296     }else{
49297       nZero = 0;
49298     }
49299     rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
49300                             pData->z, pData->n, nZero,
49301                             pOp->p5 & OPFLAG_APPEND);
49302   }
49303   
49304   pC->rowidIsValid = 0;
49305   pC->deferredMoveto = 0;
49306   pC->cacheStatus = CACHE_STALE;
49307
49308   /* Invoke the update-hook if required. */
49309   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
49310     const char *zDb = db->aDb[pC->iDb].zName;
49311     const char *zTbl = pOp->p4.z;
49312     int op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
49313     assert( pC->isTable );
49314     db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
49315     assert( pC->iDb>=0 );
49316   }
49317   break;
49318 }
49319
49320 /* Opcode: Delete P1 P2 * P4 *
49321 **
49322 ** Delete the record at which the P1 cursor is currently pointing.
49323 **
49324 ** The cursor will be left pointing at either the next or the previous
49325 ** record in the table. If it is left pointing at the next record, then
49326 ** the next Next instruction will be a no-op.  Hence it is OK to delete
49327 ** a record from within an Next loop.
49328 **
49329 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
49330 ** incremented (otherwise not).
49331 **
49332 ** P1 must not be pseudo-table.  It has to be a real table with
49333 ** multiple rows.
49334 **
49335 ** If P4 is not NULL, then it is the name of the table that P1 is
49336 ** pointing to.  The update hook will be invoked, if it exists.
49337 ** If P4 is not NULL then the P1 cursor must have been positioned
49338 ** using OP_NotFound prior to invoking this opcode.
49339 */
49340 case OP_Delete: {
49341   int i = pOp->p1;
49342   i64 iKey;
49343   Cursor *pC;
49344
49345   assert( i>=0 && i<p->nCursor );
49346   pC = p->apCsr[i];
49347   assert( pC!=0 );
49348   assert( pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
49349
49350   /* If the update-hook will be invoked, set iKey to the rowid of the
49351   ** row being deleted.
49352   */
49353   if( db->xUpdateCallback && pOp->p4.z ){
49354     assert( pC->isTable );
49355     assert( pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
49356     iKey = pC->lastRowid;
49357   }
49358
49359   rc = sqlite3VdbeCursorMoveto(pC);
49360   if( rc ) goto abort_due_to_error;
49361   rc = sqlite3BtreeDelete(pC->pCursor);
49362   pC->nextRowidValid = 0;
49363   pC->cacheStatus = CACHE_STALE;
49364
49365   /* Invoke the update-hook if required. */
49366   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
49367     const char *zDb = db->aDb[pC->iDb].zName;
49368     const char *zTbl = pOp->p4.z;
49369     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey);
49370     assert( pC->iDb>=0 );
49371   }
49372   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
49373   break;
49374 }
49375
49376 /* Opcode: ResetCount P1 * *
49377 **
49378 ** This opcode resets the VMs internal change counter to 0. If P1 is true,
49379 ** then the value of the change counter is copied to the database handle
49380 ** change counter (returned by subsequent calls to sqlite3_changes())
49381 ** before it is reset. This is used by trigger programs.
49382 */
49383 case OP_ResetCount: {
49384   if( pOp->p1 ){
49385     sqlite3VdbeSetChanges(db, p->nChange);
49386   }
49387   p->nChange = 0;
49388   break;
49389 }
49390
49391 /* Opcode: RowData P1 P2 * * *
49392 **
49393 ** Write into register P2 the complete row data for cursor P1.
49394 ** There is no interpretation of the data.  
49395 ** It is just copied onto the P2 register exactly as 
49396 ** it is found in the database file.
49397 **
49398 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
49399 ** of a real table, not a pseudo-table.
49400 */
49401 /* Opcode: RowKey P1 P2 * * *
49402 **
49403 ** Write into register P2 the complete row key for cursor P1.
49404 ** There is no interpretation of the data.  
49405 ** The key is copied onto the P3 register exactly as 
49406 ** it is found in the database file.
49407 **
49408 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
49409 ** of a real table, not a pseudo-table.
49410 */
49411 case OP_RowKey:
49412 case OP_RowData: {
49413   int i = pOp->p1;
49414   Cursor *pC;
49415   BtCursor *pCrsr;
49416   u32 n;
49417
49418   pOut = &p->aMem[pOp->p2];
49419
49420   /* Note that RowKey and RowData are really exactly the same instruction */
49421   assert( i>=0 && i<p->nCursor );
49422   pC = p->apCsr[i];
49423   assert( pC->isTable || pOp->opcode==OP_RowKey );
49424   assert( pC->isIndex || pOp->opcode==OP_RowData );
49425   assert( pC!=0 );
49426   assert( pC->nullRow==0 );
49427   assert( pC->pseudoTable==0 );
49428   assert( pC->pCursor!=0 );
49429   pCrsr = pC->pCursor;
49430   rc = sqlite3VdbeCursorMoveto(pC);
49431   if( rc ) goto abort_due_to_error;
49432   if( pC->isIndex ){
49433     i64 n64;
49434     assert( !pC->isTable );
49435     sqlite3BtreeKeySize(pCrsr, &n64);
49436     if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
49437       goto too_big;
49438     }
49439     n = n64;
49440   }else{
49441     sqlite3BtreeDataSize(pCrsr, &n);
49442     if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
49443       goto too_big;
49444     }
49445   }
49446   if( sqlite3VdbeMemGrow(pOut, n, 0) ){
49447     goto no_mem;
49448   }
49449   pOut->n = n;
49450   MemSetTypeFlag(pOut, MEM_Blob);
49451   if( pC->isIndex ){
49452     rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
49453   }else{
49454     rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
49455   }
49456   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
49457   UPDATE_MAX_BLOBSIZE(pOut);
49458   break;
49459 }
49460
49461 /* Opcode: Rowid P1 P2 * * *
49462 **
49463 ** Store in register P2 an integer which is the key of the table entry that
49464 ** P1 is currently point to.
49465 */
49466 case OP_Rowid: {                 /* out2-prerelease */
49467   int i = pOp->p1;
49468   Cursor *pC;
49469   i64 v;
49470
49471   assert( i>=0 && i<p->nCursor );
49472   pC = p->apCsr[i];
49473   assert( pC!=0 );
49474   rc = sqlite3VdbeCursorMoveto(pC);
49475   if( rc ) goto abort_due_to_error;
49476   if( pC->rowidIsValid ){
49477     v = pC->lastRowid;
49478   }else if( pC->pseudoTable ){
49479     v = keyToInt(pC->iKey);
49480   }else if( pC->nullRow ){
49481     /* Leave the rowid set to a NULL */
49482     break;
49483   }else{
49484     assert( pC->pCursor!=0 );
49485     sqlite3BtreeKeySize(pC->pCursor, &v);
49486     v = keyToInt(v);
49487   }
49488   pOut->u.i = v;
49489   MemSetTypeFlag(pOut, MEM_Int);
49490   break;
49491 }
49492
49493 /* Opcode: NullRow P1 * * * *
49494 **
49495 ** Move the cursor P1 to a null row.  Any OP_Column operations
49496 ** that occur while the cursor is on the null row will always
49497 ** write a NULL.
49498 */
49499 case OP_NullRow: {
49500   int i = pOp->p1;
49501   Cursor *pC;
49502
49503   assert( i>=0 && i<p->nCursor );
49504   pC = p->apCsr[i];
49505   assert( pC!=0 );
49506   pC->nullRow = 1;
49507   pC->rowidIsValid = 0;
49508   break;
49509 }
49510
49511 /* Opcode: Last P1 P2 * * *
49512 **
49513 ** The next use of the Rowid or Column or Next instruction for P1 
49514 ** will refer to the last entry in the database table or index.
49515 ** If the table or index is empty and P2>0, then jump immediately to P2.
49516 ** If P2 is 0 or if the table or index is not empty, fall through
49517 ** to the following instruction.
49518 */
49519 case OP_Last: {        /* jump */
49520   int i = pOp->p1;
49521   Cursor *pC;
49522   BtCursor *pCrsr;
49523   int res;
49524
49525   assert( i>=0 && i<p->nCursor );
49526   pC = p->apCsr[i];
49527   assert( pC!=0 );
49528   pCrsr = pC->pCursor;
49529   assert( pCrsr!=0 );
49530   rc = sqlite3BtreeLast(pCrsr, &res);
49531   pC->nullRow = res;
49532   pC->deferredMoveto = 0;
49533   pC->cacheStatus = CACHE_STALE;
49534   if( res && pOp->p2>0 ){
49535     pc = pOp->p2 - 1;
49536   }
49537   break;
49538 }
49539
49540
49541 /* Opcode: Sort P1 P2 * * *
49542 **
49543 ** This opcode does exactly the same thing as OP_Rewind except that
49544 ** it increments an undocumented global variable used for testing.
49545 **
49546 ** Sorting is accomplished by writing records into a sorting index,
49547 ** then rewinding that index and playing it back from beginning to
49548 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
49549 ** rewinding so that the global variable will be incremented and
49550 ** regression tests can determine whether or not the optimizer is
49551 ** correctly optimizing out sorts.
49552 */
49553 case OP_Sort: {        /* jump */
49554 #ifdef SQLITE_TEST
49555   sqlite3_sort_count++;
49556   sqlite3_search_count--;
49557 #endif
49558   /* Fall through into OP_Rewind */
49559 }
49560 /* Opcode: Rewind P1 P2 * * *
49561 **
49562 ** The next use of the Rowid or Column or Next instruction for P1 
49563 ** will refer to the first entry in the database table or index.
49564 ** If the table or index is empty and P2>0, then jump immediately to P2.
49565 ** If P2 is 0 or if the table or index is not empty, fall through
49566 ** to the following instruction.
49567 */
49568 case OP_Rewind: {        /* jump */
49569   int i = pOp->p1;
49570   Cursor *pC;
49571   BtCursor *pCrsr;
49572   int res;
49573
49574   assert( i>=0 && i<p->nCursor );
49575   pC = p->apCsr[i];
49576   assert( pC!=0 );
49577   if( (pCrsr = pC->pCursor)!=0 ){
49578     rc = sqlite3BtreeFirst(pCrsr, &res);
49579     pC->atFirst = res==0;
49580     pC->deferredMoveto = 0;
49581     pC->cacheStatus = CACHE_STALE;
49582   }else{
49583     res = 1;
49584   }
49585   pC->nullRow = res;
49586   assert( pOp->p2>0 && pOp->p2<p->nOp );
49587   if( res ){
49588     pc = pOp->p2 - 1;
49589   }
49590   break;
49591 }
49592
49593 /* Opcode: Next P1 P2 * * *
49594 **
49595 ** Advance cursor P1 so that it points to the next key/data pair in its
49596 ** table or index.  If there are no more key/value pairs then fall through
49597 ** to the following instruction.  But if the cursor advance was successful,
49598 ** jump immediately to P2.
49599 **
49600 ** The P1 cursor must be for a real table, not a pseudo-table.
49601 **
49602 ** See also: Prev
49603 */
49604 /* Opcode: Prev P1 P2 * * *
49605 **
49606 ** Back up cursor P1 so that it points to the previous key/data pair in its
49607 ** table or index.  If there is no previous key/value pairs then fall through
49608 ** to the following instruction.  But if the cursor backup was successful,
49609 ** jump immediately to P2.
49610 **
49611 ** The P1 cursor must be for a real table, not a pseudo-table.
49612 */
49613 case OP_Prev:          /* jump */
49614 case OP_Next: {        /* jump */
49615   Cursor *pC;
49616   BtCursor *pCrsr;
49617   int res;
49618
49619   CHECK_FOR_INTERRUPT;
49620   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
49621   pC = p->apCsr[pOp->p1];
49622   if( pC==0 ){
49623     break;  /* See ticket #2273 */
49624   }
49625   pCrsr = pC->pCursor;
49626   assert( pCrsr );
49627   res = 1;
49628   assert( pC->deferredMoveto==0 );
49629   rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(pCrsr, &res) :
49630                               sqlite3BtreePrevious(pCrsr, &res);
49631   pC->nullRow = res;
49632   pC->cacheStatus = CACHE_STALE;
49633   if( res==0 ){
49634     pc = pOp->p2 - 1;
49635 #ifdef SQLITE_TEST
49636     sqlite3_search_count++;
49637 #endif
49638   }
49639   pC->rowidIsValid = 0;
49640   break;
49641 }
49642
49643 /* Opcode: IdxInsert P1 P2 P3 * *
49644 **
49645 ** Register P2 holds a SQL index key made using the
49646 ** MakeIdxRec instructions.  This opcode writes that key
49647 ** into the index P1.  Data for the entry is nil.
49648 **
49649 ** P3 is a flag that provides a hint to the b-tree layer that this
49650 ** insert is likely to be an append.
49651 **
49652 ** This instruction only works for indices.  The equivalent instruction
49653 ** for tables is OP_Insert.
49654 */
49655 case OP_IdxInsert: {        /* in2 */
49656   int i = pOp->p1;
49657   Cursor *pC;
49658   BtCursor *pCrsr;
49659   assert( i>=0 && i<p->nCursor );
49660   assert( p->apCsr[i]!=0 );
49661   assert( pIn2->flags & MEM_Blob );
49662   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
49663     assert( pC->isTable==0 );
49664     rc = ExpandBlob(pIn2);
49665     if( rc==SQLITE_OK ){
49666       int nKey = pIn2->n;
49667       const char *zKey = pIn2->z;
49668       rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3);
49669       assert( pC->deferredMoveto==0 );
49670       pC->cacheStatus = CACHE_STALE;
49671     }
49672   }
49673   break;
49674 }
49675
49676 /* Opcode: IdxDeleteM P1 P2 P3 * *
49677 **
49678 ** The content of P3 registers starting at register P2 form
49679 ** an unpacked index key. This opcode removes that entry from the 
49680 ** index opened by cursor P1.
49681 */
49682 case OP_IdxDelete: {
49683   int i = pOp->p1;
49684   Cursor *pC;
49685   BtCursor *pCrsr;
49686   assert( pOp->p3>0 );
49687   assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem );
49688   assert( i>=0 && i<p->nCursor );
49689   assert( p->apCsr[i]!=0 );
49690   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
49691     int res;
49692     UnpackedRecord r;
49693     r.pKeyInfo = pC->pKeyInfo;
49694     r.nField = pOp->p3;
49695     r.flags = 0;
49696     r.aMem = &p->aMem[pOp->p2];
49697     rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
49698     if( rc==SQLITE_OK && res==0 ){
49699       rc = sqlite3BtreeDelete(pCrsr);
49700     }
49701     assert( pC->deferredMoveto==0 );
49702     pC->cacheStatus = CACHE_STALE;
49703   }
49704   break;
49705 }
49706
49707 /* Opcode: IdxRowid P1 P2 * * *
49708 **
49709 ** Write into register P2 an integer which is the last entry in the record at
49710 ** the end of the index key pointed to by cursor P1.  This integer should be
49711 ** the rowid of the table entry to which this index entry points.
49712 **
49713 ** See also: Rowid, MakeIdxRec.
49714 */
49715 case OP_IdxRowid: {              /* out2-prerelease */
49716   int i = pOp->p1;
49717   BtCursor *pCrsr;
49718   Cursor *pC;
49719
49720   assert( i>=0 && i<p->nCursor );
49721   assert( p->apCsr[i]!=0 );
49722   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
49723     i64 rowid;
49724
49725     assert( pC->deferredMoveto==0 );
49726     assert( pC->isTable==0 );
49727     if( !pC->nullRow ){
49728       rc = sqlite3VdbeIdxRowid(pCrsr, &rowid);
49729       if( rc!=SQLITE_OK ){
49730         goto abort_due_to_error;
49731       }
49732       MemSetTypeFlag(pOut, MEM_Int);
49733       pOut->u.i = rowid;
49734     }
49735   }
49736   break;
49737 }
49738
49739 /* Opcode: IdxGE P1 P2 P3 P4 P5
49740 **
49741 ** The P4 register values beginning with P3 form an unpacked index 
49742 ** key that omits the ROWID.  Compare this key value against the index 
49743 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
49744 **
49745 ** If the P1 index entry is greater than or equal to the key value
49746 ** then jump to P2.  Otherwise fall through to the next instruction.
49747 **
49748 ** If P5 is non-zero then the key value is increased by an epsilon 
49749 ** prior to the comparison.  This make the opcode work like IdxGT except
49750 ** that if the key from register P3 is a prefix of the key in the cursor,
49751 ** the result is false whereas it would be true with IdxGT.
49752 */
49753 /* Opcode: IdxLT P1 P2 P3 * P5
49754 **
49755 ** The P4 register values beginning with P3 form an unpacked index 
49756 ** key that omits the ROWID.  Compare this key value against the index 
49757 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
49758 **
49759 ** If the P1 index entry is less than the key value then jump to P2.
49760 ** Otherwise fall through to the next instruction.
49761 **
49762 ** If P5 is non-zero then the key value is increased by an epsilon prior 
49763 ** to the comparison.  This makes the opcode work like IdxLE.
49764 */
49765 case OP_IdxLT:          /* jump, in3 */
49766 case OP_IdxGE: {        /* jump, in3 */
49767   int i= pOp->p1;
49768   Cursor *pC;
49769
49770   assert( i>=0 && i<p->nCursor );
49771   assert( p->apCsr[i]!=0 );
49772   if( (pC = p->apCsr[i])->pCursor!=0 ){
49773     int res;
49774     UnpackedRecord r;
49775     assert( pC->deferredMoveto==0 );
49776     assert( pOp->p5==0 || pOp->p5==1 );
49777     assert( pOp->p4type==P4_INT32 );
49778     r.pKeyInfo = pC->pKeyInfo;
49779     r.nField = pOp->p4.i;
49780     if( pOp->p5 ){
49781       r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
49782     }else{
49783       r.flags = UNPACKED_IGNORE_ROWID;
49784     }
49785     r.aMem = &p->aMem[pOp->p3];
49786     rc = sqlite3VdbeIdxKeyCompare(pC, &r, &res);
49787     if( pOp->opcode==OP_IdxLT ){
49788       res = -res;
49789     }else{
49790       assert( pOp->opcode==OP_IdxGE );
49791       res++;
49792     }
49793     if( res>0 ){
49794       pc = pOp->p2 - 1 ;
49795     }
49796   }
49797   break;
49798 }
49799
49800 /* Opcode: Destroy P1 P2 P3 * *
49801 **
49802 ** Delete an entire database table or index whose root page in the database
49803 ** file is given by P1.
49804 **
49805 ** The table being destroyed is in the main database file if P3==0.  If
49806 ** P3==1 then the table to be clear is in the auxiliary database file
49807 ** that is used to store tables create using CREATE TEMPORARY TABLE.
49808 **
49809 ** If AUTOVACUUM is enabled then it is possible that another root page
49810 ** might be moved into the newly deleted root page in order to keep all
49811 ** root pages contiguous at the beginning of the database.  The former
49812 ** value of the root page that moved - its value before the move occurred -
49813 ** is stored in register P2.  If no page 
49814 ** movement was required (because the table being dropped was already 
49815 ** the last one in the database) then a zero is stored in register P2.
49816 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
49817 **
49818 ** See also: Clear
49819 */
49820 case OP_Destroy: {     /* out2-prerelease */
49821   int iMoved;
49822   int iCnt;
49823 #ifndef SQLITE_OMIT_VIRTUALTABLE
49824   Vdbe *pVdbe;
49825   iCnt = 0;
49826   for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
49827     if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->inVtabMethod<2 && pVdbe->pc>=0 ){
49828       iCnt++;
49829     }
49830   }
49831 #else
49832   iCnt = db->activeVdbeCnt;
49833 #endif
49834   if( iCnt>1 ){
49835     rc = SQLITE_LOCKED;
49836     p->errorAction = OE_Abort;
49837   }else{
49838     int iDb = pOp->p3;
49839     assert( iCnt==1 );
49840     assert( (p->btreeMask & (1<<iDb))!=0 );
49841     rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
49842     MemSetTypeFlag(pOut, MEM_Int);
49843     pOut->u.i = iMoved;
49844 #ifndef SQLITE_OMIT_AUTOVACUUM
49845     if( rc==SQLITE_OK && iMoved!=0 ){
49846       sqlite3RootPageMoved(&db->aDb[iDb], iMoved, pOp->p1);
49847     }
49848 #endif
49849   }
49850   break;
49851 }
49852
49853 /* Opcode: Clear P1 P2 *
49854 **
49855 ** Delete all contents of the database table or index whose root page
49856 ** in the database file is given by P1.  But, unlike Destroy, do not
49857 ** remove the table or index from the database file.
49858 **
49859 ** The table being clear is in the main database file if P2==0.  If
49860 ** P2==1 then the table to be clear is in the auxiliary database file
49861 ** that is used to store tables create using CREATE TEMPORARY TABLE.
49862 **
49863 ** See also: Destroy
49864 */
49865 case OP_Clear: {
49866   assert( (p->btreeMask & (1<<pOp->p2))!=0 );
49867   rc = sqlite3BtreeClearTable(db->aDb[pOp->p2].pBt, pOp->p1);
49868   break;
49869 }
49870
49871 /* Opcode: CreateTable P1 P2 * * *
49872 **
49873 ** Allocate a new table in the main database file if P1==0 or in the
49874 ** auxiliary database file if P1==1 or in an attached database if
49875 ** P1>1.  Write the root page number of the new table into
49876 ** register P2
49877 **
49878 ** The difference between a table and an index is this:  A table must
49879 ** have a 4-byte integer key and can have arbitrary data.  An index
49880 ** has an arbitrary key but no data.
49881 **
49882 ** See also: CreateIndex
49883 */
49884 /* Opcode: CreateIndex P1 P2 * * *
49885 **
49886 ** Allocate a new index in the main database file if P1==0 or in the
49887 ** auxiliary database file if P1==1 or in an attached database if
49888 ** P1>1.  Write the root page number of the new table into
49889 ** register P2.
49890 **
49891 ** See documentation on OP_CreateTable for additional information.
49892 */
49893 case OP_CreateIndex:            /* out2-prerelease */
49894 case OP_CreateTable: {          /* out2-prerelease */
49895   int pgno;
49896   int flags;
49897   Db *pDb;
49898   assert( pOp->p1>=0 && pOp->p1<db->nDb );
49899   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
49900   pDb = &db->aDb[pOp->p1];
49901   assert( pDb->pBt!=0 );
49902   if( pOp->opcode==OP_CreateTable ){
49903     /* flags = BTREE_INTKEY; */
49904     flags = BTREE_LEAFDATA|BTREE_INTKEY;
49905   }else{
49906     flags = BTREE_ZERODATA;
49907   }
49908   rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
49909   if( rc==SQLITE_OK ){
49910     pOut->u.i = pgno;
49911     MemSetTypeFlag(pOut, MEM_Int);
49912   }
49913   break;
49914 }
49915
49916 /* Opcode: ParseSchema P1 P2 * P4 *
49917 **
49918 ** Read and parse all entries from the SQLITE_MASTER table of database P1
49919 ** that match the WHERE clause P4.  P2 is the "force" flag.   Always do
49920 ** the parsing if P2 is true.  If P2 is false, then this routine is a
49921 ** no-op if the schema is not currently loaded.  In other words, if P2
49922 ** is false, the SQLITE_MASTER table is only parsed if the rest of the
49923 ** schema is already loaded into the symbol table.
49924 **
49925 ** This opcode invokes the parser to create a new virtual machine,
49926 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
49927 */
49928 case OP_ParseSchema: {
49929   char *zSql;
49930   int iDb = pOp->p1;
49931   const char *zMaster;
49932   InitData initData;
49933
49934   assert( iDb>=0 && iDb<db->nDb );
49935   if( !pOp->p2 && !DbHasProperty(db, iDb, DB_SchemaLoaded) ){
49936     break;
49937   }
49938   zMaster = SCHEMA_TABLE(iDb);
49939   initData.db = db;
49940   initData.iDb = pOp->p1;
49941   initData.pzErrMsg = &p->zErrMsg;
49942   zSql = sqlite3MPrintf(db,
49943      "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s",
49944      db->aDb[iDb].zName, zMaster, pOp->p4.z);
49945   if( zSql==0 ) goto no_mem;
49946   (void)sqlite3SafetyOff(db);
49947   assert( db->init.busy==0 );
49948   db->init.busy = 1;
49949   initData.rc = SQLITE_OK;
49950   assert( !db->mallocFailed );
49951   rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
49952   if( rc==SQLITE_OK ) rc = initData.rc;
49953   sqlite3DbFree(db, zSql);
49954   db->init.busy = 0;
49955   (void)sqlite3SafetyOn(db);
49956   if( rc==SQLITE_NOMEM ){
49957     goto no_mem;
49958   }
49959   break;  
49960 }
49961
49962 #if !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER)
49963 /* Opcode: LoadAnalysis P1 * * * *
49964 **
49965 ** Read the sqlite_stat1 table for database P1 and load the content
49966 ** of that table into the internal index hash table.  This will cause
49967 ** the analysis to be used when preparing all subsequent queries.
49968 */
49969 case OP_LoadAnalysis: {
49970   int iDb = pOp->p1;
49971   assert( iDb>=0 && iDb<db->nDb );
49972   rc = sqlite3AnalysisLoad(db, iDb);
49973   break;  
49974 }
49975 #endif /* !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER)  */
49976
49977 /* Opcode: DropTable P1 * * P4 *
49978 **
49979 ** Remove the internal (in-memory) data structures that describe
49980 ** the table named P4 in database P1.  This is called after a table
49981 ** is dropped in order to keep the internal representation of the
49982 ** schema consistent with what is on disk.
49983 */
49984 case OP_DropTable: {
49985   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
49986   break;
49987 }
49988
49989 /* Opcode: DropIndex P1 * * P4 *
49990 **
49991 ** Remove the internal (in-memory) data structures that describe
49992 ** the index named P4 in database P1.  This is called after an index
49993 ** is dropped in order to keep the internal representation of the
49994 ** schema consistent with what is on disk.
49995 */
49996 case OP_DropIndex: {
49997   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
49998   break;
49999 }
50000
50001 /* Opcode: DropTrigger P1 * * P4 *
50002 **
50003 ** Remove the internal (in-memory) data structures that describe
50004 ** the trigger named P4 in database P1.  This is called after a trigger
50005 ** is dropped in order to keep the internal representation of the
50006 ** schema consistent with what is on disk.
50007 */
50008 case OP_DropTrigger: {
50009   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
50010   break;
50011 }
50012
50013
50014 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
50015 /* Opcode: IntegrityCk P1 P2 P3 * P5
50016 **
50017 ** Do an analysis of the currently open database.  Store in
50018 ** register P1 the text of an error message describing any problems.
50019 ** If no problems are found, store a NULL in register P1.
50020 **
50021 ** The register P3 contains the maximum number of allowed errors.
50022 ** At most reg(P3) errors will be reported.
50023 ** In other words, the analysis stops as soon as reg(P1) errors are 
50024 ** seen.  Reg(P1) is updated with the number of errors remaining.
50025 **
50026 ** The root page numbers of all tables in the database are integer
50027 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
50028 ** total.
50029 **
50030 ** If P5 is not zero, the check is done on the auxiliary database
50031 ** file, not the main database file.
50032 **
50033 ** This opcode is used to implement the integrity_check pragma.
50034 */
50035 case OP_IntegrityCk: {
50036   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
50037   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
50038   int j;          /* Loop counter */
50039   int nErr;       /* Number of errors reported */
50040   char *z;        /* Text of the error report */
50041   Mem *pnErr;     /* Register keeping track of errors remaining */
50042   
50043   nRoot = pOp->p2;
50044   assert( nRoot>0 );
50045   aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) );
50046   if( aRoot==0 ) goto no_mem;
50047   assert( pOp->p3>0 && pOp->p3<=p->nMem );
50048   pnErr = &p->aMem[pOp->p3];
50049   assert( (pnErr->flags & MEM_Int)!=0 );
50050   assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
50051   pIn1 = &p->aMem[pOp->p1];
50052   for(j=0; j<nRoot; j++){
50053     aRoot[j] = sqlite3VdbeIntValue(&pIn1[j]);
50054   }
50055   aRoot[j] = 0;
50056   assert( pOp->p5<db->nDb );
50057   assert( (p->btreeMask & (1<<pOp->p5))!=0 );
50058   z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
50059                                  pnErr->u.i, &nErr);
50060   sqlite3DbFree(db, aRoot);
50061   pnErr->u.i -= nErr;
50062   sqlite3VdbeMemSetNull(pIn1);
50063   if( nErr==0 ){
50064     assert( z==0 );
50065   }else if( z==0 ){
50066     goto no_mem;
50067   }else{
50068     sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
50069   }
50070   UPDATE_MAX_BLOBSIZE(pIn1);
50071   sqlite3VdbeChangeEncoding(pIn1, encoding);
50072   break;
50073 }
50074 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
50075
50076 /* Opcode: FifoWrite P1 * * * *
50077 **
50078 ** Write the integer from register P1 into the Fifo.
50079 */
50080 case OP_FifoWrite: {        /* in1 */
50081   p->sFifo.db = db;
50082   if( sqlite3VdbeFifoPush(&p->sFifo, sqlite3VdbeIntValue(pIn1))==SQLITE_NOMEM ){
50083     goto no_mem;
50084   }
50085   break;
50086 }
50087
50088 /* Opcode: FifoRead P1 P2 * * *
50089 **
50090 ** Attempt to read a single integer from the Fifo.  Store that
50091 ** integer in register P1.
50092 ** 
50093 ** If the Fifo is empty jump to P2.
50094 */
50095 case OP_FifoRead: {         /* jump */
50096   CHECK_FOR_INTERRUPT;
50097   assert( pOp->p1>0 && pOp->p1<=p->nMem );
50098   pOut = &p->aMem[pOp->p1];
50099   MemSetTypeFlag(pOut, MEM_Int);
50100   if( sqlite3VdbeFifoPop(&p->sFifo, &pOut->u.i)==SQLITE_DONE ){
50101     pc = pOp->p2 - 1;
50102   }
50103   break;
50104 }
50105
50106 #ifndef SQLITE_OMIT_TRIGGER
50107 /* Opcode: ContextPush * * * 
50108 **
50109 ** Save the current Vdbe context such that it can be restored by a ContextPop
50110 ** opcode. The context stores the last insert row id, the last statement change
50111 ** count, and the current statement change count.
50112 */
50113 case OP_ContextPush: {
50114   int i = p->contextStackTop++;
50115   Context *pContext;
50116
50117   assert( i>=0 );
50118   /* FIX ME: This should be allocated as part of the vdbe at compile-time */
50119   if( i>=p->contextStackDepth ){
50120     p->contextStackDepth = i+1;
50121     p->contextStack = sqlite3DbReallocOrFree(db, p->contextStack,
50122                                           sizeof(Context)*(i+1));
50123     if( p->contextStack==0 ) goto no_mem;
50124   }
50125   pContext = &p->contextStack[i];
50126   pContext->lastRowid = db->lastRowid;
50127   pContext->nChange = p->nChange;
50128   pContext->sFifo = p->sFifo;
50129   sqlite3VdbeFifoInit(&p->sFifo, db);
50130   break;
50131 }
50132
50133 /* Opcode: ContextPop * * * 
50134 **
50135 ** Restore the Vdbe context to the state it was in when contextPush was last
50136 ** executed. The context stores the last insert row id, the last statement
50137 ** change count, and the current statement change count.
50138 */
50139 case OP_ContextPop: {
50140   Context *pContext = &p->contextStack[--p->contextStackTop];
50141   assert( p->contextStackTop>=0 );
50142   db->lastRowid = pContext->lastRowid;
50143   p->nChange = pContext->nChange;
50144   sqlite3VdbeFifoClear(&p->sFifo);
50145   p->sFifo = pContext->sFifo;
50146   break;
50147 }
50148 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
50149
50150 #ifndef SQLITE_OMIT_AUTOINCREMENT
50151 /* Opcode: MemMax P1 P2 * * *
50152 **
50153 ** Set the value of register P1 to the maximum of its current value
50154 ** and the value in register P2.
50155 **
50156 ** This instruction throws an error if the memory cell is not initially
50157 ** an integer.
50158 */
50159 case OP_MemMax: {        /* in1, in2 */
50160   sqlite3VdbeMemIntegerify(pIn1);
50161   sqlite3VdbeMemIntegerify(pIn2);
50162   if( pIn1->u.i<pIn2->u.i){
50163     pIn1->u.i = pIn2->u.i;
50164   }
50165   break;
50166 }
50167 #endif /* SQLITE_OMIT_AUTOINCREMENT */
50168
50169 /* Opcode: IfPos P1 P2 * * *
50170 **
50171 ** If the value of register P1 is 1 or greater, jump to P2.
50172 **
50173 ** It is illegal to use this instruction on a register that does
50174 ** not contain an integer.  An assertion fault will result if you try.
50175 */
50176 case OP_IfPos: {        /* jump, in1 */
50177   assert( pIn1->flags&MEM_Int );
50178   if( pIn1->u.i>0 ){
50179      pc = pOp->p2 - 1;
50180   }
50181   break;
50182 }
50183
50184 /* Opcode: IfNeg P1 P2 * * *
50185 **
50186 ** If the value of register P1 is less than zero, jump to P2. 
50187 **
50188 ** It is illegal to use this instruction on a register that does
50189 ** not contain an integer.  An assertion fault will result if you try.
50190 */
50191 case OP_IfNeg: {        /* jump, in1 */
50192   assert( pIn1->flags&MEM_Int );
50193   if( pIn1->u.i<0 ){
50194      pc = pOp->p2 - 1;
50195   }
50196   break;
50197 }
50198
50199 /* Opcode: IfZero P1 P2 * * *
50200 **
50201 ** If the value of register P1 is exactly 0, jump to P2. 
50202 **
50203 ** It is illegal to use this instruction on a register that does
50204 ** not contain an integer.  An assertion fault will result if you try.
50205 */
50206 case OP_IfZero: {        /* jump, in1 */
50207   assert( pIn1->flags&MEM_Int );
50208   if( pIn1->u.i==0 ){
50209      pc = pOp->p2 - 1;
50210   }
50211   break;
50212 }
50213
50214 /* Opcode: AggStep * P2 P3 P4 P5
50215 **
50216 ** Execute the step function for an aggregate.  The
50217 ** function has P5 arguments.   P4 is a pointer to the FuncDef
50218 ** structure that specifies the function.  Use register
50219 ** P3 as the accumulator.
50220 **
50221 ** The P5 arguments are taken from register P2 and its
50222 ** successors.
50223 */
50224 case OP_AggStep: {
50225   int n = pOp->p5;
50226   int i;
50227   Mem *pMem, *pRec;
50228   sqlite3_context ctx;
50229   sqlite3_value **apVal;
50230
50231   assert( n>=0 );
50232   pRec = &p->aMem[pOp->p2];
50233   apVal = p->apArg;
50234   assert( apVal || n==0 );
50235   for(i=0; i<n; i++, pRec++){
50236     apVal[i] = pRec;
50237     storeTypeInfo(pRec, encoding);
50238   }
50239   ctx.pFunc = pOp->p4.pFunc;
50240   assert( pOp->p3>0 && pOp->p3<=p->nMem );
50241   ctx.pMem = pMem = &p->aMem[pOp->p3];
50242   pMem->n++;
50243   ctx.s.flags = MEM_Null;
50244   ctx.s.z = 0;
50245   ctx.s.zMalloc = 0;
50246   ctx.s.xDel = 0;
50247   ctx.s.db = db;
50248   ctx.isError = 0;
50249   ctx.pColl = 0;
50250   if( ctx.pFunc->needCollSeq ){
50251     assert( pOp>p->aOp );
50252     assert( pOp[-1].p4type==P4_COLLSEQ );
50253     assert( pOp[-1].opcode==OP_CollSeq );
50254     ctx.pColl = pOp[-1].p4.pColl;
50255   }
50256   (ctx.pFunc->xStep)(&ctx, n, apVal);
50257   if( ctx.isError ){
50258     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s));
50259     rc = ctx.isError;
50260   }
50261   sqlite3VdbeMemRelease(&ctx.s);
50262   break;
50263 }
50264
50265 /* Opcode: AggFinal P1 P2 * P4 *
50266 **
50267 ** Execute the finalizer function for an aggregate.  P1 is
50268 ** the memory location that is the accumulator for the aggregate.
50269 **
50270 ** P2 is the number of arguments that the step function takes and
50271 ** P4 is a pointer to the FuncDef for this function.  The P2
50272 ** argument is not used by this opcode.  It is only there to disambiguate
50273 ** functions that can take varying numbers of arguments.  The
50274 ** P4 argument is only needed for the degenerate case where
50275 ** the step function was not previously called.
50276 */
50277 case OP_AggFinal: {
50278   Mem *pMem;
50279   assert( pOp->p1>0 && pOp->p1<=p->nMem );
50280   pMem = &p->aMem[pOp->p1];
50281   assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
50282   rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
50283   if( rc==SQLITE_ERROR ){
50284     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(pMem));
50285   }
50286   sqlite3VdbeChangeEncoding(pMem, encoding);
50287   UPDATE_MAX_BLOBSIZE(pMem);
50288   if( sqlite3VdbeMemTooBig(pMem) ){
50289     goto too_big;
50290   }
50291   break;
50292 }
50293
50294
50295 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
50296 /* Opcode: Vacuum * * * * *
50297 **
50298 ** Vacuum the entire database.  This opcode will cause other virtual
50299 ** machines to be created and run.  It may not be called from within
50300 ** a transaction.
50301 */
50302 case OP_Vacuum: {
50303   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse; 
50304   rc = sqlite3RunVacuum(&p->zErrMsg, db);
50305   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
50306   break;
50307 }
50308 #endif
50309
50310 #if !defined(SQLITE_OMIT_AUTOVACUUM)
50311 /* Opcode: IncrVacuum P1 P2 * * *
50312 **
50313 ** Perform a single step of the incremental vacuum procedure on
50314 ** the P1 database. If the vacuum has finished, jump to instruction
50315 ** P2. Otherwise, fall through to the next instruction.
50316 */
50317 case OP_IncrVacuum: {        /* jump */
50318   Btree *pBt;
50319
50320   assert( pOp->p1>=0 && pOp->p1<db->nDb );
50321   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
50322   pBt = db->aDb[pOp->p1].pBt;
50323   rc = sqlite3BtreeIncrVacuum(pBt);
50324   if( rc==SQLITE_DONE ){
50325     pc = pOp->p2 - 1;
50326     rc = SQLITE_OK;
50327   }
50328   break;
50329 }
50330 #endif
50331
50332 /* Opcode: Expire P1 * * * *
50333 **
50334 ** Cause precompiled statements to become expired. An expired statement
50335 ** fails with an error code of SQLITE_SCHEMA if it is ever executed 
50336 ** (via sqlite3_step()).
50337 ** 
50338 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
50339 ** then only the currently executing statement is affected. 
50340 */
50341 case OP_Expire: {
50342   if( !pOp->p1 ){
50343     sqlite3ExpirePreparedStatements(db);
50344   }else{
50345     p->expired = 1;
50346   }
50347   break;
50348 }
50349
50350 #ifndef SQLITE_OMIT_SHARED_CACHE
50351 /* Opcode: TableLock P1 P2 P3 P4 *
50352 **
50353 ** Obtain a lock on a particular table. This instruction is only used when
50354 ** the shared-cache feature is enabled. 
50355 **
50356 ** If P1 is  the index of the database in sqlite3.aDb[] of the database
50357 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
50358 ** a write lock if P3==1.
50359 **
50360 ** P2 contains the root-page of the table to lock.
50361 **
50362 ** P4 contains a pointer to the name of the table being locked. This is only
50363 ** used to generate an error message if the lock cannot be obtained.
50364 */
50365 case OP_TableLock: {
50366   int p1 = pOp->p1; 
50367   u8 isWriteLock = pOp->p3;
50368   assert( p1>=0 && p1<db->nDb );
50369   assert( (p->btreeMask & (1<<p1))!=0 );
50370   assert( isWriteLock==0 || isWriteLock==1 );
50371   rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
50372   if( rc==SQLITE_LOCKED ){
50373     const char *z = pOp->p4.z;
50374     sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
50375   }
50376   break;
50377 }
50378 #endif /* SQLITE_OMIT_SHARED_CACHE */
50379
50380 #ifndef SQLITE_OMIT_VIRTUALTABLE
50381 /* Opcode: VBegin * * * P4 *
50382 **
50383 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the 
50384 ** xBegin method for that table.
50385 **
50386 ** Also, whether or not P4 is set, check that this is not being called from
50387 ** within a callback to a virtual table xSync() method. If it is, set the
50388 ** error code to SQLITE_LOCKED.
50389 */
50390 case OP_VBegin: {
50391   sqlite3_vtab *pVtab = pOp->p4.pVtab;
50392   rc = sqlite3VtabBegin(db, pVtab);
50393   if( pVtab ){
50394     sqlite3DbFree(db, p->zErrMsg);
50395     p->zErrMsg = pVtab->zErrMsg;
50396     pVtab->zErrMsg = 0;
50397   }
50398   break;
50399 }
50400 #endif /* SQLITE_OMIT_VIRTUALTABLE */
50401
50402 #ifndef SQLITE_OMIT_VIRTUALTABLE
50403 /* Opcode: VCreate P1 * * P4 *
50404 **
50405 ** P4 is the name of a virtual table in database P1. Call the xCreate method
50406 ** for that table.
50407 */
50408 case OP_VCreate: {
50409   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
50410   break;
50411 }
50412 #endif /* SQLITE_OMIT_VIRTUALTABLE */
50413
50414 #ifndef SQLITE_OMIT_VIRTUALTABLE
50415 /* Opcode: VDestroy P1 * * P4 *
50416 **
50417 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
50418 ** of that table.
50419 */
50420 case OP_VDestroy: {
50421   p->inVtabMethod = 2;
50422   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
50423   p->inVtabMethod = 0;
50424   break;
50425 }
50426 #endif /* SQLITE_OMIT_VIRTUALTABLE */
50427
50428 #ifndef SQLITE_OMIT_VIRTUALTABLE
50429 /* Opcode: VOpen P1 * * P4 *
50430 **
50431 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
50432 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
50433 ** table and stores that cursor in P1.
50434 */
50435 case OP_VOpen: {
50436   Cursor *pCur = 0;
50437   sqlite3_vtab_cursor *pVtabCursor = 0;
50438
50439   sqlite3_vtab *pVtab = pOp->p4.pVtab;
50440   sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
50441
50442   assert(pVtab && pModule);
50443   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
50444   rc = pModule->xOpen(pVtab, &pVtabCursor);
50445   sqlite3DbFree(db, p->zErrMsg);
50446   p->zErrMsg = pVtab->zErrMsg;
50447   pVtab->zErrMsg = 0;
50448   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
50449   if( SQLITE_OK==rc ){
50450     /* Initialize sqlite3_vtab_cursor base class */
50451     pVtabCursor->pVtab = pVtab;
50452
50453     /* Initialise vdbe cursor object */
50454     pCur = allocateCursor(p, pOp->p1, &pOp[-1], -1, 0);
50455     if( pCur ){
50456       pCur->pVtabCursor = pVtabCursor;
50457       pCur->pModule = pVtabCursor->pVtab->pModule;
50458     }else{
50459       db->mallocFailed = 1;
50460       pModule->xClose(pVtabCursor);
50461     }
50462   }
50463   break;
50464 }
50465 #endif /* SQLITE_OMIT_VIRTUALTABLE */
50466
50467 #ifndef SQLITE_OMIT_VIRTUALTABLE
50468 /* Opcode: VFilter P1 P2 P3 P4 *
50469 **
50470 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
50471 ** the filtered result set is empty.
50472 **
50473 ** P4 is either NULL or a string that was generated by the xBestIndex
50474 ** method of the module.  The interpretation of the P4 string is left
50475 ** to the module implementation.
50476 **
50477 ** This opcode invokes the xFilter method on the virtual table specified
50478 ** by P1.  The integer query plan parameter to xFilter is stored in register
50479 ** P3. Register P3+1 stores the argc parameter to be passed to the
50480 ** xFilter method. Registers P3+2..P3+1+argc are the argc
50481 ** additional parameters which are passed to
50482 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
50483 **
50484 ** A jump is made to P2 if the result set after filtering would be empty.
50485 */
50486 case OP_VFilter: {   /* jump */
50487   int nArg;
50488   int iQuery;
50489   const sqlite3_module *pModule;
50490   Mem *pQuery = &p->aMem[pOp->p3];
50491   Mem *pArgc = &pQuery[1];
50492   sqlite3_vtab_cursor *pVtabCursor;
50493   sqlite3_vtab *pVtab;
50494
50495   Cursor *pCur = p->apCsr[pOp->p1];
50496
50497   REGISTER_TRACE(pOp->p3, pQuery);
50498   assert( pCur->pVtabCursor );
50499   pVtabCursor = pCur->pVtabCursor;
50500   pVtab = pVtabCursor->pVtab;
50501   pModule = pVtab->pModule;
50502
50503   /* Grab the index number and argc parameters */
50504   assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
50505   nArg = pArgc->u.i;
50506   iQuery = pQuery->u.i;
50507
50508   /* Invoke the xFilter method */
50509   {
50510     int res = 0;
50511     int i;
50512     Mem **apArg = p->apArg;
50513     for(i = 0; i<nArg; i++){
50514       apArg[i] = &pArgc[i+1];
50515       storeTypeInfo(apArg[i], 0);
50516     }
50517
50518     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
50519     sqlite3VtabLock(pVtab);
50520     p->inVtabMethod = 1;
50521     rc = pModule->xFilter(pVtabCursor, iQuery, pOp->p4.z, nArg, apArg);
50522     p->inVtabMethod = 0;
50523     sqlite3DbFree(db, p->zErrMsg);
50524     p->zErrMsg = pVtab->zErrMsg;
50525     pVtab->zErrMsg = 0;
50526     sqlite3VtabUnlock(db, pVtab);
50527     if( rc==SQLITE_OK ){
50528       res = pModule->xEof(pVtabCursor);
50529     }
50530     if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
50531
50532     if( res ){
50533       pc = pOp->p2 - 1;
50534     }
50535   }
50536   pCur->nullRow = 0;
50537
50538   break;
50539 }
50540 #endif /* SQLITE_OMIT_VIRTUALTABLE */
50541
50542 #ifndef SQLITE_OMIT_VIRTUALTABLE
50543 /* Opcode: VRowid P1 P2 * * *
50544 **
50545 ** Store into register P2  the rowid of
50546 ** the virtual-table that the P1 cursor is pointing to.
50547 */
50548 case OP_VRowid: {             /* out2-prerelease */
50549   sqlite3_vtab *pVtab;
50550   const sqlite3_module *pModule;
50551   sqlite_int64 iRow;
50552   Cursor *pCur = p->apCsr[pOp->p1];
50553
50554   assert( pCur->pVtabCursor );
50555   if( pCur->nullRow ){
50556     break;
50557   }
50558   pVtab = pCur->pVtabCursor->pVtab;
50559   pModule = pVtab->pModule;
50560   assert( pModule->xRowid );
50561   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
50562   rc = pModule->xRowid(pCur->pVtabCursor, &iRow);
50563   sqlite3DbFree(db, p->zErrMsg);
50564   p->zErrMsg = pVtab->zErrMsg;
50565   pVtab->zErrMsg = 0;
50566   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
50567   MemSetTypeFlag(pOut, MEM_Int);
50568   pOut->u.i = iRow;
50569   break;
50570 }
50571 #endif /* SQLITE_OMIT_VIRTUALTABLE */
50572
50573 #ifndef SQLITE_OMIT_VIRTUALTABLE
50574 /* Opcode: VColumn P1 P2 P3 * *
50575 **
50576 ** Store the value of the P2-th column of
50577 ** the row of the virtual-table that the 
50578 ** P1 cursor is pointing to into register P3.
50579 */
50580 case OP_VColumn: {
50581   sqlite3_vtab *pVtab;
50582   const sqlite3_module *pModule;
50583   Mem *pDest;
50584   sqlite3_context sContext;
50585
50586   Cursor *pCur = p->apCsr[pOp->p1];
50587   assert( pCur->pVtabCursor );
50588   assert( pOp->p3>0 && pOp->p3<=p->nMem );
50589   pDest = &p->aMem[pOp->p3];
50590   if( pCur->nullRow ){
50591     sqlite3VdbeMemSetNull(pDest);
50592     break;
50593   }
50594   pVtab = pCur->pVtabCursor->pVtab;
50595   pModule = pVtab->pModule;
50596   assert( pModule->xColumn );
50597   memset(&sContext, 0, sizeof(sContext));
50598
50599   /* The output cell may already have a buffer allocated. Move
50600   ** the current contents to sContext.s so in case the user-function 
50601   ** can use the already allocated buffer instead of allocating a 
50602   ** new one.
50603   */
50604   sqlite3VdbeMemMove(&sContext.s, pDest);
50605   MemSetTypeFlag(&sContext.s, MEM_Null);
50606
50607   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
50608   rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
50609   sqlite3DbFree(db, p->zErrMsg);
50610   p->zErrMsg = pVtab->zErrMsg;
50611   pVtab->zErrMsg = 0;
50612
50613   /* Copy the result of the function to the P3 register. We
50614   ** do this regardless of whether or not an error occured to ensure any
50615   ** dynamic allocation in sContext.s (a Mem struct) is  released.
50616   */
50617   sqlite3VdbeChangeEncoding(&sContext.s, encoding);
50618   REGISTER_TRACE(pOp->p3, pDest);
50619   sqlite3VdbeMemMove(pDest, &sContext.s);
50620   UPDATE_MAX_BLOBSIZE(pDest);
50621
50622   if( sqlite3SafetyOn(db) ){
50623     goto abort_due_to_misuse;
50624   }
50625   if( sqlite3VdbeMemTooBig(pDest) ){
50626     goto too_big;
50627   }
50628   break;
50629 }
50630 #endif /* SQLITE_OMIT_VIRTUALTABLE */
50631
50632 #ifndef SQLITE_OMIT_VIRTUALTABLE
50633 /* Opcode: VNext P1 P2 * * *
50634 **
50635 ** Advance virtual table P1 to the next row in its result set and
50636 ** jump to instruction P2.  Or, if the virtual table has reached
50637 ** the end of its result set, then fall through to the next instruction.
50638 */
50639 case OP_VNext: {   /* jump */
50640   sqlite3_vtab *pVtab;
50641   const sqlite3_module *pModule;
50642   int res = 0;
50643
50644   Cursor *pCur = p->apCsr[pOp->p1];
50645   assert( pCur->pVtabCursor );
50646   if( pCur->nullRow ){
50647     break;
50648   }
50649   pVtab = pCur->pVtabCursor->pVtab;
50650   pModule = pVtab->pModule;
50651   assert( pModule->xNext );
50652
50653   /* Invoke the xNext() method of the module. There is no way for the
50654   ** underlying implementation to return an error if one occurs during
50655   ** xNext(). Instead, if an error occurs, true is returned (indicating that 
50656   ** data is available) and the error code returned when xColumn or
50657   ** some other method is next invoked on the save virtual table cursor.
50658   */
50659   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
50660   sqlite3VtabLock(pVtab);
50661   p->inVtabMethod = 1;
50662   rc = pModule->xNext(pCur->pVtabCursor);
50663   p->inVtabMethod = 0;
50664   sqlite3DbFree(db, p->zErrMsg);
50665   p->zErrMsg = pVtab->zErrMsg;
50666   pVtab->zErrMsg = 0;
50667   sqlite3VtabUnlock(db, pVtab);
50668   if( rc==SQLITE_OK ){
50669     res = pModule->xEof(pCur->pVtabCursor);
50670   }
50671   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
50672
50673   if( !res ){
50674     /* If there is data, jump to P2 */
50675     pc = pOp->p2 - 1;
50676   }
50677   break;
50678 }
50679 #endif /* SQLITE_OMIT_VIRTUALTABLE */
50680
50681 #ifndef SQLITE_OMIT_VIRTUALTABLE
50682 /* Opcode: VRename P1 * * P4 *
50683 **
50684 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
50685 ** This opcode invokes the corresponding xRename method. The value
50686 ** in register P1 is passed as the zName argument to the xRename method.
50687 */
50688 case OP_VRename: {
50689   sqlite3_vtab *pVtab = pOp->p4.pVtab;
50690   Mem *pName = &p->aMem[pOp->p1];
50691   assert( pVtab->pModule->xRename );
50692   REGISTER_TRACE(pOp->p1, pName);
50693
50694   Stringify(pName, encoding);
50695
50696   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
50697   sqlite3VtabLock(pVtab);
50698   rc = pVtab->pModule->xRename(pVtab, pName->z);
50699   sqlite3DbFree(db, p->zErrMsg);
50700   p->zErrMsg = pVtab->zErrMsg;
50701   pVtab->zErrMsg = 0;
50702   sqlite3VtabUnlock(db, pVtab);
50703   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
50704
50705   break;
50706 }
50707 #endif
50708
50709 #ifndef SQLITE_OMIT_VIRTUALTABLE
50710 /* Opcode: VUpdate P1 P2 P3 P4 *
50711 **
50712 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
50713 ** This opcode invokes the corresponding xUpdate method. P2 values
50714 ** are contiguous memory cells starting at P3 to pass to the xUpdate 
50715 ** invocation. The value in register (P3+P2-1) corresponds to the 
50716 ** p2th element of the argv array passed to xUpdate.
50717 **
50718 ** The xUpdate method will do a DELETE or an INSERT or both.
50719 ** The argv[0] element (which corresponds to memory cell P3)
50720 ** is the rowid of a row to delete.  If argv[0] is NULL then no 
50721 ** deletion occurs.  The argv[1] element is the rowid of the new 
50722 ** row.  This can be NULL to have the virtual table select the new 
50723 ** rowid for itself.  The subsequent elements in the array are 
50724 ** the values of columns in the new row.
50725 **
50726 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
50727 ** a row to delete.
50728 **
50729 ** P1 is a boolean flag. If it is set to true and the xUpdate call
50730 ** is successful, then the value returned by sqlite3_last_insert_rowid() 
50731 ** is set to the value of the rowid for the row just inserted.
50732 */
50733 case OP_VUpdate: {
50734   sqlite3_vtab *pVtab = pOp->p4.pVtab;
50735   sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
50736   int nArg = pOp->p2;
50737   assert( pOp->p4type==P4_VTAB );
50738   if( pModule->xUpdate==0 ){
50739     sqlite3SetString(&p->zErrMsg, db, "read-only table");
50740     rc = SQLITE_ERROR;
50741   }else{
50742     int i;
50743     sqlite_int64 rowid;
50744     Mem **apArg = p->apArg;
50745     Mem *pX = &p->aMem[pOp->p3];
50746     for(i=0; i<nArg; i++){
50747       storeTypeInfo(pX, 0);
50748       apArg[i] = pX;
50749       pX++;
50750     }
50751     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
50752     sqlite3VtabLock(pVtab);
50753     rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
50754     sqlite3DbFree(db, p->zErrMsg);
50755     p->zErrMsg = pVtab->zErrMsg;
50756     pVtab->zErrMsg = 0;
50757     sqlite3VtabUnlock(db, pVtab);
50758     if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
50759     if( pOp->p1 && rc==SQLITE_OK ){
50760       assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
50761       db->lastRowid = rowid;
50762     }
50763     p->nChange++;
50764   }
50765   break;
50766 }
50767 #endif /* SQLITE_OMIT_VIRTUALTABLE */
50768
50769 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
50770 /* Opcode: Pagecount P1 P2 * * *
50771 **
50772 ** Write the current number of pages in database P1 to memory cell P2.
50773 */
50774 case OP_Pagecount: {            /* out2-prerelease */
50775   int p1 = pOp->p1; 
50776   int nPage;
50777   Pager *pPager = sqlite3BtreePager(db->aDb[p1].pBt);
50778
50779   rc = sqlite3PagerPagecount(pPager, &nPage);
50780   if( rc==SQLITE_OK ){
50781     pOut->flags = MEM_Int;
50782     pOut->u.i = nPage;
50783   }
50784   break;
50785 }
50786 #endif
50787
50788 #ifndef SQLITE_OMIT_TRACE
50789 /* Opcode: Trace * * * P4 *
50790 **
50791 ** If tracing is enabled (by the sqlite3_trace()) interface, then
50792 ** the UTF-8 string contained in P4 is emitted on the trace callback.
50793 */
50794 case OP_Trace: {
50795   if( pOp->p4.z ){
50796     if( db->xTrace ){
50797       db->xTrace(db->pTraceArg, pOp->p4.z);
50798     }
50799 #ifdef SQLITE_DEBUG
50800     if( (db->flags & SQLITE_SqlTrace)!=0 ){
50801       sqlite3DebugPrintf("SQL-trace: %s\n", pOp->p4.z);
50802     }
50803 #endif /* SQLITE_DEBUG */
50804   }
50805   break;
50806 }
50807 #endif
50808
50809
50810 /* Opcode: Noop * * * * *
50811 **
50812 ** Do nothing.  This instruction is often useful as a jump
50813 ** destination.
50814 */
50815 /*
50816 ** The magic Explain opcode are only inserted when explain==2 (which
50817 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
50818 ** This opcode records information from the optimizer.  It is the
50819 ** the same as a no-op.  This opcodesnever appears in a real VM program.
50820 */
50821 default: {          /* This is really OP_Noop and OP_Explain */
50822   break;
50823 }
50824
50825 /*****************************************************************************
50826 ** The cases of the switch statement above this line should all be indented
50827 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
50828 ** readability.  From this point on down, the normal indentation rules are
50829 ** restored.
50830 *****************************************************************************/
50831     }
50832
50833 #ifdef VDBE_PROFILE
50834     {
50835       u64 elapsed = sqlite3Hwtime() - start;
50836       pOp->cycles += elapsed;
50837       pOp->cnt++;
50838 #if 0
50839         fprintf(stdout, "%10llu ", elapsed);
50840         sqlite3VdbePrintOp(stdout, origPc, &p->aOp[origPc]);
50841 #endif
50842     }
50843 #endif
50844
50845     /* The following code adds nothing to the actual functionality
50846     ** of the program.  It is only here for testing and debugging.
50847     ** On the other hand, it does burn CPU cycles every time through
50848     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
50849     */
50850 #ifndef NDEBUG
50851     assert( pc>=-1 && pc<p->nOp );
50852
50853 #ifdef SQLITE_DEBUG
50854     if( p->trace ){
50855       if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
50856       if( opProperty & OPFLG_OUT2_PRERELEASE ){
50857         registerTrace(p->trace, pOp->p2, pOut);
50858       }
50859       if( opProperty & OPFLG_OUT3 ){
50860         registerTrace(p->trace, pOp->p3, pOut);
50861       }
50862     }
50863 #endif  /* SQLITE_DEBUG */
50864 #endif  /* NDEBUG */
50865   }  /* The end of the for(;;) loop the loops through opcodes */
50866
50867   /* If we reach this point, it means that execution is finished with
50868   ** an error of some kind.
50869   */
50870 vdbe_error_halt:
50871   assert( rc );
50872   p->rc = rc;
50873   sqlite3VdbeHalt(p);
50874   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
50875   rc = SQLITE_ERROR;
50876
50877   /* This is the only way out of this procedure.  We have to
50878   ** release the mutexes on btrees that were acquired at the
50879   ** top. */
50880 vdbe_return:
50881   sqlite3BtreeMutexArrayLeave(&p->aMutex);
50882   return rc;
50883
50884   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
50885   ** is encountered.
50886   */
50887 too_big:
50888   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
50889   rc = SQLITE_TOOBIG;
50890   goto vdbe_error_halt;
50891
50892   /* Jump to here if a malloc() fails.
50893   */
50894 no_mem:
50895   db->mallocFailed = 1;
50896   sqlite3SetString(&p->zErrMsg, db, "out of memory");
50897   rc = SQLITE_NOMEM;
50898   goto vdbe_error_halt;
50899
50900   /* Jump to here for an SQLITE_MISUSE error.
50901   */
50902 abort_due_to_misuse:
50903   rc = SQLITE_MISUSE;
50904   /* Fall thru into abort_due_to_error */
50905
50906   /* Jump to here for any other kind of fatal error.  The "rc" variable
50907   ** should hold the error number.
50908   */
50909 abort_due_to_error:
50910   assert( p->zErrMsg==0 );
50911   if( db->mallocFailed ) rc = SQLITE_NOMEM;
50912   if( rc!=SQLITE_IOERR_NOMEM ){
50913     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
50914   }
50915   goto vdbe_error_halt;
50916
50917   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
50918   ** flag.
50919   */
50920 abort_due_to_interrupt:
50921   assert( db->u1.isInterrupted );
50922   rc = SQLITE_INTERRUPT;
50923   p->rc = rc;
50924   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
50925   goto vdbe_error_halt;
50926 }
50927
50928 /************** End of vdbe.c ************************************************/
50929 /************** Begin file vdbeblob.c ****************************************/
50930 /*
50931 ** 2007 May 1
50932 **
50933 ** The author disclaims copyright to this source code.  In place of
50934 ** a legal notice, here is a blessing:
50935 **
50936 **    May you do good and not evil.
50937 **    May you find forgiveness for yourself and forgive others.
50938 **    May you share freely, never taking more than you give.
50939 **
50940 *************************************************************************
50941 **
50942 ** This file contains code used to implement incremental BLOB I/O.
50943 **
50944 ** $Id: vdbeblob.c,v 1.25 2008/07/28 19:34:54 drh Exp $
50945 */
50946
50947
50948 #ifndef SQLITE_OMIT_INCRBLOB
50949
50950 /*
50951 ** Valid sqlite3_blob* handles point to Incrblob structures.
50952 */
50953 typedef struct Incrblob Incrblob;
50954 struct Incrblob {
50955   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
50956   int nByte;              /* Size of open blob, in bytes */
50957   int iOffset;            /* Byte offset of blob in cursor data */
50958   BtCursor *pCsr;         /* Cursor pointing at blob row */
50959   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
50960   sqlite3 *db;            /* The associated database */
50961 };
50962
50963 /*
50964 ** Open a blob handle.
50965 */
50966 SQLITE_API int sqlite3_blob_open(
50967   sqlite3* db,            /* The database connection */
50968   const char *zDb,        /* The attached database containing the blob */
50969   const char *zTable,     /* The table containing the blob */
50970   const char *zColumn,    /* The column containing the blob */
50971   sqlite_int64 iRow,      /* The row containing the glob */
50972   int flags,              /* True -> read/write access, false -> read-only */
50973   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
50974 ){
50975   int nAttempt = 0;
50976   int iCol;               /* Index of zColumn in row-record */
50977
50978   /* This VDBE program seeks a btree cursor to the identified 
50979   ** db/table/row entry. The reason for using a vdbe program instead
50980   ** of writing code to use the b-tree layer directly is that the
50981   ** vdbe program will take advantage of the various transaction,
50982   ** locking and error handling infrastructure built into the vdbe.
50983   **
50984   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
50985   ** Code external to the Vdbe then "borrows" the b-tree cursor and
50986   ** uses it to implement the blob_read(), blob_write() and 
50987   ** blob_bytes() functions.
50988   **
50989   ** The sqlite3_blob_close() function finalizes the vdbe program,
50990   ** which closes the b-tree cursor and (possibly) commits the 
50991   ** transaction.
50992   */
50993   static const VdbeOpList openBlob[] = {
50994     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
50995     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
50996
50997     /* One of the following two instructions is replaced by an
50998     ** OP_Noop before exection.
50999     */
51000     {OP_SetNumColumns, 0, 0, 0},   /* 2: Num cols for cursor */
51001     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
51002     {OP_SetNumColumns, 0, 0, 0},   /* 4: Num cols for cursor */
51003     {OP_OpenWrite, 0, 0, 0},       /* 5: Open cursor 0 for read/write */
51004
51005     {OP_Variable, 1, 1, 0},        /* 6: Push the rowid to the stack */
51006     {OP_NotExists, 0, 10, 1},      /* 7: Seek the cursor */
51007     {OP_Column, 0, 0, 1},          /* 8  */
51008     {OP_ResultRow, 1, 0, 0},       /* 9  */
51009     {OP_Close, 0, 0, 0},           /* 10  */
51010     {OP_Halt, 0, 0, 0},            /* 11 */
51011   };
51012
51013   Vdbe *v = 0;
51014   int rc = SQLITE_OK;
51015   char zErr[128];
51016
51017   zErr[0] = 0;
51018   sqlite3_mutex_enter(db->mutex);
51019   do {
51020     Parse sParse;
51021     Table *pTab;
51022
51023     memset(&sParse, 0, sizeof(Parse));
51024     sParse.db = db;
51025
51026     if( sqlite3SafetyOn(db) ){
51027       sqlite3_mutex_leave(db->mutex);
51028       return SQLITE_MISUSE;
51029     }
51030
51031     sqlite3BtreeEnterAll(db);
51032     pTab = sqlite3LocateTable(&sParse, 0, zTable, zDb);
51033     if( pTab && IsVirtual(pTab) ){
51034       pTab = 0;
51035       sqlite3ErrorMsg(&sParse, "cannot open virtual table: %s", zTable);
51036     }
51037 #ifndef SQLITE_OMIT_VIEW
51038     if( pTab && pTab->pSelect ){
51039       pTab = 0;
51040       sqlite3ErrorMsg(&sParse, "cannot open view: %s", zTable);
51041     }
51042 #endif
51043     if( !pTab ){
51044       if( sParse.zErrMsg ){
51045         sqlite3_snprintf(sizeof(zErr), zErr, "%s", sParse.zErrMsg);
51046       }
51047       sqlite3DbFree(db, sParse.zErrMsg);
51048       rc = SQLITE_ERROR;
51049       (void)sqlite3SafetyOff(db);
51050       sqlite3BtreeLeaveAll(db);
51051       goto blob_open_out;
51052     }
51053
51054     /* Now search pTab for the exact column. */
51055     for(iCol=0; iCol < pTab->nCol; iCol++) {
51056       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
51057         break;
51058       }
51059     }
51060     if( iCol==pTab->nCol ){
51061       sqlite3_snprintf(sizeof(zErr), zErr, "no such column: \"%s\"", zColumn);
51062       rc = SQLITE_ERROR;
51063       (void)sqlite3SafetyOff(db);
51064       sqlite3BtreeLeaveAll(db);
51065       goto blob_open_out;
51066     }
51067
51068     /* If the value is being opened for writing, check that the
51069     ** column is not indexed. It is against the rules to open an
51070     ** indexed column for writing.
51071     */
51072     if( flags ){
51073       Index *pIdx;
51074       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
51075         int j;
51076         for(j=0; j<pIdx->nColumn; j++){
51077           if( pIdx->aiColumn[j]==iCol ){
51078             sqlite3_snprintf(sizeof(zErr), zErr,
51079                              "cannot open indexed column for writing");
51080             rc = SQLITE_ERROR;
51081             (void)sqlite3SafetyOff(db);
51082             sqlite3BtreeLeaveAll(db);
51083             goto blob_open_out;
51084           }
51085         }
51086       }
51087     }
51088
51089     v = sqlite3VdbeCreate(db);
51090     if( v ){
51091       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
51092       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
51093
51094       /* Configure the OP_Transaction */
51095       sqlite3VdbeChangeP1(v, 0, iDb);
51096       sqlite3VdbeChangeP2(v, 0, (flags ? 1 : 0));
51097
51098       /* Configure the OP_VerifyCookie */
51099       sqlite3VdbeChangeP1(v, 1, iDb);
51100       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
51101
51102       /* Make sure a mutex is held on the table to be accessed */
51103       sqlite3VdbeUsesBtree(v, iDb); 
51104
51105       /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
51106       ** parameter of the other to pTab->tnum. 
51107       */
51108       sqlite3VdbeChangeToNoop(v, (flags ? 3 : 5), 1);
51109       sqlite3VdbeChangeP2(v, (flags ? 5 : 3), pTab->tnum);
51110       sqlite3VdbeChangeP3(v, (flags ? 5 : 3), iDb);
51111
51112       /* Configure the OP_SetNumColumns. Configure the cursor to
51113       ** think that the table has one more column than it really
51114       ** does. An OP_Column to retrieve this imaginary column will
51115       ** always return an SQL NULL. This is useful because it means
51116       ** we can invoke OP_Column to fill in the vdbe cursors type 
51117       ** and offset cache without causing any IO.
51118       */
51119       sqlite3VdbeChangeP2(v, flags ? 4 : 2, pTab->nCol+1);
51120       sqlite3VdbeChangeP2(v, 8, pTab->nCol);
51121       if( !db->mallocFailed ){
51122         sqlite3VdbeMakeReady(v, 1, 1, 1, 0);
51123       }
51124     }
51125    
51126     sqlite3BtreeLeaveAll(db);
51127     rc = sqlite3SafetyOff(db);
51128     if( rc!=SQLITE_OK || db->mallocFailed ){
51129       goto blob_open_out;
51130     }
51131
51132     sqlite3_bind_int64((sqlite3_stmt *)v, 1, iRow);
51133     rc = sqlite3_step((sqlite3_stmt *)v);
51134     if( rc!=SQLITE_ROW ){
51135       nAttempt++;
51136       rc = sqlite3_finalize((sqlite3_stmt *)v);
51137       sqlite3_snprintf(sizeof(zErr), zErr, sqlite3_errmsg(db));
51138       v = 0;
51139     }
51140   } while( nAttempt<5 && rc==SQLITE_SCHEMA );
51141
51142   if( rc==SQLITE_ROW ){
51143     /* The row-record has been opened successfully. Check that the
51144     ** column in question contains text or a blob. If it contains
51145     ** text, it is up to the caller to get the encoding right.
51146     */
51147     Incrblob *pBlob;
51148     u32 type = v->apCsr[0]->aType[iCol];
51149
51150     if( type<12 ){
51151       sqlite3_snprintf(sizeof(zErr), zErr, "cannot open value of type %s",
51152           type==0?"null": type==7?"real": "integer"
51153       );
51154       rc = SQLITE_ERROR;
51155       goto blob_open_out;
51156     }
51157     pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
51158     if( db->mallocFailed ){
51159       sqlite3DbFree(db, pBlob);
51160       goto blob_open_out;
51161     }
51162     pBlob->flags = flags;
51163     pBlob->pCsr =  v->apCsr[0]->pCursor;
51164     sqlite3BtreeEnterCursor(pBlob->pCsr);
51165     sqlite3BtreeCacheOverflow(pBlob->pCsr);
51166     sqlite3BtreeLeaveCursor(pBlob->pCsr);
51167     pBlob->pStmt = (sqlite3_stmt *)v;
51168     pBlob->iOffset = v->apCsr[0]->aOffset[iCol];
51169     pBlob->nByte = sqlite3VdbeSerialTypeLen(type);
51170     pBlob->db = db;
51171     *ppBlob = (sqlite3_blob *)pBlob;
51172     rc = SQLITE_OK;
51173   }else if( rc==SQLITE_OK ){
51174     sqlite3_snprintf(sizeof(zErr), zErr, "no such rowid: %lld", iRow);
51175     rc = SQLITE_ERROR;
51176   }
51177
51178 blob_open_out:
51179   zErr[sizeof(zErr)-1] = '\0';
51180   if( rc!=SQLITE_OK || db->mallocFailed ){
51181     sqlite3_finalize((sqlite3_stmt *)v);
51182   }
51183   sqlite3Error(db, rc, (rc==SQLITE_OK?0:zErr));
51184   rc = sqlite3ApiExit(db, rc);
51185   sqlite3_mutex_leave(db->mutex);
51186   return rc;
51187 }
51188
51189 /*
51190 ** Close a blob handle that was previously created using
51191 ** sqlite3_blob_open().
51192 */
51193 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
51194   Incrblob *p = (Incrblob *)pBlob;
51195   int rc;
51196
51197   rc = sqlite3_finalize(p->pStmt);
51198   sqlite3DbFree(p->db, p);
51199   return rc;
51200 }
51201
51202 /*
51203 ** Perform a read or write operation on a blob
51204 */
51205 static int blobReadWrite(
51206   sqlite3_blob *pBlob, 
51207   void *z, 
51208   int n, 
51209   int iOffset, 
51210   int (*xCall)(BtCursor*, u32, u32, void*)
51211 ){
51212   int rc;
51213   Incrblob *p = (Incrblob *)pBlob;
51214   Vdbe *v;
51215   sqlite3 *db = p->db;  
51216
51217   /* Request is out of range. Return a transient error. */
51218   if( (iOffset+n)>p->nByte ){
51219     return SQLITE_ERROR;
51220   }
51221   sqlite3_mutex_enter(db->mutex);
51222
51223   /* If there is no statement handle, then the blob-handle has
51224   ** already been invalidated. Return SQLITE_ABORT in this case.
51225   */
51226   v = (Vdbe*)p->pStmt;
51227   if( v==0 ){
51228     rc = SQLITE_ABORT;
51229   }else{
51230     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
51231     ** returned, clean-up the statement handle.
51232     */
51233     assert( db == v->db );
51234     sqlite3BtreeEnterCursor(p->pCsr);
51235     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
51236     sqlite3BtreeLeaveCursor(p->pCsr);
51237     if( rc==SQLITE_ABORT ){
51238       sqlite3VdbeFinalize(v);
51239       p->pStmt = 0;
51240     }else{
51241       db->errCode = rc;
51242       v->rc = rc;
51243     }
51244   }
51245   rc = sqlite3ApiExit(db, rc);
51246   sqlite3_mutex_leave(db->mutex);
51247   return rc;
51248 }
51249
51250 /*
51251 ** Read data from a blob handle.
51252 */
51253 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
51254   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
51255 }
51256
51257 /*
51258 ** Write data to a blob handle.
51259 */
51260 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
51261   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
51262 }
51263
51264 /*
51265 ** Query a blob handle for the size of the data.
51266 **
51267 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
51268 ** so no mutex is required for access.
51269 */
51270 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
51271   Incrblob *p = (Incrblob *)pBlob;
51272   return p->nByte;
51273 }
51274
51275 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
51276
51277 /************** End of vdbeblob.c ********************************************/
51278 /************** Begin file journal.c *****************************************/
51279 /*
51280 ** 2007 August 22
51281 **
51282 ** The author disclaims copyright to this source code.  In place of
51283 ** a legal notice, here is a blessing:
51284 **
51285 **    May you do good and not evil.
51286 **    May you find forgiveness for yourself and forgive others.
51287 **    May you share freely, never taking more than you give.
51288 **
51289 *************************************************************************
51290 **
51291 ** @(#) $Id: journal.c,v 1.8 2008/05/01 18:01:47 drh Exp $
51292 */
51293
51294 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
51295
51296 /*
51297 ** This file implements a special kind of sqlite3_file object used
51298 ** by SQLite to create journal files if the atomic-write optimization
51299 ** is enabled.
51300 **
51301 ** The distinctive characteristic of this sqlite3_file is that the
51302 ** actual on disk file is created lazily. When the file is created,
51303 ** the caller specifies a buffer size for an in-memory buffer to
51304 ** be used to service read() and write() requests. The actual file
51305 ** on disk is not created or populated until either:
51306 **
51307 **   1) The in-memory representation grows too large for the allocated 
51308 **      buffer, or
51309 **   2) The xSync() method is called.
51310 */
51311
51312
51313
51314 /*
51315 ** A JournalFile object is a subclass of sqlite3_file used by
51316 ** as an open file handle for journal files.
51317 */
51318 struct JournalFile {
51319   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
51320   int nBuf;                       /* Size of zBuf[] in bytes */
51321   char *zBuf;                     /* Space to buffer journal writes */
51322   int iSize;                      /* Amount of zBuf[] currently used */
51323   int flags;                      /* xOpen flags */
51324   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
51325   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
51326   const char *zJournal;           /* Name of the journal file */
51327 };
51328 typedef struct JournalFile JournalFile;
51329
51330 /*
51331 ** If it does not already exists, create and populate the on-disk file 
51332 ** for JournalFile p.
51333 */
51334 static int createFile(JournalFile *p){
51335   int rc = SQLITE_OK;
51336   if( !p->pReal ){
51337     sqlite3_file *pReal = (sqlite3_file *)&p[1];
51338     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
51339     if( rc==SQLITE_OK ){
51340       p->pReal = pReal;
51341       if( p->iSize>0 ){
51342         assert(p->iSize<=p->nBuf);
51343         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
51344       }
51345     }
51346   }
51347   return rc;
51348 }
51349
51350 /*
51351 ** Close the file.
51352 */
51353 static int jrnlClose(sqlite3_file *pJfd){
51354   JournalFile *p = (JournalFile *)pJfd;
51355   if( p->pReal ){
51356     sqlite3OsClose(p->pReal);
51357   }
51358   sqlite3_free(p->zBuf);
51359   return SQLITE_OK;
51360 }
51361
51362 /*
51363 ** Read data from the file.
51364 */
51365 static int jrnlRead(
51366   sqlite3_file *pJfd,    /* The journal file from which to read */
51367   void *zBuf,            /* Put the results here */
51368   int iAmt,              /* Number of bytes to read */
51369   sqlite_int64 iOfst     /* Begin reading at this offset */
51370 ){
51371   int rc = SQLITE_OK;
51372   JournalFile *p = (JournalFile *)pJfd;
51373   if( p->pReal ){
51374     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
51375   }else{
51376     assert( iAmt+iOfst<=p->iSize );
51377     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
51378   }
51379   return rc;
51380 }
51381
51382 /*
51383 ** Write data to the file.
51384 */
51385 static int jrnlWrite(
51386   sqlite3_file *pJfd,    /* The journal file into which to write */
51387   const void *zBuf,      /* Take data to be written from here */
51388   int iAmt,              /* Number of bytes to write */
51389   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
51390 ){
51391   int rc = SQLITE_OK;
51392   JournalFile *p = (JournalFile *)pJfd;
51393   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
51394     rc = createFile(p);
51395   }
51396   if( rc==SQLITE_OK ){
51397     if( p->pReal ){
51398       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
51399     }else{
51400       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
51401       if( p->iSize<(iOfst+iAmt) ){
51402         p->iSize = (iOfst+iAmt);
51403       }
51404     }
51405   }
51406   return rc;
51407 }
51408
51409 /*
51410 ** Truncate the file.
51411 */
51412 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
51413   int rc = SQLITE_OK;
51414   JournalFile *p = (JournalFile *)pJfd;
51415   if( p->pReal ){
51416     rc = sqlite3OsTruncate(p->pReal, size);
51417   }else if( size<p->iSize ){
51418     p->iSize = size;
51419   }
51420   return rc;
51421 }
51422
51423 /*
51424 ** Sync the file.
51425 */
51426 static int jrnlSync(sqlite3_file *pJfd, int flags){
51427   int rc;
51428   JournalFile *p = (JournalFile *)pJfd;
51429   if( p->pReal ){
51430     rc = sqlite3OsSync(p->pReal, flags);
51431   }else{
51432     rc = SQLITE_OK;
51433   }
51434   return rc;
51435 }
51436
51437 /*
51438 ** Query the size of the file in bytes.
51439 */
51440 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
51441   int rc = SQLITE_OK;
51442   JournalFile *p = (JournalFile *)pJfd;
51443   if( p->pReal ){
51444     rc = sqlite3OsFileSize(p->pReal, pSize);
51445   }else{
51446     *pSize = (sqlite_int64) p->iSize;
51447   }
51448   return rc;
51449 }
51450
51451 /*
51452 ** Table of methods for JournalFile sqlite3_file object.
51453 */
51454 static struct sqlite3_io_methods JournalFileMethods = {
51455   1,             /* iVersion */
51456   jrnlClose,     /* xClose */
51457   jrnlRead,      /* xRead */
51458   jrnlWrite,     /* xWrite */
51459   jrnlTruncate,  /* xTruncate */
51460   jrnlSync,      /* xSync */
51461   jrnlFileSize,  /* xFileSize */
51462   0,             /* xLock */
51463   0,             /* xUnlock */
51464   0,             /* xCheckReservedLock */
51465   0,             /* xFileControl */
51466   0,             /* xSectorSize */
51467   0              /* xDeviceCharacteristics */
51468 };
51469
51470 /* 
51471 ** Open a journal file.
51472 */
51473 SQLITE_PRIVATE int sqlite3JournalOpen(
51474   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
51475   const char *zName,         /* Name of the journal file */
51476   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
51477   int flags,                 /* Opening flags */
51478   int nBuf                   /* Bytes buffered before opening the file */
51479 ){
51480   JournalFile *p = (JournalFile *)pJfd;
51481   memset(p, 0, sqlite3JournalSize(pVfs));
51482   if( nBuf>0 ){
51483     p->zBuf = sqlite3MallocZero(nBuf);
51484     if( !p->zBuf ){
51485       return SQLITE_NOMEM;
51486     }
51487   }else{
51488     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
51489   }
51490   p->pMethod = &JournalFileMethods;
51491   p->nBuf = nBuf;
51492   p->flags = flags;
51493   p->zJournal = zName;
51494   p->pVfs = pVfs;
51495   return SQLITE_OK;
51496 }
51497
51498 /*
51499 ** If the argument p points to a JournalFile structure, and the underlying
51500 ** file has not yet been created, create it now.
51501 */
51502 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
51503   if( p->pMethods!=&JournalFileMethods ){
51504     return SQLITE_OK;
51505   }
51506   return createFile((JournalFile *)p);
51507 }
51508
51509 /* 
51510 ** Return the number of bytes required to store a JournalFile that uses vfs
51511 ** pVfs to create the underlying on-disk files.
51512 */
51513 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
51514   return (pVfs->szOsFile+sizeof(JournalFile));
51515 }
51516 #endif
51517
51518 /************** End of journal.c *********************************************/
51519 /************** Begin file walker.c ******************************************/
51520 /*
51521 ** 2008 August 16
51522 **
51523 ** The author disclaims copyright to this source code.  In place of
51524 ** a legal notice, here is a blessing:
51525 **
51526 **    May you do good and not evil.
51527 **    May you find forgiveness for yourself and forgive others.
51528 **    May you share freely, never taking more than you give.
51529 **
51530 *************************************************************************
51531 ** This file contains routines used for walking the parser tree for
51532 ** an SQL statement.
51533 **
51534 ** $Id: walker.c,v 1.1 2008/08/20 16:35:10 drh Exp $
51535 */
51536
51537
51538 /*
51539 ** Walk an expression tree.  Invoke the callback once for each node
51540 ** of the expression, while decending.  (In other words, the callback
51541 ** is invoked before visiting children.)
51542 **
51543 ** The return value from the callback should be one of the WRC_*
51544 ** constants to specify how to proceed with the walk.
51545 **
51546 **    WRC_Continue      Continue descending down the tree.
51547 **
51548 **    WRC_Prune         Do not descend into child nodes.  But allow
51549 **                      the walk to continue with sibling nodes.
51550 **
51551 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
51552 **                      return the top-level walk call.
51553 **
51554 ** The return value from this routine is WRC_Abort to abandon the tree walk
51555 ** and WRC_Continue to continue.
51556 */
51557 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
51558   int rc;
51559   if( pExpr==0 ) return WRC_Continue;
51560   rc = pWalker->xExprCallback(pWalker, pExpr);
51561   if( rc==WRC_Continue ){
51562     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
51563     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
51564     if( sqlite3WalkExprList(pWalker, pExpr->pList) ) return WRC_Abort;
51565     if( sqlite3WalkSelect(pWalker, pExpr->pSelect) ){
51566       return WRC_Abort;
51567     }
51568   }
51569   return rc & WRC_Abort;
51570 }
51571
51572 /*
51573 ** Call sqlite3WalkExpr() for every expression in list p or until
51574 ** an abort request is seen.
51575 */
51576 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
51577   int i, rc = WRC_Continue;
51578   struct ExprList_item *pItem;
51579   if( p ){
51580     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
51581       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
51582     }
51583   }
51584   return rc & WRC_Continue;
51585 }
51586
51587 /*
51588 ** Walk all expressions associated with SELECT statement p.  Do
51589 ** not invoke the SELECT callback on p, but do (of course) invoke
51590 ** any expr callbacks and SELECT callbacks that come from subqueries.
51591 ** Return WRC_Abort or WRC_Continue.
51592 */
51593 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
51594   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
51595   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
51596   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
51597   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
51598   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
51599   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
51600   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
51601   return WRC_Continue;
51602 }
51603
51604 /*
51605 ** Walk the parse trees associated with all subqueries in the
51606 ** FROM clause of SELECT statement p.  Do not invoke the select
51607 ** callback on p, but do invoke it on each FROM clause subquery
51608 ** and on any subqueries further down in the tree.  Return 
51609 ** WRC_Abort or WRC_Continue;
51610 */
51611 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
51612   SrcList *pSrc;
51613   int i;
51614   struct SrcList_item *pItem;
51615
51616   pSrc = p->pSrc;
51617   if( pSrc ){
51618     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
51619       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
51620         return WRC_Abort;
51621       }
51622     }
51623   }
51624   return WRC_Continue;
51625
51626
51627 /*
51628 ** Call sqlite3WalkExpr() for every expression in Select statement p.
51629 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
51630 ** on the compound select chain, p->pPrior.
51631 **
51632 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
51633 ** there is an abort request.
51634 **
51635 ** If the Walker does not have an xSelectCallback() then this routine
51636 ** is a no-op returning WRC_Continue.
51637 */
51638 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
51639   int rc;
51640   if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
51641   rc = WRC_Continue;
51642   while( p  ){
51643     rc = pWalker->xSelectCallback(pWalker, p);
51644     if( rc ) break;
51645     if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
51646     if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
51647     p = p->pPrior;
51648   }
51649   return rc & WRC_Abort;
51650 }
51651
51652 /************** End of walker.c **********************************************/
51653 /************** Begin file resolve.c *****************************************/
51654 /*
51655 ** 2008 August 18
51656 **
51657 ** The author disclaims copyright to this source code.  In place of
51658 ** a legal notice, here is a blessing:
51659 **
51660 **    May you do good and not evil.
51661 **    May you find forgiveness for yourself and forgive others.
51662 **    May you share freely, never taking more than you give.
51663 **
51664 *************************************************************************
51665 **
51666 ** This file contains routines used for walking the parser tree and
51667 ** resolve all identifiers by associating them with a particular
51668 ** table and column.
51669 **
51670 ** $Id: resolve.c,v 1.5 2008/08/29 02:14:03 drh Exp $
51671 */
51672
51673 /*
51674 ** Turn the pExpr expression into an alias for the iCol-th column of the
51675 ** result set in pEList.
51676 **
51677 ** If the result set column is a simple column reference, then this routine
51678 ** makes an exact copy.  But for any other kind of expression, this
51679 ** routine make a copy of the result set column as the argument to the
51680 ** TK_AS operator.  The TK_AS operator causes the expression to be
51681 ** evaluated just once and then reused for each alias.
51682 **
51683 ** The reason for suppressing the TK_AS term when the expression is a simple
51684 ** column reference is so that the column reference will be recognized as
51685 ** usable by indices within the WHERE clause processing logic. 
51686 **
51687 ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
51688 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
51689 **
51690 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
51691 **
51692 ** Is equivalent to:
51693 **
51694 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
51695 **
51696 ** The result of random()%5 in the GROUP BY clause is probably different
51697 ** from the result in the result-set.  We might fix this someday.  Or
51698 ** then again, we might not...
51699 */
51700 static void resolveAlias(
51701   Parse *pParse,         /* Parsing context */
51702   ExprList *pEList,      /* A result set */
51703   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
51704   Expr *pExpr,           /* Transform this into an alias to the result set */
51705   const char *zType      /* "GROUP" or "ORDER" or "" */
51706 ){
51707   Expr *pOrig;           /* The iCol-th column of the result set */
51708   Expr *pDup;            /* Copy of pOrig */
51709   sqlite3 *db;           /* The database connection */
51710
51711   assert( iCol>=0 && iCol<pEList->nExpr );
51712   pOrig = pEList->a[iCol].pExpr;
51713   assert( pOrig!=0 );
51714   assert( pOrig->flags & EP_Resolved );
51715   db = pParse->db;
51716   pDup = sqlite3ExprDup(db, pOrig);
51717   if( pDup==0 ) return;
51718   if( pDup->op!=TK_COLUMN && zType[0]!='G' ){
51719     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
51720     if( pDup==0 ) return;
51721     if( pEList->a[iCol].iAlias==0 ){
51722       pEList->a[iCol].iAlias = ++pParse->nAlias;
51723     }
51724     pDup->iTable = pEList->a[iCol].iAlias;
51725   }
51726   if( pExpr->flags & EP_ExpCollate ){
51727     pDup->pColl = pExpr->pColl;
51728     pDup->flags |= EP_ExpCollate;
51729   }
51730   if( pExpr->span.dyn ) sqlite3DbFree(db, (char*)pExpr->span.z);
51731   if( pExpr->token.dyn ) sqlite3DbFree(db, (char*)pExpr->token.z);
51732   memcpy(pExpr, pDup, sizeof(*pExpr));
51733   sqlite3DbFree(db, pDup);
51734 }
51735
51736 /*
51737 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
51738 ** that name in the set of source tables in pSrcList and make the pExpr 
51739 ** expression node refer back to that source column.  The following changes
51740 ** are made to pExpr:
51741 **
51742 **    pExpr->iDb           Set the index in db->aDb[] of the database X
51743 **                         (even if X is implied).
51744 **    pExpr->iTable        Set to the cursor number for the table obtained
51745 **                         from pSrcList.
51746 **    pExpr->pTab          Points to the Table structure of X.Y (even if
51747 **                         X and/or Y are implied.)
51748 **    pExpr->iColumn       Set to the column number within the table.
51749 **    pExpr->op            Set to TK_COLUMN.
51750 **    pExpr->pLeft         Any expression this points to is deleted
51751 **    pExpr->pRight        Any expression this points to is deleted.
51752 **
51753 ** The pDbToken is the name of the database (the "X").  This value may be
51754 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
51755 ** can be used.  The pTableToken is the name of the table (the "Y").  This
51756 ** value can be NULL if pDbToken is also NULL.  If pTableToken is NULL it
51757 ** means that the form of the name is Z and that columns from any table
51758 ** can be used.
51759 **
51760 ** If the name cannot be resolved unambiguously, leave an error message
51761 ** in pParse and return non-zero.  Return zero on success.
51762 */
51763 static int lookupName(
51764   Parse *pParse,       /* The parsing context */
51765   Token *pDbToken,     /* Name of the database containing table, or NULL */
51766   Token *pTableToken,  /* Name of table containing column, or NULL */
51767   Token *pColumnToken, /* Name of the column. */
51768   NameContext *pNC,    /* The name context used to resolve the name */
51769   Expr *pExpr          /* Make this EXPR node point to the selected column */
51770 ){
51771   char *zDb = 0;       /* Name of the database.  The "X" in X.Y.Z */
51772   char *zTab = 0;      /* Name of the table.  The "Y" in X.Y.Z or Y.Z */
51773   char *zCol = 0;      /* Name of the column.  The "Z" */
51774   int i, j;            /* Loop counters */
51775   int cnt = 0;                      /* Number of matching column names */
51776   int cntTab = 0;                   /* Number of matching table names */
51777   sqlite3 *db = pParse->db;         /* The database connection */
51778   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
51779   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
51780   NameContext *pTopNC = pNC;        /* First namecontext in the list */
51781   Schema *pSchema = 0;              /* Schema of the expression */
51782
51783   assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
51784
51785   /* Dequote and zero-terminate the names */
51786   zDb = sqlite3NameFromToken(db, pDbToken);
51787   zTab = sqlite3NameFromToken(db, pTableToken);
51788   zCol = sqlite3NameFromToken(db, pColumnToken);
51789   if( db->mallocFailed ){
51790     goto lookupname_end;
51791   }
51792
51793   /* Initialize the node to no-match */
51794   pExpr->iTable = -1;
51795   pExpr->pTab = 0;
51796
51797   /* Start at the inner-most context and move outward until a match is found */
51798   while( pNC && cnt==0 ){
51799     ExprList *pEList;
51800     SrcList *pSrcList = pNC->pSrcList;
51801
51802     if( pSrcList ){
51803       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
51804         Table *pTab;
51805         int iDb;
51806         Column *pCol;
51807   
51808         pTab = pItem->pTab;
51809         assert( pTab!=0 && pTab->zName!=0 );
51810         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
51811         assert( pTab->nCol>0 );
51812         if( zTab ){
51813           if( pItem->zAlias ){
51814             char *zTabName = pItem->zAlias;
51815             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
51816           }else{
51817             char *zTabName = pTab->zName;
51818             if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
51819             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
51820               continue;
51821             }
51822           }
51823         }
51824         if( 0==(cntTab++) ){
51825           pExpr->iTable = pItem->iCursor;
51826           pExpr->pTab = pTab;
51827           pSchema = pTab->pSchema;
51828           pMatch = pItem;
51829         }
51830         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
51831           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
51832             IdList *pUsing;
51833             cnt++;
51834             pExpr->iTable = pItem->iCursor;
51835             pExpr->pTab = pTab;
51836             pMatch = pItem;
51837             pSchema = pTab->pSchema;
51838             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
51839             pExpr->iColumn = j==pTab->iPKey ? -1 : j;
51840             if( i<pSrcList->nSrc-1 ){
51841               if( pItem[1].jointype & JT_NATURAL ){
51842                 /* If this match occurred in the left table of a natural join,
51843                 ** then skip the right table to avoid a duplicate match */
51844                 pItem++;
51845                 i++;
51846               }else if( (pUsing = pItem[1].pUsing)!=0 ){
51847                 /* If this match occurs on a column that is in the USING clause
51848                 ** of a join, skip the search of the right table of the join
51849                 ** to avoid a duplicate match there. */
51850                 int k;
51851                 for(k=0; k<pUsing->nId; k++){
51852                   if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
51853                     pItem++;
51854                     i++;
51855                     break;
51856                   }
51857                 }
51858               }
51859             }
51860             break;
51861           }
51862         }
51863       }
51864     }
51865
51866 #ifndef SQLITE_OMIT_TRIGGER
51867     /* If we have not already resolved the name, then maybe 
51868     ** it is a new.* or old.* trigger argument reference
51869     */
51870     if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
51871       TriggerStack *pTriggerStack = pParse->trigStack;
51872       Table *pTab = 0;
51873       u32 *piColMask;
51874       if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
51875         pExpr->iTable = pTriggerStack->newIdx;
51876         assert( pTriggerStack->pTab );
51877         pTab = pTriggerStack->pTab;
51878         piColMask = &(pTriggerStack->newColMask);
51879       }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
51880         pExpr->iTable = pTriggerStack->oldIdx;
51881         assert( pTriggerStack->pTab );
51882         pTab = pTriggerStack->pTab;
51883         piColMask = &(pTriggerStack->oldColMask);
51884       }
51885
51886       if( pTab ){ 
51887         int iCol;
51888         Column *pCol = pTab->aCol;
51889
51890         pSchema = pTab->pSchema;
51891         cntTab++;
51892         for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) {
51893           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
51894             cnt++;
51895             pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
51896             pExpr->pTab = pTab;
51897             if( iCol>=0 ){
51898               testcase( iCol==31 );
51899               testcase( iCol==32 );
51900               *piColMask |= ((u32)1<<iCol) | (iCol>=32?0xffffffff:0);
51901             }
51902             break;
51903           }
51904         }
51905       }
51906     }
51907 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
51908
51909     /*
51910     ** Perhaps the name is a reference to the ROWID
51911     */
51912     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
51913       cnt = 1;
51914       pExpr->iColumn = -1;
51915       pExpr->affinity = SQLITE_AFF_INTEGER;
51916     }
51917
51918     /*
51919     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
51920     ** might refer to an result-set alias.  This happens, for example, when
51921     ** we are resolving names in the WHERE clause of the following command:
51922     **
51923     **     SELECT a+b AS x FROM table WHERE x<10;
51924     **
51925     ** In cases like this, replace pExpr with a copy of the expression that
51926     ** forms the result set entry ("a+b" in the example) and return immediately.
51927     ** Note that the expression in the result set should have already been
51928     ** resolved by the time the WHERE clause is resolved.
51929     */
51930     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
51931       for(j=0; j<pEList->nExpr; j++){
51932         char *zAs = pEList->a[j].zName;
51933         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
51934           Expr *pOrig;
51935           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
51936           assert( pExpr->pList==0 );
51937           assert( pExpr->pSelect==0 );
51938           pOrig = pEList->a[j].pExpr;
51939           if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
51940             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
51941             sqlite3DbFree(db, zCol);
51942             return 2;
51943           }
51944           resolveAlias(pParse, pEList, j, pExpr, "");
51945           cnt = 1;
51946           pMatch = 0;
51947           assert( zTab==0 && zDb==0 );
51948           goto lookupname_end_2;
51949         }
51950       } 
51951     }
51952
51953     /* Advance to the next name context.  The loop will exit when either
51954     ** we have a match (cnt>0) or when we run out of name contexts.
51955     */
51956     if( cnt==0 ){
51957       pNC = pNC->pNext;
51958     }
51959   }
51960
51961   /*
51962   ** If X and Y are NULL (in other words if only the column name Z is
51963   ** supplied) and the value of Z is enclosed in double-quotes, then
51964   ** Z is a string literal if it doesn't match any column names.  In that
51965   ** case, we need to return right away and not make any changes to
51966   ** pExpr.
51967   **
51968   ** Because no reference was made to outer contexts, the pNC->nRef
51969   ** fields are not changed in any context.
51970   */
51971   if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
51972     sqlite3DbFree(db, zCol);
51973     pExpr->op = TK_STRING;
51974     return 0;
51975   }
51976
51977   /*
51978   ** cnt==0 means there was not match.  cnt>1 means there were two or
51979   ** more matches.  Either way, we have an error.
51980   */
51981   if( cnt!=1 ){
51982     const char *zErr;
51983     zErr = cnt==0 ? "no such column" : "ambiguous column name";
51984     if( zDb ){
51985       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
51986     }else if( zTab ){
51987       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
51988     }else{
51989       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
51990     }
51991     pTopNC->nErr++;
51992   }
51993
51994   /* If a column from a table in pSrcList is referenced, then record
51995   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
51996   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
51997   ** column number is greater than the number of bits in the bitmask
51998   ** then set the high-order bit of the bitmask.
51999   */
52000   if( pExpr->iColumn>=0 && pMatch!=0 ){
52001     int n = pExpr->iColumn;
52002     testcase( n==sizeof(Bitmask)*8-1 );
52003     if( n>=sizeof(Bitmask)*8 ){
52004       n = sizeof(Bitmask)*8-1;
52005     }
52006     assert( pMatch->iCursor==pExpr->iTable );
52007     pMatch->colUsed |= ((Bitmask)1)<<n;
52008   }
52009
52010 lookupname_end:
52011   /* Clean up and return
52012   */
52013   sqlite3DbFree(db, zDb);
52014   sqlite3DbFree(db, zTab);
52015   sqlite3ExprDelete(db, pExpr->pLeft);
52016   pExpr->pLeft = 0;
52017   sqlite3ExprDelete(db, pExpr->pRight);
52018   pExpr->pRight = 0;
52019   pExpr->op = TK_COLUMN;
52020 lookupname_end_2:
52021   sqlite3DbFree(db, zCol);
52022   if( cnt==1 ){
52023     assert( pNC!=0 );
52024     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
52025     /* Increment the nRef value on all name contexts from TopNC up to
52026     ** the point where the name matched. */
52027     for(;;){
52028       assert( pTopNC!=0 );
52029       pTopNC->nRef++;
52030       if( pTopNC==pNC ) break;
52031       pTopNC = pTopNC->pNext;
52032     }
52033     return 0;
52034   } else {
52035     return 1;
52036   }
52037 }
52038
52039 /*
52040 ** This routine is callback for sqlite3WalkExpr().
52041 **
52042 ** Resolve symbolic names into TK_COLUMN operators for the current
52043 ** node in the expression tree.  Return 0 to continue the search down
52044 ** the tree or 2 to abort the tree walk.
52045 **
52046 ** This routine also does error checking and name resolution for
52047 ** function names.  The operator for aggregate functions is changed
52048 ** to TK_AGG_FUNCTION.
52049 */
52050 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
52051   NameContext *pNC;
52052   Parse *pParse;
52053
52054   pNC = pWalker->u.pNC;
52055   assert( pNC!=0 );
52056   pParse = pNC->pParse;
52057   assert( pParse==pWalker->pParse );
52058
52059   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
52060   ExprSetProperty(pExpr, EP_Resolved);
52061 #ifndef NDEBUG
52062   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
52063     SrcList *pSrcList = pNC->pSrcList;
52064     int i;
52065     for(i=0; i<pNC->pSrcList->nSrc; i++){
52066       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
52067     }
52068   }
52069 #endif
52070   switch( pExpr->op ){
52071     /* A lone identifier is the name of a column.
52072     */
52073     case TK_ID: {
52074       lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr);
52075       return WRC_Prune;
52076     }
52077   
52078     /* A table name and column name:     ID.ID
52079     ** Or a database, table and column:  ID.ID.ID
52080     */
52081     case TK_DOT: {
52082       Token *pColumn;
52083       Token *pTable;
52084       Token *pDb;
52085       Expr *pRight;
52086
52087       /* if( pSrcList==0 ) break; */
52088       pRight = pExpr->pRight;
52089       if( pRight->op==TK_ID ){
52090         pDb = 0;
52091         pTable = &pExpr->pLeft->token;
52092         pColumn = &pRight->token;
52093       }else{
52094         assert( pRight->op==TK_DOT );
52095         pDb = &pExpr->pLeft->token;
52096         pTable = &pRight->pLeft->token;
52097         pColumn = &pRight->pRight->token;
52098       }
52099       lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr);
52100       return WRC_Prune;
52101     }
52102
52103     /* Resolve function names
52104     */
52105     case TK_CONST_FUNC:
52106     case TK_FUNCTION: {
52107       ExprList *pList = pExpr->pList;    /* The argument list */
52108       int n = pList ? pList->nExpr : 0;  /* Number of arguments */
52109       int no_such_func = 0;       /* True if no such function exists */
52110       int wrong_num_args = 0;     /* True if wrong number of arguments */
52111       int is_agg = 0;             /* True if is an aggregate function */
52112       int auth;                   /* Authorization to use the function */
52113       int nId;                    /* Number of characters in function name */
52114       const char *zId;            /* The function name. */
52115       FuncDef *pDef;              /* Information about the function */
52116       int enc = ENC(pParse->db);  /* The database encoding */
52117
52118       zId = (char*)pExpr->token.z;
52119       nId = pExpr->token.n;
52120       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
52121       if( pDef==0 ){
52122         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
52123         if( pDef==0 ){
52124           no_such_func = 1;
52125         }else{
52126           wrong_num_args = 1;
52127         }
52128       }else{
52129         is_agg = pDef->xFunc==0;
52130       }
52131 #ifndef SQLITE_OMIT_AUTHORIZATION
52132       if( pDef ){
52133         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
52134         if( auth!=SQLITE_OK ){
52135           if( auth==SQLITE_DENY ){
52136             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
52137                                     pDef->zName);
52138             pNC->nErr++;
52139           }
52140           pExpr->op = TK_NULL;
52141           return WRC_Prune;
52142         }
52143       }
52144 #endif
52145       if( is_agg && !pNC->allowAgg ){
52146         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
52147         pNC->nErr++;
52148         is_agg = 0;
52149       }else if( no_such_func ){
52150         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
52151         pNC->nErr++;
52152       }else if( wrong_num_args ){
52153         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
52154              nId, zId);
52155         pNC->nErr++;
52156       }
52157       if( is_agg ){
52158         pExpr->op = TK_AGG_FUNCTION;
52159         pNC->hasAgg = 1;
52160       }
52161       if( is_agg ) pNC->allowAgg = 0;
52162       sqlite3WalkExprList(pWalker, pList);
52163       if( is_agg ) pNC->allowAgg = 1;
52164       /* FIX ME:  Compute pExpr->affinity based on the expected return
52165       ** type of the function 
52166       */
52167       return WRC_Prune;
52168     }
52169 #ifndef SQLITE_OMIT_SUBQUERY
52170     case TK_SELECT:
52171     case TK_EXISTS:
52172 #endif
52173     case TK_IN: {
52174       if( pExpr->pSelect ){
52175         int nRef = pNC->nRef;
52176 #ifndef SQLITE_OMIT_CHECK
52177         if( pNC->isCheck ){
52178           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
52179         }
52180 #endif
52181         sqlite3WalkSelect(pWalker, pExpr->pSelect);
52182         assert( pNC->nRef>=nRef );
52183         if( nRef!=pNC->nRef ){
52184           ExprSetProperty(pExpr, EP_VarSelect);
52185         }
52186       }
52187       break;
52188     }
52189 #ifndef SQLITE_OMIT_CHECK
52190     case TK_VARIABLE: {
52191       if( pNC->isCheck ){
52192         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
52193       }
52194       break;
52195     }
52196 #endif
52197   }
52198   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
52199 }
52200
52201 /*
52202 ** pEList is a list of expressions which are really the result set of the
52203 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
52204 ** This routine checks to see if pE is a simple identifier which corresponds
52205 ** to the AS-name of one of the terms of the expression list.  If it is,
52206 ** this routine return an integer between 1 and N where N is the number of
52207 ** elements in pEList, corresponding to the matching entry.  If there is
52208 ** no match, or if pE is not a simple identifier, then this routine
52209 ** return 0.
52210 **
52211 ** pEList has been resolved.  pE has not.
52212 */
52213 static int resolveAsName(
52214   Parse *pParse,     /* Parsing context for error messages */
52215   ExprList *pEList,  /* List of expressions to scan */
52216   Expr *pE           /* Expression we are trying to match */
52217 ){
52218   int i;             /* Loop counter */
52219
52220   if( pE->op==TK_ID || (pE->op==TK_STRING && pE->token.z[0]!='\'') ){
52221     sqlite3 *db = pParse->db;
52222     char *zCol = sqlite3NameFromToken(db, &pE->token);
52223     if( zCol==0 ){
52224       return -1;
52225     }
52226     for(i=0; i<pEList->nExpr; i++){
52227       char *zAs = pEList->a[i].zName;
52228       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
52229         sqlite3DbFree(db, zCol);
52230         return i+1;
52231       }
52232     }
52233     sqlite3DbFree(db, zCol);
52234   }
52235   return 0;
52236 }
52237
52238 /*
52239 ** pE is a pointer to an expression which is a single term in the
52240 ** ORDER BY of a compound SELECT.  The expression has not been
52241 ** name resolved.
52242 **
52243 ** At the point this routine is called, we already know that the
52244 ** ORDER BY term is not an integer index into the result set.  That
52245 ** case is handled by the calling routine.
52246 **
52247 ** Attempt to match pE against result set columns in the left-most
52248 ** SELECT statement.  Return the index i of the matching column,
52249 ** as an indication to the caller that it should sort by the i-th column.
52250 ** The left-most column is 1.  In other words, the value returned is the
52251 ** same integer value that would be used in the SQL statement to indicate
52252 ** the column.
52253 **
52254 ** If there is no match, return 0.  Return -1 if an error occurs.
52255 */
52256 static int resolveOrderByTermToExprList(
52257   Parse *pParse,     /* Parsing context for error messages */
52258   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
52259   Expr *pE           /* The specific ORDER BY term */
52260 ){
52261   int i;             /* Loop counter */
52262   ExprList *pEList;  /* The columns of the result set */
52263   NameContext nc;    /* Name context for resolving pE */
52264
52265   assert( sqlite3ExprIsInteger(pE, &i)==0 );
52266   pEList = pSelect->pEList;
52267
52268   /* Resolve all names in the ORDER BY term expression
52269   */
52270   memset(&nc, 0, sizeof(nc));
52271   nc.pParse = pParse;
52272   nc.pSrcList = pSelect->pSrc;
52273   nc.pEList = pEList;
52274   nc.allowAgg = 1;
52275   nc.nErr = 0;
52276   if( sqlite3ResolveExprNames(&nc, pE) ){
52277     sqlite3ErrorClear(pParse);
52278     return 0;
52279   }
52280
52281   /* Try to match the ORDER BY expression against an expression
52282   ** in the result set.  Return an 1-based index of the matching
52283   ** result-set entry.
52284   */
52285   for(i=0; i<pEList->nExpr; i++){
52286     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){
52287       return i+1;
52288     }
52289   }
52290
52291   /* If no match, return 0. */
52292   return 0;
52293 }
52294
52295 /*
52296 ** Generate an ORDER BY or GROUP BY term out-of-range error.
52297 */
52298 static void resolveOutOfRangeError(
52299   Parse *pParse,         /* The error context into which to write the error */
52300   const char *zType,     /* "ORDER" or "GROUP" */
52301   int i,                 /* The index (1-based) of the term out of range */
52302   int mx                 /* Largest permissible value of i */
52303 ){
52304   sqlite3ErrorMsg(pParse, 
52305     "%r %s BY term out of range - should be "
52306     "between 1 and %d", i, zType, mx);
52307 }
52308
52309 /*
52310 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
52311 ** each term of the ORDER BY clause is a constant integer between 1
52312 ** and N where N is the number of columns in the compound SELECT.
52313 **
52314 ** ORDER BY terms that are already an integer between 1 and N are
52315 ** unmodified.  ORDER BY terms that are integers outside the range of
52316 ** 1 through N generate an error.  ORDER BY terms that are expressions
52317 ** are matched against result set expressions of compound SELECT
52318 ** beginning with the left-most SELECT and working toward the right.
52319 ** At the first match, the ORDER BY expression is transformed into
52320 ** the integer column number.
52321 **
52322 ** Return the number of errors seen.
52323 */
52324 static int resolveCompoundOrderBy(
52325   Parse *pParse,        /* Parsing context.  Leave error messages here */
52326   Select *pSelect       /* The SELECT statement containing the ORDER BY */
52327 ){
52328   int i;
52329   ExprList *pOrderBy;
52330   ExprList *pEList;
52331   sqlite3 *db;
52332   int moreToDo = 1;
52333
52334   pOrderBy = pSelect->pOrderBy;
52335   if( pOrderBy==0 ) return 0;
52336   db = pParse->db;
52337 #if SQLITE_MAX_COLUMN
52338   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
52339     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
52340     return 1;
52341   }
52342 #endif
52343   for(i=0; i<pOrderBy->nExpr; i++){
52344     pOrderBy->a[i].done = 0;
52345   }
52346   pSelect->pNext = 0;
52347   while( pSelect->pPrior ){
52348     pSelect->pPrior->pNext = pSelect;
52349     pSelect = pSelect->pPrior;
52350   }
52351   while( pSelect && moreToDo ){
52352     struct ExprList_item *pItem;
52353     moreToDo = 0;
52354     pEList = pSelect->pEList;
52355     assert( pEList!=0 );
52356     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
52357       int iCol = -1;
52358       Expr *pE, *pDup;
52359       if( pItem->done ) continue;
52360       pE = pItem->pExpr;
52361       if( sqlite3ExprIsInteger(pE, &iCol) ){
52362         if( iCol<0 || iCol>pEList->nExpr ){
52363           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
52364           return 1;
52365         }
52366       }else{
52367         iCol = resolveAsName(pParse, pEList, pE);
52368         if( iCol==0 ){
52369           pDup = sqlite3ExprDup(db, pE);
52370           if( !db->mallocFailed ){
52371             assert(pDup);
52372             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
52373           }
52374           sqlite3ExprDelete(db, pDup);
52375         }
52376         if( iCol<0 ){
52377           return 1;
52378         }
52379       }
52380       if( iCol>0 ){
52381         CollSeq *pColl = pE->pColl;
52382         int flags = pE->flags & EP_ExpCollate;
52383         sqlite3ExprDelete(db, pE);
52384         pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0, 0, 0);
52385         if( pE==0 ) return 1;
52386         pE->pColl = pColl;
52387         pE->flags |= EP_IntValue | flags;
52388         pE->iTable = iCol;
52389         pItem->iCol = iCol;
52390         pItem->done = 1;
52391       }else{
52392         moreToDo = 1;
52393       }
52394     }
52395     pSelect = pSelect->pNext;
52396   }
52397   for(i=0; i<pOrderBy->nExpr; i++){
52398     if( pOrderBy->a[i].done==0 ){
52399       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
52400             "column in the result set", i+1);
52401       return 1;
52402     }
52403   }
52404   return 0;
52405 }
52406
52407 /*
52408 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
52409 ** the SELECT statement pSelect.  If any term is reference to a
52410 ** result set expression (as determined by the ExprList.a.iCol field)
52411 ** then convert that term into a copy of the corresponding result set
52412 ** column.
52413 **
52414 ** If any errors are detected, add an error message to pParse and
52415 ** return non-zero.  Return zero if no errors are seen.
52416 */
52417 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
52418   Parse *pParse,        /* Parsing context.  Leave error messages here */
52419   Select *pSelect,      /* The SELECT statement containing the clause */
52420   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
52421   const char *zType     /* "ORDER" or "GROUP" */
52422 ){
52423   int i;
52424   sqlite3 *db = pParse->db;
52425   ExprList *pEList;
52426   struct ExprList_item *pItem;
52427
52428   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
52429 #if SQLITE_MAX_COLUMN
52430   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
52431     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
52432     return 1;
52433   }
52434 #endif
52435   pEList = pSelect->pEList;
52436   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
52437   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
52438     if( pItem->iCol ){
52439       if( pItem->iCol>pEList->nExpr ){
52440         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
52441         return 1;
52442       }
52443       resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
52444     }
52445   }
52446   return 0;
52447 }
52448
52449 /*
52450 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
52451 ** The Name context of the SELECT statement is pNC.  zType is either
52452 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
52453 **
52454 ** This routine resolves each term of the clause into an expression.
52455 ** If the order-by term is an integer I between 1 and N (where N is the
52456 ** number of columns in the result set of the SELECT) then the expression
52457 ** in the resolution is a copy of the I-th result-set expression.  If
52458 ** the order-by term is an identify that corresponds to the AS-name of
52459 ** a result-set expression, then the term resolves to a copy of the
52460 ** result-set expression.  Otherwise, the expression is resolved in
52461 ** the usual way - using sqlite3ResolveExprNames().
52462 **
52463 ** This routine returns the number of errors.  If errors occur, then
52464 ** an appropriate error message might be left in pParse.  (OOM errors
52465 ** excepted.)
52466 */
52467 static int resolveOrderGroupBy(
52468   NameContext *pNC,     /* The name context of the SELECT statement */
52469   Select *pSelect,      /* The SELECT statement holding pOrderBy */
52470   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
52471   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
52472 ){
52473   int i;                         /* Loop counter */
52474   int iCol;                      /* Column number */
52475   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
52476   Parse *pParse;                 /* Parsing context */
52477   int nResult;                   /* Number of terms in the result set */
52478
52479   if( pOrderBy==0 ) return 0;
52480   nResult = pSelect->pEList->nExpr;
52481   pParse = pNC->pParse;
52482   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
52483     Expr *pE = pItem->pExpr;
52484     iCol = resolveAsName(pParse, pSelect->pEList, pE);
52485     if( iCol<0 ){
52486       return 1;  /* OOM error */
52487     }
52488     if( iCol>0 ){
52489       /* If an AS-name match is found, mark this ORDER BY column as being
52490       ** a copy of the iCol-th result-set column.  The subsequent call to
52491       ** sqlite3ResolveOrderGroupBy() will convert the expression to a
52492       ** copy of the iCol-th result-set expression. */
52493       pItem->iCol = iCol;
52494       continue;
52495     }
52496     if( sqlite3ExprIsInteger(pE, &iCol) ){
52497       /* The ORDER BY term is an integer constant.  Again, set the column
52498       ** number so that sqlite3ResolveOrderGroupBy() will convert the
52499       ** order-by term to a copy of the result-set expression */
52500       if( iCol<1 ){
52501         resolveOutOfRangeError(pParse, zType, i+1, nResult);
52502         return 1;
52503       }
52504       pItem->iCol = iCol;
52505       continue;
52506     }
52507
52508     /* Otherwise, treat the ORDER BY term as an ordinary expression */
52509     pItem->iCol = 0;
52510     if( sqlite3ResolveExprNames(pNC, pE) ){
52511       return 1;
52512     }
52513   }
52514   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
52515 }
52516
52517 /*
52518 ** Resolve names in the SELECT statement p and all of its descendents.
52519 */
52520 static int resolveSelectStep(Walker *pWalker, Select *p){
52521   NameContext *pOuterNC;  /* Context that contains this SELECT */
52522   NameContext sNC;        /* Name context of this SELECT */
52523   int isCompound;         /* True if p is a compound select */
52524   int nCompound;          /* Number of compound terms processed so far */
52525   Parse *pParse;          /* Parsing context */
52526   ExprList *pEList;       /* Result set expression list */
52527   int i;                  /* Loop counter */
52528   ExprList *pGroupBy;     /* The GROUP BY clause */
52529   Select *pLeftmost;      /* Left-most of SELECT of a compound */
52530   sqlite3 *db;            /* Database connection */
52531   
52532
52533   assert( p!=0 );
52534   if( p->selFlags & SF_Resolved ){
52535     return WRC_Prune;
52536   }
52537   pOuterNC = pWalker->u.pNC;
52538   pParse = pWalker->pParse;
52539   db = pParse->db;
52540
52541   /* Normally sqlite3SelectExpand() will be called first and will have
52542   ** already expanded this SELECT.  However, if this is a subquery within
52543   ** an expression, sqlite3ResolveExprNames() will be called without a
52544   ** prior call to sqlite3SelectExpand().  When that happens, let
52545   ** sqlite3SelectPrep() do all of the processing for this SELECT.
52546   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
52547   ** this routine in the correct order.
52548   */
52549   if( (p->selFlags & SF_Expanded)==0 ){
52550     sqlite3SelectPrep(pParse, p, pOuterNC);
52551     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
52552   }
52553
52554   isCompound = p->pPrior!=0;
52555   nCompound = 0;
52556   pLeftmost = p;
52557   while( p ){
52558     assert( (p->selFlags & SF_Expanded)!=0 );
52559     assert( (p->selFlags & SF_Resolved)==0 );
52560     p->selFlags |= SF_Resolved;
52561
52562     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
52563     ** are not allowed to refer to any names, so pass an empty NameContext.
52564     */
52565     memset(&sNC, 0, sizeof(sNC));
52566     sNC.pParse = pParse;
52567     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
52568         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
52569       return WRC_Abort;
52570     }
52571   
52572     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
52573     ** resolve the result-set expression list.
52574     */
52575     sNC.allowAgg = 1;
52576     sNC.pSrcList = p->pSrc;
52577     sNC.pNext = pOuterNC;
52578   
52579     /* Resolve names in the result set. */
52580     pEList = p->pEList;
52581     assert( pEList!=0 );
52582     for(i=0; i<pEList->nExpr; i++){
52583       Expr *pX = pEList->a[i].pExpr;
52584       if( sqlite3ResolveExprNames(&sNC, pX) ){
52585         return WRC_Abort;
52586       }
52587     }
52588   
52589     /* Recursively resolve names in all subqueries
52590     */
52591     for(i=0; i<p->pSrc->nSrc; i++){
52592       struct SrcList_item *pItem = &p->pSrc->a[i];
52593       if( pItem->pSelect ){
52594         const char *zSavedContext = pParse->zAuthContext;
52595         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
52596         sqlite3ResolveSelectNames(pParse, pItem->pSelect, &sNC);
52597         pParse->zAuthContext = zSavedContext;
52598         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
52599       }
52600     }
52601   
52602     /* If there are no aggregate functions in the result-set, and no GROUP BY 
52603     ** expression, do not allow aggregates in any of the other expressions.
52604     */
52605     assert( (p->selFlags & SF_Aggregate)==0 );
52606     pGroupBy = p->pGroupBy;
52607     if( pGroupBy || sNC.hasAgg ){
52608       p->selFlags |= SF_Aggregate;
52609     }else{
52610       sNC.allowAgg = 0;
52611     }
52612   
52613     /* If a HAVING clause is present, then there must be a GROUP BY clause.
52614     */
52615     if( p->pHaving && !pGroupBy ){
52616       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
52617       return WRC_Abort;
52618     }
52619   
52620     /* Add the expression list to the name-context before parsing the
52621     ** other expressions in the SELECT statement. This is so that
52622     ** expressions in the WHERE clause (etc.) can refer to expressions by
52623     ** aliases in the result set.
52624     **
52625     ** Minor point: If this is the case, then the expression will be
52626     ** re-evaluated for each reference to it.
52627     */
52628     sNC.pEList = p->pEList;
52629     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
52630        sqlite3ResolveExprNames(&sNC, p->pHaving)
52631     ){
52632       return WRC_Abort;
52633     }
52634
52635     /* The ORDER BY and GROUP BY clauses may not refer to terms in
52636     ** outer queries 
52637     */
52638     sNC.pNext = 0;
52639     sNC.allowAgg = 1;
52640
52641     /* Process the ORDER BY clause for singleton SELECT statements.
52642     ** The ORDER BY clause for compounds SELECT statements is handled
52643     ** below, after all of the result-sets for all of the elements of
52644     ** the compound have been resolved.
52645     */
52646     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
52647       return WRC_Abort;
52648     }
52649     if( db->mallocFailed ){
52650       return WRC_Abort;
52651     }
52652   
52653     /* Resolve the GROUP BY clause.  At the same time, make sure 
52654     ** the GROUP BY clause does not contain aggregate functions.
52655     */
52656     if( pGroupBy ){
52657       struct ExprList_item *pItem;
52658     
52659       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
52660         return WRC_Abort;
52661       }
52662       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
52663         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
52664           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
52665               "the GROUP BY clause");
52666           return WRC_Abort;
52667         }
52668       }
52669     }
52670
52671     /* Advance to the next term of the compound
52672     */
52673     p = p->pPrior;
52674     nCompound++;
52675   }
52676
52677   /* Resolve the ORDER BY on a compound SELECT after all terms of
52678   ** the compound have been resolved.
52679   */
52680   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
52681     return WRC_Abort;
52682   }
52683
52684   return WRC_Prune;
52685 }
52686
52687 /*
52688 ** This routine walks an expression tree and resolves references to
52689 ** table columns and result-set columns.  At the same time, do error
52690 ** checking on function usage and set a flag if any aggregate functions
52691 ** are seen.
52692 **
52693 ** To resolve table columns references we look for nodes (or subtrees) of the 
52694 ** form X.Y.Z or Y.Z or just Z where
52695 **
52696 **      X:   The name of a database.  Ex:  "main" or "temp" or
52697 **           the symbolic name assigned to an ATTACH-ed database.
52698 **
52699 **      Y:   The name of a table in a FROM clause.  Or in a trigger
52700 **           one of the special names "old" or "new".
52701 **
52702 **      Z:   The name of a column in table Y.
52703 **
52704 ** The node at the root of the subtree is modified as follows:
52705 **
52706 **    Expr.op        Changed to TK_COLUMN
52707 **    Expr.pTab      Points to the Table object for X.Y
52708 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
52709 **    Expr.iTable    The VDBE cursor number for X.Y
52710 **
52711 **
52712 ** To resolve result-set references, look for expression nodes of the
52713 ** form Z (with no X and Y prefix) where the Z matches the right-hand
52714 ** size of an AS clause in the result-set of a SELECT.  The Z expression
52715 ** is replaced by a copy of the left-hand side of the result-set expression.
52716 ** Table-name and function resolution occurs on the substituted expression
52717 ** tree.  For example, in:
52718 **
52719 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
52720 **
52721 ** The "x" term of the order by is replaced by "a+b" to render:
52722 **
52723 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
52724 **
52725 ** Function calls are checked to make sure that the function is 
52726 ** defined and that the correct number of arguments are specified.
52727 ** If the function is an aggregate function, then the pNC->hasAgg is
52728 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
52729 ** If an expression contains aggregate functions then the EP_Agg
52730 ** property on the expression is set.
52731 **
52732 ** An error message is left in pParse if anything is amiss.  The number
52733 ** if errors is returned.
52734 */
52735 SQLITE_PRIVATE int sqlite3ResolveExprNames( 
52736   NameContext *pNC,       /* Namespace to resolve expressions in. */
52737   Expr *pExpr             /* The expression to be analyzed. */
52738 ){
52739   int savedHasAgg;
52740   Walker w;
52741
52742   if( pExpr==0 ) return 0;
52743 #if SQLITE_MAX_EXPR_DEPTH>0
52744   {
52745     Parse *pParse = pNC->pParse;
52746     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
52747       return 1;
52748     }
52749     pParse->nHeight += pExpr->nHeight;
52750   }
52751 #endif
52752   savedHasAgg = pNC->hasAgg;
52753   pNC->hasAgg = 0;
52754   w.xExprCallback = resolveExprStep;
52755   w.xSelectCallback = resolveSelectStep;
52756   w.pParse = pNC->pParse;
52757   w.u.pNC = pNC;
52758   sqlite3WalkExpr(&w, pExpr);
52759 #if SQLITE_MAX_EXPR_DEPTH>0
52760   pNC->pParse->nHeight -= pExpr->nHeight;
52761 #endif
52762   if( pNC->nErr>0 ){
52763     ExprSetProperty(pExpr, EP_Error);
52764   }
52765   if( pNC->hasAgg ){
52766     ExprSetProperty(pExpr, EP_Agg);
52767   }else if( savedHasAgg ){
52768     pNC->hasAgg = 1;
52769   }
52770   return ExprHasProperty(pExpr, EP_Error);
52771 }
52772
52773
52774 /*
52775 ** Resolve all names in all expressions of a SELECT and in all
52776 ** decendents of the SELECT, including compounds off of p->pPrior,
52777 ** subqueries in expressions, and subqueries used as FROM clause
52778 ** terms.
52779 **
52780 ** See sqlite3ResolveExprNames() for a description of the kinds of
52781 ** transformations that occur.
52782 **
52783 ** All SELECT statements should have been expanded using
52784 ** sqlite3SelectExpand() prior to invoking this routine.
52785 */
52786 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
52787   Parse *pParse,         /* The parser context */
52788   Select *p,             /* The SELECT statement being coded. */
52789   NameContext *pOuterNC  /* Name context for parent SELECT statement */
52790 ){
52791   Walker w;
52792
52793   assert( p!=0 );
52794   w.xExprCallback = resolveExprStep;
52795   w.xSelectCallback = resolveSelectStep;
52796   w.pParse = pParse;
52797   w.u.pNC = pOuterNC;
52798   sqlite3WalkSelect(&w, p);
52799 }
52800
52801 /************** End of resolve.c *********************************************/
52802 /************** Begin file expr.c ********************************************/
52803 /*
52804 ** 2001 September 15
52805 **
52806 ** The author disclaims copyright to this source code.  In place of
52807 ** a legal notice, here is a blessing:
52808 **
52809 **    May you do good and not evil.
52810 **    May you find forgiveness for yourself and forgive others.
52811 **    May you share freely, never taking more than you give.
52812 **
52813 *************************************************************************
52814 ** This file contains routines used for analyzing expressions and
52815 ** for generating VDBE code that evaluates expressions in SQLite.
52816 **
52817 ** $Id: expr.c,v 1.394 2008/09/17 00:13:12 drh Exp $
52818 */
52819
52820 /*
52821 ** Return the 'affinity' of the expression pExpr if any.
52822 **
52823 ** If pExpr is a column, a reference to a column via an 'AS' alias,
52824 ** or a sub-select with a column as the return value, then the 
52825 ** affinity of that column is returned. Otherwise, 0x00 is returned,
52826 ** indicating no affinity for the expression.
52827 **
52828 ** i.e. the WHERE clause expresssions in the following statements all
52829 ** have an affinity:
52830 **
52831 ** CREATE TABLE t1(a);
52832 ** SELECT * FROM t1 WHERE a;
52833 ** SELECT a AS b FROM t1 WHERE b;
52834 ** SELECT * FROM t1 WHERE (select a from t1);
52835 */
52836 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
52837   int op = pExpr->op;
52838   if( op==TK_SELECT ){
52839     return sqlite3ExprAffinity(pExpr->pSelect->pEList->a[0].pExpr);
52840   }
52841 #ifndef SQLITE_OMIT_CAST
52842   if( op==TK_CAST ){
52843     return sqlite3AffinityType(&pExpr->token);
52844   }
52845 #endif
52846   if( (op==TK_COLUMN || op==TK_REGISTER) && pExpr->pTab!=0 ){
52847     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
52848     ** a TK_COLUMN but was previously evaluated and cached in a register */
52849     int j = pExpr->iColumn;
52850     if( j<0 ) return SQLITE_AFF_INTEGER;
52851     assert( pExpr->pTab && j<pExpr->pTab->nCol );
52852     return pExpr->pTab->aCol[j].affinity;
52853   }
52854   return pExpr->affinity;
52855 }
52856
52857 /*
52858 ** Set the collating sequence for expression pExpr to be the collating
52859 ** sequence named by pToken.   Return a pointer to the revised expression.
52860 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
52861 ** flag.  An explicit collating sequence will override implicit
52862 ** collating sequences.
52863 */
52864 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pCollName){
52865   char *zColl = 0;            /* Dequoted name of collation sequence */
52866   CollSeq *pColl;
52867   sqlite3 *db = pParse->db;
52868   zColl = sqlite3NameFromToken(db, pCollName);
52869   if( pExpr && zColl ){
52870     pColl = sqlite3LocateCollSeq(pParse, zColl, -1);
52871     if( pColl ){
52872       pExpr->pColl = pColl;
52873       pExpr->flags |= EP_ExpCollate;
52874     }
52875   }
52876   sqlite3DbFree(db, zColl);
52877   return pExpr;
52878 }
52879
52880 /*
52881 ** Return the default collation sequence for the expression pExpr. If
52882 ** there is no default collation type, return 0.
52883 */
52884 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
52885   CollSeq *pColl = 0;
52886   Expr *p = pExpr;
52887   while( p ){
52888     int op;
52889     pColl = p->pColl;
52890     if( pColl ) break;
52891     op = p->op;
52892     if( (op==TK_COLUMN || op==TK_REGISTER) && p->pTab!=0 ){
52893       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
52894       ** a TK_COLUMN but was previously evaluated and cached in a register */
52895       const char *zColl;
52896       int j = p->iColumn;
52897       if( j>=0 ){
52898         sqlite3 *db = pParse->db;
52899         zColl = p->pTab->aCol[j].zColl;
52900         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, -1, 0);
52901         pExpr->pColl = pColl;
52902       }
52903       break;
52904     }
52905     if( op!=TK_CAST && op!=TK_UPLUS ){
52906       break;
52907     }
52908     p = p->pLeft;
52909   }
52910   if( sqlite3CheckCollSeq(pParse, pColl) ){ 
52911     pColl = 0;
52912   }
52913   return pColl;
52914 }
52915
52916 /*
52917 ** pExpr is an operand of a comparison operator.  aff2 is the
52918 ** type affinity of the other operand.  This routine returns the
52919 ** type affinity that should be used for the comparison operator.
52920 */
52921 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
52922   char aff1 = sqlite3ExprAffinity(pExpr);
52923   if( aff1 && aff2 ){
52924     /* Both sides of the comparison are columns. If one has numeric
52925     ** affinity, use that. Otherwise use no affinity.
52926     */
52927     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
52928       return SQLITE_AFF_NUMERIC;
52929     }else{
52930       return SQLITE_AFF_NONE;
52931     }
52932   }else if( !aff1 && !aff2 ){
52933     /* Neither side of the comparison is a column.  Compare the
52934     ** results directly.
52935     */
52936     return SQLITE_AFF_NONE;
52937   }else{
52938     /* One side is a column, the other is not. Use the columns affinity. */
52939     assert( aff1==0 || aff2==0 );
52940     return (aff1 + aff2);
52941   }
52942 }
52943
52944 /*
52945 ** pExpr is a comparison operator.  Return the type affinity that should
52946 ** be applied to both operands prior to doing the comparison.
52947 */
52948 static char comparisonAffinity(Expr *pExpr){
52949   char aff;
52950   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
52951           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
52952           pExpr->op==TK_NE );
52953   assert( pExpr->pLeft );
52954   aff = sqlite3ExprAffinity(pExpr->pLeft);
52955   if( pExpr->pRight ){
52956     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
52957   }
52958   else if( pExpr->pSelect ){
52959     aff = sqlite3CompareAffinity(pExpr->pSelect->pEList->a[0].pExpr, aff);
52960   }
52961   else if( !aff ){
52962     aff = SQLITE_AFF_NONE;
52963   }
52964   return aff;
52965 }
52966
52967 /*
52968 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
52969 ** idx_affinity is the affinity of an indexed column. Return true
52970 ** if the index with affinity idx_affinity may be used to implement
52971 ** the comparison in pExpr.
52972 */
52973 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
52974   char aff = comparisonAffinity(pExpr);
52975   switch( aff ){
52976     case SQLITE_AFF_NONE:
52977       return 1;
52978     case SQLITE_AFF_TEXT:
52979       return idx_affinity==SQLITE_AFF_TEXT;
52980     default:
52981       return sqlite3IsNumericAffinity(idx_affinity);
52982   }
52983 }
52984
52985 /*
52986 ** Return the P5 value that should be used for a binary comparison
52987 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
52988 */
52989 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
52990   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
52991   aff = sqlite3CompareAffinity(pExpr1, aff) | jumpIfNull;
52992   return aff;
52993 }
52994
52995 /*
52996 ** Return a pointer to the collation sequence that should be used by
52997 ** a binary comparison operator comparing pLeft and pRight.
52998 **
52999 ** If the left hand expression has a collating sequence type, then it is
53000 ** used. Otherwise the collation sequence for the right hand expression
53001 ** is used, or the default (BINARY) if neither expression has a collating
53002 ** type.
53003 **
53004 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
53005 ** it is not considered.
53006 */
53007 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
53008   Parse *pParse, 
53009   Expr *pLeft, 
53010   Expr *pRight
53011 ){
53012   CollSeq *pColl;
53013   assert( pLeft );
53014   if( pLeft->flags & EP_ExpCollate ){
53015     assert( pLeft->pColl );
53016     pColl = pLeft->pColl;
53017   }else if( pRight && pRight->flags & EP_ExpCollate ){
53018     assert( pRight->pColl );
53019     pColl = pRight->pColl;
53020   }else{
53021     pColl = sqlite3ExprCollSeq(pParse, pLeft);
53022     if( !pColl ){
53023       pColl = sqlite3ExprCollSeq(pParse, pRight);
53024     }
53025   }
53026   return pColl;
53027 }
53028
53029 /*
53030 ** Generate the operands for a comparison operation.  Before
53031 ** generating the code for each operand, set the EP_AnyAff
53032 ** flag on the expression so that it will be able to used a
53033 ** cached column value that has previously undergone an
53034 ** affinity change.
53035 */
53036 static void codeCompareOperands(
53037   Parse *pParse,    /* Parsing and code generating context */
53038   Expr *pLeft,      /* The left operand */
53039   int *pRegLeft,    /* Register where left operand is stored */
53040   int *pFreeLeft,   /* Free this register when done */
53041   Expr *pRight,     /* The right operand */
53042   int *pRegRight,   /* Register where right operand is stored */
53043   int *pFreeRight   /* Write temp register for right operand there */
53044 ){
53045   while( pLeft->op==TK_UPLUS ) pLeft = pLeft->pLeft;
53046   pLeft->flags |= EP_AnyAff;
53047   *pRegLeft = sqlite3ExprCodeTemp(pParse, pLeft, pFreeLeft);
53048   while( pRight->op==TK_UPLUS ) pRight = pRight->pLeft;
53049   pRight->flags |= EP_AnyAff;
53050   *pRegRight = sqlite3ExprCodeTemp(pParse, pRight, pFreeRight);
53051 }
53052
53053 /*
53054 ** Generate code for a comparison operator.
53055 */
53056 static int codeCompare(
53057   Parse *pParse,    /* The parsing (and code generating) context */
53058   Expr *pLeft,      /* The left operand */
53059   Expr *pRight,     /* The right operand */
53060   int opcode,       /* The comparison opcode */
53061   int in1, int in2, /* Register holding operands */
53062   int dest,         /* Jump here if true.  */
53063   int jumpIfNull    /* If true, jump if either operand is NULL */
53064 ){
53065   int p5;
53066   int addr;
53067   CollSeq *p4;
53068
53069   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
53070   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
53071   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
53072                            (void*)p4, P4_COLLSEQ);
53073   sqlite3VdbeChangeP5(pParse->pVdbe, p5);
53074   if( (p5 & SQLITE_AFF_MASK)!=SQLITE_AFF_NONE ){
53075     sqlite3ExprCacheAffinityChange(pParse, in1, 1);
53076     sqlite3ExprCacheAffinityChange(pParse, in2, 1);
53077   }
53078   return addr;
53079 }
53080
53081 #if SQLITE_MAX_EXPR_DEPTH>0
53082 /*
53083 ** Check that argument nHeight is less than or equal to the maximum
53084 ** expression depth allowed. If it is not, leave an error message in
53085 ** pParse.
53086 */
53087 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
53088   int rc = SQLITE_OK;
53089   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
53090   if( nHeight>mxHeight ){
53091     sqlite3ErrorMsg(pParse, 
53092        "Expression tree is too large (maximum depth %d)", mxHeight
53093     );
53094     rc = SQLITE_ERROR;
53095   }
53096   return rc;
53097 }
53098
53099 /* The following three functions, heightOfExpr(), heightOfExprList()
53100 ** and heightOfSelect(), are used to determine the maximum height
53101 ** of any expression tree referenced by the structure passed as the
53102 ** first argument.
53103 **
53104 ** If this maximum height is greater than the current value pointed
53105 ** to by pnHeight, the second parameter, then set *pnHeight to that
53106 ** value.
53107 */
53108 static void heightOfExpr(Expr *p, int *pnHeight){
53109   if( p ){
53110     if( p->nHeight>*pnHeight ){
53111       *pnHeight = p->nHeight;
53112     }
53113   }
53114 }
53115 static void heightOfExprList(ExprList *p, int *pnHeight){
53116   if( p ){
53117     int i;
53118     for(i=0; i<p->nExpr; i++){
53119       heightOfExpr(p->a[i].pExpr, pnHeight);
53120     }
53121   }
53122 }
53123 static void heightOfSelect(Select *p, int *pnHeight){
53124   if( p ){
53125     heightOfExpr(p->pWhere, pnHeight);
53126     heightOfExpr(p->pHaving, pnHeight);
53127     heightOfExpr(p->pLimit, pnHeight);
53128     heightOfExpr(p->pOffset, pnHeight);
53129     heightOfExprList(p->pEList, pnHeight);
53130     heightOfExprList(p->pGroupBy, pnHeight);
53131     heightOfExprList(p->pOrderBy, pnHeight);
53132     heightOfSelect(p->pPrior, pnHeight);
53133   }
53134 }
53135
53136 /*
53137 ** Set the Expr.nHeight variable in the structure passed as an 
53138 ** argument. An expression with no children, Expr.pList or 
53139 ** Expr.pSelect member has a height of 1. Any other expression
53140 ** has a height equal to the maximum height of any other 
53141 ** referenced Expr plus one.
53142 */
53143 static void exprSetHeight(Expr *p){
53144   int nHeight = 0;
53145   heightOfExpr(p->pLeft, &nHeight);
53146   heightOfExpr(p->pRight, &nHeight);
53147   heightOfExprList(p->pList, &nHeight);
53148   heightOfSelect(p->pSelect, &nHeight);
53149   p->nHeight = nHeight + 1;
53150 }
53151
53152 /*
53153 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
53154 ** the height is greater than the maximum allowed expression depth,
53155 ** leave an error in pParse.
53156 */
53157 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
53158   exprSetHeight(p);
53159   sqlite3ExprCheckHeight(pParse, p->nHeight);
53160 }
53161
53162 /*
53163 ** Return the maximum height of any expression tree referenced
53164 ** by the select statement passed as an argument.
53165 */
53166 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
53167   int nHeight = 0;
53168   heightOfSelect(p, &nHeight);
53169   return nHeight;
53170 }
53171 #else
53172   #define exprSetHeight(y)
53173 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
53174
53175 /*
53176 ** Construct a new expression node and return a pointer to it.  Memory
53177 ** for this node is obtained from sqlite3_malloc().  The calling function
53178 ** is responsible for making sure the node eventually gets freed.
53179 */
53180 SQLITE_PRIVATE Expr *sqlite3Expr(
53181   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
53182   int op,                 /* Expression opcode */
53183   Expr *pLeft,            /* Left operand */
53184   Expr *pRight,           /* Right operand */
53185   const Token *pToken     /* Argument token */
53186 ){
53187   Expr *pNew;
53188   pNew = sqlite3DbMallocZero(db, sizeof(Expr));
53189   if( pNew==0 ){
53190     /* When malloc fails, delete pLeft and pRight. Expressions passed to 
53191     ** this function must always be allocated with sqlite3Expr() for this 
53192     ** reason. 
53193     */
53194     sqlite3ExprDelete(db, pLeft);
53195     sqlite3ExprDelete(db, pRight);
53196     return 0;
53197   }
53198   pNew->op = op;
53199   pNew->pLeft = pLeft;
53200   pNew->pRight = pRight;
53201   pNew->iAgg = -1;
53202   pNew->span.z = (u8*)"";
53203   if( pToken ){
53204     assert( pToken->dyn==0 );
53205     pNew->span = pNew->token = *pToken;
53206   }else if( pLeft ){
53207     if( pRight ){
53208       if( pRight->span.dyn==0 && pLeft->span.dyn==0 ){
53209         sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
53210       }
53211       if( pRight->flags & EP_ExpCollate ){
53212         pNew->flags |= EP_ExpCollate;
53213         pNew->pColl = pRight->pColl;
53214       }
53215     }
53216     if( pLeft->flags & EP_ExpCollate ){
53217       pNew->flags |= EP_ExpCollate;
53218       pNew->pColl = pLeft->pColl;
53219     }
53220   }
53221
53222   exprSetHeight(pNew);
53223   return pNew;
53224 }
53225
53226 /*
53227 ** Works like sqlite3Expr() except that it takes an extra Parse*
53228 ** argument and notifies the associated connection object if malloc fails.
53229 */
53230 SQLITE_PRIVATE Expr *sqlite3PExpr(
53231   Parse *pParse,          /* Parsing context */
53232   int op,                 /* Expression opcode */
53233   Expr *pLeft,            /* Left operand */
53234   Expr *pRight,           /* Right operand */
53235   const Token *pToken     /* Argument token */
53236 ){
53237   Expr *p = sqlite3Expr(pParse->db, op, pLeft, pRight, pToken);
53238   if( p ){
53239     sqlite3ExprCheckHeight(pParse, p->nHeight);
53240   }
53241   return p;
53242 }
53243
53244 /*
53245 ** When doing a nested parse, you can include terms in an expression
53246 ** that look like this:   #1 #2 ...  These terms refer to registers
53247 ** in the virtual machine.  #N is the N-th register.
53248 **
53249 ** This routine is called by the parser to deal with on of those terms.
53250 ** It immediately generates code to store the value in a memory location.
53251 ** The returns an expression that will code to extract the value from
53252 ** that memory location as needed.
53253 */
53254 SQLITE_PRIVATE Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
53255   Vdbe *v = pParse->pVdbe;
53256   Expr *p;
53257   if( pParse->nested==0 ){
53258     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
53259     return sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
53260   }
53261   if( v==0 ) return 0;
53262   p = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, pToken);
53263   if( p==0 ){
53264     return 0;  /* Malloc failed */
53265   }
53266   p->iTable = atoi((char*)&pToken->z[1]);
53267   return p;
53268 }
53269
53270 /*
53271 ** Join two expressions using an AND operator.  If either expression is
53272 ** NULL, then just return the other expression.
53273 */
53274 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
53275   if( pLeft==0 ){
53276     return pRight;
53277   }else if( pRight==0 ){
53278     return pLeft;
53279   }else{
53280     return sqlite3Expr(db, TK_AND, pLeft, pRight, 0);
53281   }
53282 }
53283
53284 /*
53285 ** Set the Expr.span field of the given expression to span all
53286 ** text between the two given tokens.  Both tokens must be pointing
53287 ** at the same string.
53288 */
53289 SQLITE_PRIVATE void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
53290   assert( pRight!=0 );
53291   assert( pLeft!=0 );
53292   if( pExpr ){
53293     pExpr->span.z = pLeft->z;
53294     pExpr->span.n = pRight->n + (pRight->z - pLeft->z);
53295   }
53296 }
53297
53298 /*
53299 ** Construct a new expression node for a function with multiple
53300 ** arguments.
53301 */
53302 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
53303   Expr *pNew;
53304   sqlite3 *db = pParse->db;
53305   assert( pToken );
53306   pNew = sqlite3DbMallocZero(db, sizeof(Expr) );
53307   if( pNew==0 ){
53308     sqlite3ExprListDelete(db, pList); /* Avoid leaking memory when malloc fails */
53309     return 0;
53310   }
53311   pNew->op = TK_FUNCTION;
53312   pNew->pList = pList;
53313   assert( pToken->dyn==0 );
53314   pNew->token = *pToken;
53315   pNew->span = pNew->token;
53316
53317   sqlite3ExprSetHeight(pParse, pNew);
53318   return pNew;
53319 }
53320
53321 /*
53322 ** Assign a variable number to an expression that encodes a wildcard
53323 ** in the original SQL statement.  
53324 **
53325 ** Wildcards consisting of a single "?" are assigned the next sequential
53326 ** variable number.
53327 **
53328 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
53329 ** sure "nnn" is not too be to avoid a denial of service attack when
53330 ** the SQL statement comes from an external source.
53331 **
53332 ** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
53333 ** as the previous instance of the same wildcard.  Or if this is the first
53334 ** instance of the wildcard, the next sequenial variable number is
53335 ** assigned.
53336 */
53337 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
53338   Token *pToken;
53339   sqlite3 *db = pParse->db;
53340
53341   if( pExpr==0 ) return;
53342   pToken = &pExpr->token;
53343   assert( pToken->n>=1 );
53344   assert( pToken->z!=0 );
53345   assert( pToken->z[0]!=0 );
53346   if( pToken->n==1 ){
53347     /* Wildcard of the form "?".  Assign the next variable number */
53348     pExpr->iTable = ++pParse->nVar;
53349   }else if( pToken->z[0]=='?' ){
53350     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
53351     ** use it as the variable number */
53352     int i;
53353     pExpr->iTable = i = atoi((char*)&pToken->z[1]);
53354     testcase( i==0 );
53355     testcase( i==1 );
53356     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
53357     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
53358     if( i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
53359       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
53360           db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
53361     }
53362     if( i>pParse->nVar ){
53363       pParse->nVar = i;
53364     }
53365   }else{
53366     /* Wildcards of the form ":aaa" or "$aaa".  Reuse the same variable
53367     ** number as the prior appearance of the same name, or if the name
53368     ** has never appeared before, reuse the same variable number
53369     */
53370     int i, n;
53371     n = pToken->n;
53372     for(i=0; i<pParse->nVarExpr; i++){
53373       Expr *pE;
53374       if( (pE = pParse->apVarExpr[i])!=0
53375           && pE->token.n==n
53376           && memcmp(pE->token.z, pToken->z, n)==0 ){
53377         pExpr->iTable = pE->iTable;
53378         break;
53379       }
53380     }
53381     if( i>=pParse->nVarExpr ){
53382       pExpr->iTable = ++pParse->nVar;
53383       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
53384         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
53385         pParse->apVarExpr =
53386             sqlite3DbReallocOrFree(
53387               db,
53388               pParse->apVarExpr,
53389               pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
53390             );
53391       }
53392       if( !db->mallocFailed ){
53393         assert( pParse->apVarExpr!=0 );
53394         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
53395       }
53396     }
53397   } 
53398   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
53399     sqlite3ErrorMsg(pParse, "too many SQL variables");
53400   }
53401 }
53402
53403 /*
53404 ** Recursively delete an expression tree.
53405 */
53406 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
53407   if( p==0 ) return;
53408   if( p->span.dyn ) sqlite3DbFree(db, (char*)p->span.z);
53409   if( p->token.dyn ) sqlite3DbFree(db, (char*)p->token.z);
53410   sqlite3ExprDelete(db, p->pLeft);
53411   sqlite3ExprDelete(db, p->pRight);
53412   sqlite3ExprListDelete(db, p->pList);
53413   sqlite3SelectDelete(db, p->pSelect);
53414   sqlite3DbFree(db, p);
53415 }
53416
53417 /*
53418 ** The Expr.token field might be a string literal that is quoted.
53419 ** If so, remove the quotation marks.
53420 */
53421 SQLITE_PRIVATE void sqlite3DequoteExpr(sqlite3 *db, Expr *p){
53422   if( ExprHasAnyProperty(p, EP_Dequoted) ){
53423     return;
53424   }
53425   ExprSetProperty(p, EP_Dequoted);
53426   if( p->token.dyn==0 ){
53427     sqlite3TokenCopy(db, &p->token, &p->token);
53428   }
53429   sqlite3Dequote((char*)p->token.z);
53430 }
53431
53432 /*
53433 ** The following group of routines make deep copies of expressions,
53434 ** expression lists, ID lists, and select statements.  The copies can
53435 ** be deleted (by being passed to their respective ...Delete() routines)
53436 ** without effecting the originals.
53437 **
53438 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
53439 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
53440 ** by subsequent calls to sqlite*ListAppend() routines.
53441 **
53442 ** Any tables that the SrcList might point to are not duplicated.
53443 */
53444 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p){
53445   Expr *pNew;
53446   if( p==0 ) return 0;
53447   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
53448   if( pNew==0 ) return 0;
53449   memcpy(pNew, p, sizeof(*pNew));
53450   if( p->token.z!=0 ){
53451     pNew->token.z = (u8*)sqlite3DbStrNDup(db, (char*)p->token.z, p->token.n);
53452     pNew->token.dyn = 1;
53453   }else{
53454     assert( pNew->token.z==0 );
53455   }
53456   pNew->span.z = 0;
53457   pNew->pLeft = sqlite3ExprDup(db, p->pLeft);
53458   pNew->pRight = sqlite3ExprDup(db, p->pRight);
53459   pNew->pList = sqlite3ExprListDup(db, p->pList);
53460   pNew->pSelect = sqlite3SelectDup(db, p->pSelect);
53461   return pNew;
53462 }
53463 SQLITE_PRIVATE void sqlite3TokenCopy(sqlite3 *db, Token *pTo, Token *pFrom){
53464   if( pTo->dyn ) sqlite3DbFree(db, (char*)pTo->z);
53465   if( pFrom->z ){
53466     pTo->n = pFrom->n;
53467     pTo->z = (u8*)sqlite3DbStrNDup(db, (char*)pFrom->z, pFrom->n);
53468     pTo->dyn = 1;
53469   }else{
53470     pTo->z = 0;
53471   }
53472 }
53473 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p){
53474   ExprList *pNew;
53475   struct ExprList_item *pItem, *pOldItem;
53476   int i;
53477   if( p==0 ) return 0;
53478   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
53479   if( pNew==0 ) return 0;
53480   pNew->iECursor = 0;
53481   pNew->nExpr = pNew->nAlloc = p->nExpr;
53482   pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
53483   if( pItem==0 ){
53484     sqlite3DbFree(db, pNew);
53485     return 0;
53486   } 
53487   pOldItem = p->a;
53488   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
53489     Expr *pNewExpr, *pOldExpr;
53490     pItem->pExpr = pNewExpr = sqlite3ExprDup(db, pOldExpr = pOldItem->pExpr);
53491     if( pOldExpr->span.z!=0 && pNewExpr ){
53492       /* Always make a copy of the span for top-level expressions in the
53493       ** expression list.  The logic in SELECT processing that determines
53494       ** the names of columns in the result set needs this information */
53495       sqlite3TokenCopy(db, &pNewExpr->span, &pOldExpr->span);
53496     }
53497     assert( pNewExpr==0 || pNewExpr->span.z!=0 
53498             || pOldExpr->span.z==0
53499             || db->mallocFailed );
53500     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
53501     pItem->sortOrder = pOldItem->sortOrder;
53502     pItem->done = 0;
53503     pItem->iCol = pOldItem->iCol;
53504     pItem->iAlias = pOldItem->iAlias;
53505   }
53506   return pNew;
53507 }
53508
53509 /*
53510 ** If cursors, triggers, views and subqueries are all omitted from
53511 ** the build, then none of the following routines, except for 
53512 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
53513 ** called with a NULL argument.
53514 */
53515 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
53516  || !defined(SQLITE_OMIT_SUBQUERY)
53517 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p){
53518   SrcList *pNew;
53519   int i;
53520   int nByte;
53521   if( p==0 ) return 0;
53522   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
53523   pNew = sqlite3DbMallocRaw(db, nByte );
53524   if( pNew==0 ) return 0;
53525   pNew->nSrc = pNew->nAlloc = p->nSrc;
53526   for(i=0; i<p->nSrc; i++){
53527     struct SrcList_item *pNewItem = &pNew->a[i];
53528     struct SrcList_item *pOldItem = &p->a[i];
53529     Table *pTab;
53530     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
53531     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
53532     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
53533     pNewItem->jointype = pOldItem->jointype;
53534     pNewItem->iCursor = pOldItem->iCursor;
53535     pNewItem->isPopulated = pOldItem->isPopulated;
53536     pTab = pNewItem->pTab = pOldItem->pTab;
53537     if( pTab ){
53538       pTab->nRef++;
53539     }
53540     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect);
53541     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn);
53542     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
53543     pNewItem->colUsed = pOldItem->colUsed;
53544   }
53545   return pNew;
53546 }
53547 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
53548   IdList *pNew;
53549   int i;
53550   if( p==0 ) return 0;
53551   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
53552   if( pNew==0 ) return 0;
53553   pNew->nId = pNew->nAlloc = p->nId;
53554   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
53555   if( pNew->a==0 ){
53556     sqlite3DbFree(db, pNew);
53557     return 0;
53558   }
53559   for(i=0; i<p->nId; i++){
53560     struct IdList_item *pNewItem = &pNew->a[i];
53561     struct IdList_item *pOldItem = &p->a[i];
53562     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
53563     pNewItem->idx = pOldItem->idx;
53564   }
53565   return pNew;
53566 }
53567 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p){
53568   Select *pNew;
53569   if( p==0 ) return 0;
53570   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
53571   if( pNew==0 ) return 0;
53572   pNew->pEList = sqlite3ExprListDup(db, p->pEList);
53573   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc);
53574   pNew->pWhere = sqlite3ExprDup(db, p->pWhere);
53575   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy);
53576   pNew->pHaving = sqlite3ExprDup(db, p->pHaving);
53577   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy);
53578   pNew->op = p->op;
53579   pNew->pPrior = sqlite3SelectDup(db, p->pPrior);
53580   pNew->pLimit = sqlite3ExprDup(db, p->pLimit);
53581   pNew->pOffset = sqlite3ExprDup(db, p->pOffset);
53582   pNew->iLimit = 0;
53583   pNew->iOffset = 0;
53584   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
53585   pNew->pRightmost = 0;
53586   pNew->addrOpenEphm[0] = -1;
53587   pNew->addrOpenEphm[1] = -1;
53588   pNew->addrOpenEphm[2] = -1;
53589   return pNew;
53590 }
53591 #else
53592 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p){
53593   assert( p==0 );
53594   return 0;
53595 }
53596 #endif
53597
53598
53599 /*
53600 ** Add a new element to the end of an expression list.  If pList is
53601 ** initially NULL, then create a new expression list.
53602 */
53603 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
53604   Parse *pParse,          /* Parsing context */
53605   ExprList *pList,        /* List to which to append. Might be NULL */
53606   Expr *pExpr,            /* Expression to be appended */
53607   Token *pName            /* AS keyword for the expression */
53608 ){
53609   sqlite3 *db = pParse->db;
53610   if( pList==0 ){
53611     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
53612     if( pList==0 ){
53613       goto no_mem;
53614     }
53615     assert( pList->nAlloc==0 );
53616   }
53617   if( pList->nAlloc<=pList->nExpr ){
53618     struct ExprList_item *a;
53619     int n = pList->nAlloc*2 + 4;
53620     a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
53621     if( a==0 ){
53622       goto no_mem;
53623     }
53624     pList->a = a;
53625     pList->nAlloc = n;
53626   }
53627   assert( pList->a!=0 );
53628   if( pExpr || pName ){
53629     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
53630     memset(pItem, 0, sizeof(*pItem));
53631     pItem->zName = sqlite3NameFromToken(db, pName);
53632     pItem->pExpr = pExpr;
53633     pItem->iAlias = 0;
53634   }
53635   return pList;
53636
53637 no_mem:     
53638   /* Avoid leaking memory if malloc has failed. */
53639   sqlite3ExprDelete(db, pExpr);
53640   sqlite3ExprListDelete(db, pList);
53641   return 0;
53642 }
53643
53644 /*
53645 ** If the expression list pEList contains more than iLimit elements,
53646 ** leave an error message in pParse.
53647 */
53648 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
53649   Parse *pParse,
53650   ExprList *pEList,
53651   const char *zObject
53652 ){
53653   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
53654   testcase( pEList && pEList->nExpr==mx );
53655   testcase( pEList && pEList->nExpr==mx+1 );
53656   if( pEList && pEList->nExpr>mx ){
53657     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
53658   }
53659 }
53660
53661 /*
53662 ** Delete an entire expression list.
53663 */
53664 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
53665   int i;
53666   struct ExprList_item *pItem;
53667   if( pList==0 ) return;
53668   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
53669   assert( pList->nExpr<=pList->nAlloc );
53670   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
53671     sqlite3ExprDelete(db, pItem->pExpr);
53672     sqlite3DbFree(db, pItem->zName);
53673   }
53674   sqlite3DbFree(db, pList->a);
53675   sqlite3DbFree(db, pList);
53676 }
53677
53678 /*
53679 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
53680 ** to an integer.  These routines are checking an expression to see
53681 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
53682 ** not constant.
53683 **
53684 ** These callback routines are used to implement the following:
53685 **
53686 **     sqlite3ExprIsConstant()
53687 **     sqlite3ExprIsConstantNotJoin()
53688 **     sqlite3ExprIsConstantOrFunction()
53689 **
53690 */
53691 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
53692
53693   /* If pWalker->u.i is 3 then any term of the expression that comes from
53694   ** the ON or USING clauses of a join disqualifies the expression
53695   ** from being considered constant. */
53696   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
53697     pWalker->u.i = 0;
53698     return WRC_Abort;
53699   }
53700
53701   switch( pExpr->op ){
53702     /* Consider functions to be constant if all their arguments are constant
53703     ** and pWalker->u.i==2 */
53704     case TK_FUNCTION:
53705       if( pWalker->u.i==2 ) return 0;
53706       /* Fall through */
53707     case TK_ID:
53708     case TK_COLUMN:
53709     case TK_DOT:
53710     case TK_AGG_FUNCTION:
53711     case TK_AGG_COLUMN:
53712 #ifndef SQLITE_OMIT_SUBQUERY
53713     case TK_SELECT:
53714     case TK_EXISTS:
53715       testcase( pExpr->op==TK_SELECT );
53716       testcase( pExpr->op==TK_EXISTS );
53717 #endif
53718       testcase( pExpr->op==TK_ID );
53719       testcase( pExpr->op==TK_COLUMN );
53720       testcase( pExpr->op==TK_DOT );
53721       testcase( pExpr->op==TK_AGG_FUNCTION );
53722       testcase( pExpr->op==TK_AGG_COLUMN );
53723       pWalker->u.i = 0;
53724       return WRC_Abort;
53725     default:
53726       return WRC_Continue;
53727   }
53728 }
53729 static int selectNodeIsConstant(Walker *pWalker, Select *pSelect){
53730   pWalker->u.i = 0;
53731   return WRC_Abort;
53732 }
53733 static int exprIsConst(Expr *p, int initFlag){
53734   Walker w;
53735   w.u.i = initFlag;
53736   w.xExprCallback = exprNodeIsConstant;
53737   w.xSelectCallback = selectNodeIsConstant;
53738   sqlite3WalkExpr(&w, p);
53739   return w.u.i;
53740 }
53741
53742 /*
53743 ** Walk an expression tree.  Return 1 if the expression is constant
53744 ** and 0 if it involves variables or function calls.
53745 **
53746 ** For the purposes of this function, a double-quoted string (ex: "abc")
53747 ** is considered a variable but a single-quoted string (ex: 'abc') is
53748 ** a constant.
53749 */
53750 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
53751   return exprIsConst(p, 1);
53752 }
53753
53754 /*
53755 ** Walk an expression tree.  Return 1 if the expression is constant
53756 ** that does no originate from the ON or USING clauses of a join.
53757 ** Return 0 if it involves variables or function calls or terms from
53758 ** an ON or USING clause.
53759 */
53760 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
53761   return exprIsConst(p, 3);
53762 }
53763
53764 /*
53765 ** Walk an expression tree.  Return 1 if the expression is constant
53766 ** or a function call with constant arguments.  Return and 0 if there
53767 ** are any variables.
53768 **
53769 ** For the purposes of this function, a double-quoted string (ex: "abc")
53770 ** is considered a variable but a single-quoted string (ex: 'abc') is
53771 ** a constant.
53772 */
53773 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
53774   return exprIsConst(p, 2);
53775 }
53776
53777 /*
53778 ** If the expression p codes a constant integer that is small enough
53779 ** to fit in a 32-bit integer, return 1 and put the value of the integer
53780 ** in *pValue.  If the expression is not an integer or if it is too big
53781 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
53782 */
53783 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
53784   int rc = 0;
53785   if( p->flags & EP_IntValue ){
53786     *pValue = p->iTable;
53787     return 1;
53788   }
53789   switch( p->op ){
53790     case TK_INTEGER: {
53791       rc = sqlite3GetInt32((char*)p->token.z, pValue);
53792       break;
53793     }
53794     case TK_UPLUS: {
53795       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
53796       break;
53797     }
53798     case TK_UMINUS: {
53799       int v;
53800       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
53801         *pValue = -v;
53802         rc = 1;
53803       }
53804       break;
53805     }
53806     default: break;
53807   }
53808   if( rc ){
53809     p->op = TK_INTEGER;
53810     p->flags |= EP_IntValue;
53811     p->iTable = *pValue;
53812   }
53813   return rc;
53814 }
53815
53816 /*
53817 ** Return TRUE if the given string is a row-id column name.
53818 */
53819 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
53820   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
53821   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
53822   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
53823   return 0;
53824 }
53825
53826 #ifdef SQLITE_TEST
53827   int sqlite3_enable_in_opt = 1;
53828 #else
53829   #define sqlite3_enable_in_opt 1
53830 #endif
53831
53832 /*
53833 ** Return true if the IN operator optimization is enabled and
53834 ** the SELECT statement p exists and is of the
53835 ** simple form:
53836 **
53837 **     SELECT <column> FROM <table>
53838 **
53839 ** If this is the case, it may be possible to use an existing table
53840 ** or index instead of generating an epheremal table.
53841 */
53842 #ifndef SQLITE_OMIT_SUBQUERY
53843 static int isCandidateForInOpt(Select *p){
53844   SrcList *pSrc;
53845   ExprList *pEList;
53846   Table *pTab;
53847   if( !sqlite3_enable_in_opt ) return 0; /* IN optimization must be enabled */
53848   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
53849   if( p->pPrior ) return 0;              /* Not a compound SELECT */
53850   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
53851       return 0; /* No DISTINCT keyword and no aggregate functions */
53852   }
53853   if( p->pGroupBy ) return 0;            /* Has no GROUP BY clause */
53854   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
53855   if( p->pOffset ) return 0;
53856   if( p->pWhere ) return 0;              /* Has no WHERE clause */
53857   pSrc = p->pSrc;
53858   if( pSrc==0 ) return 0;                /* A single table in the FROM clause */
53859   if( pSrc->nSrc!=1 ) return 0;
53860   if( pSrc->a[0].pSelect ) return 0;     /* FROM clause is not a subquery */
53861   pTab = pSrc->a[0].pTab;
53862   if( pTab==0 ) return 0;
53863   if( pTab->pSelect ) return 0;          /* FROM clause is not a view */
53864   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
53865   pEList = p->pEList;
53866   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
53867   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
53868   return 1;
53869 }
53870 #endif /* SQLITE_OMIT_SUBQUERY */
53871
53872 /*
53873 ** This function is used by the implementation of the IN (...) operator.
53874 ** It's job is to find or create a b-tree structure that may be used
53875 ** either to test for membership of the (...) set or to iterate through
53876 ** its members, skipping duplicates.
53877 **
53878 ** The cursor opened on the structure (database table, database index 
53879 ** or ephermal table) is stored in pX->iTable before this function returns.
53880 ** The returned value indicates the structure type, as follows:
53881 **
53882 **   IN_INDEX_ROWID - The cursor was opened on a database table.
53883 **   IN_INDEX_INDEX - The cursor was opened on a database index.
53884 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
53885 **                    populated epheremal table.
53886 **
53887 ** An existing structure may only be used if the SELECT is of the simple
53888 ** form:
53889 **
53890 **     SELECT <column> FROM <table>
53891 **
53892 ** If prNotFound parameter is 0, then the structure will be used to iterate
53893 ** through the set members, skipping any duplicates. In this case an
53894 ** epheremal table must be used unless the selected <column> is guaranteed
53895 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
53896 ** is unique by virtue of a constraint or implicit index.
53897 **
53898 ** If the prNotFound parameter is not 0, then the structure will be used 
53899 ** for fast set membership tests. In this case an epheremal table must 
53900 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can 
53901 ** be found with <column> as its left-most column.
53902 **
53903 ** When the structure is being used for set membership tests, the user
53904 ** needs to know whether or not the structure contains an SQL NULL 
53905 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
53906 ** If there is a chance that the structure may contain a NULL value at
53907 ** runtime, then a register is allocated and the register number written
53908 ** to *prNotFound. If there is no chance that the structure contains a
53909 ** NULL value, then *prNotFound is left unchanged.
53910 **
53911 ** If a register is allocated and its location stored in *prNotFound, then
53912 ** its initial value is NULL. If the structure does not remain constant
53913 ** for the duration of the query (i.e. the set is a correlated sub-select), 
53914 ** the value of the allocated register is reset to NULL each time the 
53915 ** structure is repopulated. This allows the caller to use vdbe code 
53916 ** equivalent to the following:
53917 **
53918 **   if( register==NULL ){
53919 **     has_null = <test if data structure contains null>
53920 **     register = 1
53921 **   }
53922 **
53923 ** in order to avoid running the <test if data structure contains null>
53924 ** test more often than is necessary.
53925 */
53926 #ifndef SQLITE_OMIT_SUBQUERY
53927 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
53928   Select *p;
53929   int eType = 0;
53930   int iTab = pParse->nTab++;
53931   int mustBeUnique = !prNotFound;
53932
53933   /* The follwing if(...) expression is true if the SELECT is of the 
53934   ** simple form:
53935   **
53936   **     SELECT <column> FROM <table>
53937   **
53938   ** If this is the case, it may be possible to use an existing table
53939   ** or index instead of generating an epheremal table.
53940   */
53941   p = pX->pSelect;
53942   if( isCandidateForInOpt(p) ){
53943     sqlite3 *db = pParse->db;
53944     Index *pIdx;
53945     Expr *pExpr = p->pEList->a[0].pExpr;
53946     int iCol = pExpr->iColumn;
53947     Vdbe *v = sqlite3GetVdbe(pParse);
53948
53949     /* This function is only called from two places. In both cases the vdbe
53950     ** has already been allocated. So assume sqlite3GetVdbe() is always
53951     ** successful here.
53952     */
53953     assert(v);
53954     if( iCol<0 ){
53955       int iMem = ++pParse->nMem;
53956       int iAddr;
53957       Table *pTab = p->pSrc->a[0].pTab;
53958       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
53959       sqlite3VdbeUsesBtree(v, iDb);
53960
53961       iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
53962       sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
53963
53964       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
53965       eType = IN_INDEX_ROWID;
53966
53967       sqlite3VdbeJumpHere(v, iAddr);
53968     }else{
53969       /* The collation sequence used by the comparison. If an index is to 
53970       ** be used in place of a temp-table, it must be ordered according
53971       ** to this collation sequence.
53972       */
53973       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
53974
53975       /* Check that the affinity that will be used to perform the 
53976       ** comparison is the same as the affinity of the column. If
53977       ** it is not, it is not possible to use any index.
53978       */
53979       Table *pTab = p->pSrc->a[0].pTab;
53980       char aff = comparisonAffinity(pX);
53981       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
53982
53983       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
53984         if( (pIdx->aiColumn[0]==iCol)
53985          && (pReq==sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], -1, 0))
53986          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
53987         ){
53988           int iDb;
53989           int iMem = ++pParse->nMem;
53990           int iAddr;
53991           char *pKey;
53992   
53993           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
53994           iDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
53995           sqlite3VdbeUsesBtree(v, iDb);
53996
53997           iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
53998           sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
53999   
54000           sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pIdx->nColumn);
54001           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
54002                                pKey,P4_KEYINFO_HANDOFF);
54003           VdbeComment((v, "%s", pIdx->zName));
54004           eType = IN_INDEX_INDEX;
54005
54006           sqlite3VdbeJumpHere(v, iAddr);
54007           if( prNotFound && !pTab->aCol[iCol].notNull ){
54008             *prNotFound = ++pParse->nMem;
54009           }
54010         }
54011       }
54012     }
54013   }
54014
54015   if( eType==0 ){
54016     int rMayHaveNull = 0;
54017     if( prNotFound ){
54018       *prNotFound = rMayHaveNull = ++pParse->nMem;
54019     }
54020     sqlite3CodeSubselect(pParse, pX, rMayHaveNull);
54021     eType = IN_INDEX_EPH;
54022   }else{
54023     pX->iTable = iTab;
54024   }
54025   return eType;
54026 }
54027 #endif
54028
54029 /*
54030 ** Generate code for scalar subqueries used as an expression
54031 ** and IN operators.  Examples:
54032 **
54033 **     (SELECT a FROM b)          -- subquery
54034 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
54035 **     x IN (4,5,11)              -- IN operator with list on right-hand side
54036 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
54037 **
54038 ** The pExpr parameter describes the expression that contains the IN
54039 ** operator or subquery.
54040 */
54041 #ifndef SQLITE_OMIT_SUBQUERY
54042 SQLITE_PRIVATE void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr, int rMayHaveNull){
54043   int testAddr = 0;                       /* One-time test address */
54044   Vdbe *v = sqlite3GetVdbe(pParse);
54045   if( v==0 ) return;
54046
54047
54048   /* This code must be run in its entirety every time it is encountered
54049   ** if any of the following is true:
54050   **
54051   **    *  The right-hand side is a correlated subquery
54052   **    *  The right-hand side is an expression list containing variables
54053   **    *  We are inside a trigger
54054   **
54055   ** If all of the above are false, then we can run this code just once
54056   ** save the results, and reuse the same result on subsequent invocations.
54057   */
54058   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
54059     int mem = ++pParse->nMem;
54060     sqlite3VdbeAddOp1(v, OP_If, mem);
54061     testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
54062     assert( testAddr>0 || pParse->db->mallocFailed );
54063   }
54064
54065   switch( pExpr->op ){
54066     case TK_IN: {
54067       char affinity;
54068       KeyInfo keyInfo;
54069       int addr;        /* Address of OP_OpenEphemeral instruction */
54070
54071       if( rMayHaveNull ){
54072         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
54073       }
54074
54075       affinity = sqlite3ExprAffinity(pExpr->pLeft);
54076
54077       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
54078       ** expression it is handled the same way. A virtual table is 
54079       ** filled with single-field index keys representing the results
54080       ** from the SELECT or the <exprlist>.
54081       **
54082       ** If the 'x' expression is a column value, or the SELECT...
54083       ** statement returns a column value, then the affinity of that
54084       ** column is used to build the index keys. If both 'x' and the
54085       ** SELECT... statement are columns, then numeric affinity is used
54086       ** if either column has NUMERIC or INTEGER affinity. If neither
54087       ** 'x' nor the SELECT... statement are columns, then numeric affinity
54088       ** is used.
54089       */
54090       pExpr->iTable = pParse->nTab++;
54091       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, 1);
54092       memset(&keyInfo, 0, sizeof(keyInfo));
54093       keyInfo.nField = 1;
54094
54095       if( pExpr->pSelect ){
54096         /* Case 1:     expr IN (SELECT ...)
54097         **
54098         ** Generate code to write the results of the select into the temporary
54099         ** table allocated and opened above.
54100         */
54101         SelectDest dest;
54102         ExprList *pEList;
54103
54104         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
54105         dest.affinity = (int)affinity;
54106         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
54107         if( sqlite3Select(pParse, pExpr->pSelect, &dest) ){
54108           return;
54109         }
54110         pEList = pExpr->pSelect->pEList;
54111         if( pEList && pEList->nExpr>0 ){ 
54112           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
54113               pEList->a[0].pExpr);
54114         }
54115       }else if( pExpr->pList ){
54116         /* Case 2:     expr IN (exprlist)
54117         **
54118         ** For each expression, build an index key from the evaluation and
54119         ** store it in the temporary table. If <expr> is a column, then use
54120         ** that columns affinity when building index keys. If <expr> is not
54121         ** a column, use numeric affinity.
54122         */
54123         int i;
54124         ExprList *pList = pExpr->pList;
54125         struct ExprList_item *pItem;
54126         int r1, r2, r3;
54127
54128         if( !affinity ){
54129           affinity = SQLITE_AFF_NONE;
54130         }
54131         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
54132
54133         /* Loop through each expression in <exprlist>. */
54134         r1 = sqlite3GetTempReg(pParse);
54135         r2 = sqlite3GetTempReg(pParse);
54136         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
54137           Expr *pE2 = pItem->pExpr;
54138
54139           /* If the expression is not constant then we will need to
54140           ** disable the test that was generated above that makes sure
54141           ** this code only executes once.  Because for a non-constant
54142           ** expression we need to rerun this code each time.
54143           */
54144           if( testAddr && !sqlite3ExprIsConstant(pE2) ){
54145             sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
54146             testAddr = 0;
54147           }
54148
54149           /* Evaluate the expression and insert it into the temp table */
54150           pParse->disableColCache++;
54151           r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
54152           assert( pParse->disableColCache>0 );
54153           pParse->disableColCache--;
54154           sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
54155           sqlite3ExprCacheAffinityChange(pParse, r3, 1);
54156           sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
54157         }
54158         sqlite3ReleaseTempReg(pParse, r1);
54159         sqlite3ReleaseTempReg(pParse, r2);
54160       }
54161       sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
54162       break;
54163     }
54164
54165     case TK_EXISTS:
54166     case TK_SELECT: {
54167       /* This has to be a scalar SELECT.  Generate code to put the
54168       ** value of this select in a memory cell and record the number
54169       ** of the memory cell in iColumn.
54170       */
54171       static const Token one = { (u8*)"1", 0, 1 };
54172       Select *pSel;
54173       SelectDest dest;
54174
54175       pSel = pExpr->pSelect;
54176       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
54177       if( pExpr->op==TK_SELECT ){
54178         dest.eDest = SRT_Mem;
54179         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
54180         VdbeComment((v, "Init subquery result"));
54181       }else{
54182         dest.eDest = SRT_Exists;
54183         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
54184         VdbeComment((v, "Init EXISTS result"));
54185       }
54186       sqlite3ExprDelete(pParse->db, pSel->pLimit);
54187       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one);
54188       if( sqlite3Select(pParse, pSel, &dest) ){
54189         return;
54190       }
54191       pExpr->iColumn = dest.iParm;
54192       break;
54193     }
54194   }
54195
54196   if( testAddr ){
54197     sqlite3VdbeJumpHere(v, testAddr-1);
54198   }
54199
54200   return;
54201 }
54202 #endif /* SQLITE_OMIT_SUBQUERY */
54203
54204 /*
54205 ** Duplicate an 8-byte value
54206 */
54207 static char *dup8bytes(Vdbe *v, const char *in){
54208   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
54209   if( out ){
54210     memcpy(out, in, 8);
54211   }
54212   return out;
54213 }
54214
54215 /*
54216 ** Generate an instruction that will put the floating point
54217 ** value described by z[0..n-1] into register iMem.
54218 **
54219 ** The z[] string will probably not be zero-terminated.  But the 
54220 ** z[n] character is guaranteed to be something that does not look
54221 ** like the continuation of the number.
54222 */
54223 static void codeReal(Vdbe *v, const char *z, int n, int negateFlag, int iMem){
54224   assert( z || v==0 || sqlite3VdbeDb(v)->mallocFailed );
54225   if( z ){
54226     double value;
54227     char *zV;
54228     assert( !isdigit(z[n]) );
54229     sqlite3AtoF(z, &value);
54230     if( sqlite3IsNaN(value) ){
54231       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem);
54232     }else{
54233       if( negateFlag ) value = -value;
54234       zV = dup8bytes(v, (char*)&value);
54235       sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
54236     }
54237   }
54238 }
54239
54240
54241 /*
54242 ** Generate an instruction that will put the integer describe by
54243 ** text z[0..n-1] into register iMem.
54244 **
54245 ** The z[] string will probably not be zero-terminated.  But the 
54246 ** z[n] character is guaranteed to be something that does not look
54247 ** like the continuation of the number.
54248 */
54249 static void codeInteger(Vdbe *v, Expr *pExpr, int negFlag, int iMem){
54250   const char *z;
54251   if( pExpr->flags & EP_IntValue ){
54252     int i = pExpr->iTable;
54253     if( negFlag ) i = -i;
54254     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
54255   }else if( (z = (char*)pExpr->token.z)!=0 ){
54256     int i;
54257     int n = pExpr->token.n;
54258     assert( !isdigit(z[n]) );
54259     if( sqlite3GetInt32(z, &i) ){
54260       if( negFlag ) i = -i;
54261       sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
54262     }else if( sqlite3FitsIn64Bits(z, negFlag) ){
54263       i64 value;
54264       char *zV;
54265       sqlite3Atoi64(z, &value);
54266       if( negFlag ) value = -value;
54267       zV = dup8bytes(v, (char*)&value);
54268       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
54269     }else{
54270       codeReal(v, z, n, negFlag, iMem);
54271     }
54272   }
54273 }
54274
54275
54276 /*
54277 ** Generate code that will extract the iColumn-th column from
54278 ** table pTab and store the column value in a register.  An effort
54279 ** is made to store the column value in register iReg, but this is
54280 ** not guaranteed.  The location of the column value is returned.
54281 **
54282 ** There must be an open cursor to pTab in iTable when this routine
54283 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
54284 **
54285 ** This routine might attempt to reuse the value of the column that
54286 ** has already been loaded into a register.  The value will always
54287 ** be used if it has not undergone any affinity changes.  But if
54288 ** an affinity change has occurred, then the cached value will only be
54289 ** used if allowAffChng is true.
54290 */
54291 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
54292   Parse *pParse,   /* Parsing and code generating context */
54293   Table *pTab,     /* Description of the table we are reading from */
54294   int iColumn,     /* Index of the table column */
54295   int iTable,      /* The cursor pointing to the table */
54296   int iReg,        /* Store results here */
54297   int allowAffChng /* True if prior affinity changes are OK */
54298 ){
54299   Vdbe *v = pParse->pVdbe;
54300   int i;
54301   struct yColCache *p;
54302
54303   for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
54304     if( p->iTable==iTable && p->iColumn==iColumn
54305            && (!p->affChange || allowAffChng) ){
54306 #if 0
54307       sqlite3VdbeAddOp0(v, OP_Noop);
54308       VdbeComment((v, "OPT: tab%d.col%d -> r%d", iTable, iColumn, p->iReg));
54309 #endif
54310       return p->iReg;
54311     }
54312   }  
54313   assert( v!=0 );
54314   if( iColumn<0 ){
54315     int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid;
54316     sqlite3VdbeAddOp2(v, op, iTable, iReg);
54317   }else if( pTab==0 ){
54318     sqlite3VdbeAddOp3(v, OP_Column, iTable, iColumn, iReg);
54319   }else{
54320     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
54321     sqlite3VdbeAddOp3(v, op, iTable, iColumn, iReg);
54322     sqlite3ColumnDefault(v, pTab, iColumn);
54323 #ifndef SQLITE_OMIT_FLOATING_POINT
54324     if( pTab->aCol[iColumn].affinity==SQLITE_AFF_REAL ){
54325       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
54326     }
54327 #endif
54328   }
54329   if( pParse->disableColCache==0 ){
54330     i = pParse->iColCache;
54331     p = &pParse->aColCache[i];
54332     p->iTable = iTable;
54333     p->iColumn = iColumn;
54334     p->iReg = iReg;
54335     p->affChange = 0;
54336     i++;
54337     if( i>=ArraySize(pParse->aColCache) ) i = 0;
54338     if( i>pParse->nColCache ) pParse->nColCache = i;
54339     pParse->iColCache = i;
54340   }
54341   return iReg;
54342 }
54343
54344 /*
54345 ** Clear all column cache entries associated with the vdbe
54346 ** cursor with cursor number iTable.
54347 */
54348 SQLITE_PRIVATE void sqlite3ExprClearColumnCache(Parse *pParse, int iTable){
54349   if( iTable<0 ){
54350     pParse->nColCache = 0;
54351     pParse->iColCache = 0;
54352   }else{
54353     int i;
54354     for(i=0; i<pParse->nColCache; i++){
54355       if( pParse->aColCache[i].iTable==iTable ){
54356         testcase( i==pParse->nColCache-1 );
54357         pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache];
54358         pParse->iColCache = pParse->nColCache;
54359       }
54360     }
54361   }
54362 }
54363
54364 /*
54365 ** Record the fact that an affinity change has occurred on iCount
54366 ** registers starting with iStart.
54367 */
54368 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
54369   int iEnd = iStart + iCount - 1;
54370   int i;
54371   for(i=0; i<pParse->nColCache; i++){
54372     int r = pParse->aColCache[i].iReg;
54373     if( r>=iStart && r<=iEnd ){
54374       pParse->aColCache[i].affChange = 1;
54375     }
54376   }
54377 }
54378
54379 /*
54380 ** Generate code to move content from registers iFrom...iFrom+nReg-1
54381 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
54382 */
54383 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
54384   int i;
54385   if( iFrom==iTo ) return;
54386   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
54387   for(i=0; i<pParse->nColCache; i++){
54388     int x = pParse->aColCache[i].iReg;
54389     if( x>=iFrom && x<iFrom+nReg ){
54390       pParse->aColCache[i].iReg += iTo-iFrom;
54391     }
54392   }
54393 }
54394
54395 /*
54396 ** Generate code to copy content from registers iFrom...iFrom+nReg-1
54397 ** over to iTo..iTo+nReg-1.
54398 */
54399 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
54400   int i;
54401   if( iFrom==iTo ) return;
54402   for(i=0; i<nReg; i++){
54403     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
54404   }
54405 }
54406
54407 /*
54408 ** Return true if any register in the range iFrom..iTo (inclusive)
54409 ** is used as part of the column cache.
54410 */
54411 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
54412   int i;
54413   for(i=0; i<pParse->nColCache; i++){
54414     int r = pParse->aColCache[i].iReg;
54415     if( r>=iFrom && r<=iTo ) return 1;
54416   }
54417   return 0;
54418 }
54419
54420 /*
54421 ** Theres is a value in register iCurrent.  We ultimately want
54422 ** the value to be in register iTarget.  It might be that
54423 ** iCurrent and iTarget are the same register.
54424 **
54425 ** We are going to modify the value, so we need to make sure it
54426 ** is not a cached register.  If iCurrent is a cached register,
54427 ** then try to move the value over to iTarget.  If iTarget is a
54428 ** cached register, then clear the corresponding cache line.
54429 **
54430 ** Return the register that the value ends up in.
54431 */
54432 SQLITE_PRIVATE int sqlite3ExprWritableRegister(Parse *pParse, int iCurrent, int iTarget){
54433   int i;
54434   assert( pParse->pVdbe!=0 );
54435   if( !usedAsColumnCache(pParse, iCurrent, iCurrent) ){
54436     return iCurrent;
54437   }
54438   if( iCurrent!=iTarget ){
54439     sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, iCurrent, iTarget);
54440   }
54441   for(i=0; i<pParse->nColCache; i++){
54442     if( pParse->aColCache[i].iReg==iTarget ){
54443       pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache];
54444       pParse->iColCache = pParse->nColCache;
54445     }
54446   }
54447   return iTarget;
54448 }
54449
54450 /*
54451 ** If the last instruction coded is an ephemeral copy of any of
54452 ** the registers in the nReg registers beginning with iReg, then
54453 ** convert the last instruction from OP_SCopy to OP_Copy.
54454 */
54455 SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){
54456   int addr;
54457   VdbeOp *pOp;
54458   Vdbe *v;
54459
54460   v = pParse->pVdbe;
54461   addr = sqlite3VdbeCurrentAddr(v);
54462   pOp = sqlite3VdbeGetOp(v, addr-1);
54463   assert( pOp || pParse->db->mallocFailed );
54464   if( pOp && pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1<iReg+nReg ){
54465     pOp->opcode = OP_Copy;
54466   }
54467 }
54468
54469 /*
54470 ** Generate code to store the value of the iAlias-th alias in register
54471 ** target.  The first time this is called, pExpr is evaluated to compute
54472 ** the value of the alias.  The value is stored in an auxiliary register
54473 ** and the number of that register is returned.  On subsequent calls,
54474 ** the register number is returned without generating any code.
54475 **
54476 ** Note that in order for this to work, code must be generated in the
54477 ** same order that it is executed.
54478 **
54479 ** Aliases are numbered starting with 1.  So iAlias is in the range
54480 ** of 1 to pParse->nAlias inclusive.  
54481 **
54482 ** pParse->aAlias[iAlias-1] records the register number where the value
54483 ** of the iAlias-th alias is stored.  If zero, that means that the
54484 ** alias has not yet been computed.
54485 */
54486 static int codeAlias(Parse *pParse, int iAlias, Expr *pExpr){
54487   sqlite3 *db = pParse->db;
54488   int iReg;
54489   if( pParse->aAlias==0 ){
54490     pParse->aAlias = sqlite3DbMallocZero(db, 
54491                                  sizeof(pParse->aAlias[0])*pParse->nAlias );
54492     if( db->mallocFailed ) return 0;
54493   }
54494   assert( iAlias>0 && iAlias<=pParse->nAlias );
54495   iReg = pParse->aAlias[iAlias-1];
54496   if( iReg==0 ){
54497     iReg = ++pParse->nMem;
54498     sqlite3ExprCode(pParse, pExpr, iReg);
54499     pParse->aAlias[iAlias-1] = iReg;
54500   }
54501   return iReg;
54502 }
54503
54504 /*
54505 ** Generate code into the current Vdbe to evaluate the given
54506 ** expression.  Attempt to store the results in register "target".
54507 ** Return the register where results are stored.
54508 **
54509 ** With this routine, there is no guarantee that results will
54510 ** be stored in target.  The result might be stored in some other
54511 ** register if it is convenient to do so.  The calling function
54512 ** must check the return code and move the results to the desired
54513 ** register.
54514 */
54515 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
54516   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
54517   int op;                   /* The opcode being coded */
54518   int inReg = target;       /* Results stored in register inReg */
54519   int regFree1 = 0;         /* If non-zero free this temporary register */
54520   int regFree2 = 0;         /* If non-zero free this temporary register */
54521   int r1, r2, r3, r4;       /* Various register numbers */
54522   sqlite3 *db;
54523
54524   db = pParse->db;
54525   assert( v!=0 || db->mallocFailed );
54526   assert( target>0 && target<=pParse->nMem );
54527   if( v==0 ) return 0;
54528
54529   if( pExpr==0 ){
54530     op = TK_NULL;
54531   }else{
54532     op = pExpr->op;
54533   }
54534   switch( op ){
54535     case TK_AGG_COLUMN: {
54536       AggInfo *pAggInfo = pExpr->pAggInfo;
54537       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
54538       if( !pAggInfo->directMode ){
54539         assert( pCol->iMem>0 );
54540         inReg = pCol->iMem;
54541         break;
54542       }else if( pAggInfo->useSortingIdx ){
54543         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
54544                               pCol->iSorterColumn, target);
54545         break;
54546       }
54547       /* Otherwise, fall thru into the TK_COLUMN case */
54548     }
54549     case TK_COLUMN: {
54550       if( pExpr->iTable<0 ){
54551         /* This only happens when coding check constraints */
54552         assert( pParse->ckBase>0 );
54553         inReg = pExpr->iColumn + pParse->ckBase;
54554       }else{
54555         testcase( (pExpr->flags & EP_AnyAff)!=0 );
54556         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
54557                                  pExpr->iColumn, pExpr->iTable, target,
54558                                  pExpr->flags & EP_AnyAff);
54559       }
54560       break;
54561     }
54562     case TK_INTEGER: {
54563       codeInteger(v, pExpr, 0, target);
54564       break;
54565     }
54566     case TK_FLOAT: {
54567       codeReal(v, (char*)pExpr->token.z, pExpr->token.n, 0, target);
54568       break;
54569     }
54570     case TK_STRING: {
54571       sqlite3DequoteExpr(db, pExpr);
54572       sqlite3VdbeAddOp4(v,OP_String8, 0, target, 0,
54573                         (char*)pExpr->token.z, pExpr->token.n);
54574       break;
54575     }
54576     case TK_NULL: {
54577       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
54578       break;
54579     }
54580 #ifndef SQLITE_OMIT_BLOB_LITERAL
54581     case TK_BLOB: {
54582       int n;
54583       const char *z;
54584       char *zBlob;
54585       assert( pExpr->token.n>=3 );
54586       assert( pExpr->token.z[0]=='x' || pExpr->token.z[0]=='X' );
54587       assert( pExpr->token.z[1]=='\'' );
54588       assert( pExpr->token.z[pExpr->token.n-1]=='\'' );
54589       n = pExpr->token.n - 3;
54590       z = (char*)pExpr->token.z + 2;
54591       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
54592       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
54593       break;
54594     }
54595 #endif
54596     case TK_VARIABLE: {
54597       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iTable, target);
54598       if( pExpr->token.n>1 ){
54599         sqlite3VdbeChangeP4(v, -1, (char*)pExpr->token.z, pExpr->token.n);
54600       }
54601       break;
54602     }
54603     case TK_REGISTER: {
54604       inReg = pExpr->iTable;
54605       break;
54606     }
54607     case TK_AS: {
54608       inReg = codeAlias(pParse, pExpr->iTable, pExpr->pLeft);
54609       break;
54610     }
54611 #ifndef SQLITE_OMIT_CAST
54612     case TK_CAST: {
54613       /* Expressions of the form:   CAST(pLeft AS token) */
54614       int aff, to_op;
54615       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
54616       aff = sqlite3AffinityType(&pExpr->token);
54617       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
54618       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
54619       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
54620       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
54621       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
54622       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
54623       testcase( to_op==OP_ToText );
54624       testcase( to_op==OP_ToBlob );
54625       testcase( to_op==OP_ToNumeric );
54626       testcase( to_op==OP_ToInt );
54627       testcase( to_op==OP_ToReal );
54628       sqlite3VdbeAddOp1(v, to_op, inReg);
54629       testcase( usedAsColumnCache(pParse, inReg, inReg) );
54630       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
54631       break;
54632     }
54633 #endif /* SQLITE_OMIT_CAST */
54634     case TK_LT:
54635     case TK_LE:
54636     case TK_GT:
54637     case TK_GE:
54638     case TK_NE:
54639     case TK_EQ: {
54640       assert( TK_LT==OP_Lt );
54641       assert( TK_LE==OP_Le );
54642       assert( TK_GT==OP_Gt );
54643       assert( TK_GE==OP_Ge );
54644       assert( TK_EQ==OP_Eq );
54645       assert( TK_NE==OP_Ne );
54646       testcase( op==TK_LT );
54647       testcase( op==TK_LE );
54648       testcase( op==TK_GT );
54649       testcase( op==TK_GE );
54650       testcase( op==TK_EQ );
54651       testcase( op==TK_NE );
54652       codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
54653                                   pExpr->pRight, &r2, &regFree2);
54654       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
54655                   r1, r2, inReg, SQLITE_STOREP2);
54656       testcase( regFree1==0 );
54657       testcase( regFree2==0 );
54658       break;
54659     }
54660     case TK_AND:
54661     case TK_OR:
54662     case TK_PLUS:
54663     case TK_STAR:
54664     case TK_MINUS:
54665     case TK_REM:
54666     case TK_BITAND:
54667     case TK_BITOR:
54668     case TK_SLASH:
54669     case TK_LSHIFT:
54670     case TK_RSHIFT: 
54671     case TK_CONCAT: {
54672       assert( TK_AND==OP_And );
54673       assert( TK_OR==OP_Or );
54674       assert( TK_PLUS==OP_Add );
54675       assert( TK_MINUS==OP_Subtract );
54676       assert( TK_REM==OP_Remainder );
54677       assert( TK_BITAND==OP_BitAnd );
54678       assert( TK_BITOR==OP_BitOr );
54679       assert( TK_SLASH==OP_Divide );
54680       assert( TK_LSHIFT==OP_ShiftLeft );
54681       assert( TK_RSHIFT==OP_ShiftRight );
54682       assert( TK_CONCAT==OP_Concat );
54683       testcase( op==TK_AND );
54684       testcase( op==TK_OR );
54685       testcase( op==TK_PLUS );
54686       testcase( op==TK_MINUS );
54687       testcase( op==TK_REM );
54688       testcase( op==TK_BITAND );
54689       testcase( op==TK_BITOR );
54690       testcase( op==TK_SLASH );
54691       testcase( op==TK_LSHIFT );
54692       testcase( op==TK_RSHIFT );
54693       testcase( op==TK_CONCAT );
54694       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
54695       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
54696       sqlite3VdbeAddOp3(v, op, r2, r1, target);
54697       testcase( regFree1==0 );
54698       testcase( regFree2==0 );
54699       break;
54700     }
54701     case TK_UMINUS: {
54702       Expr *pLeft = pExpr->pLeft;
54703       assert( pLeft );
54704       if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){
54705         if( pLeft->op==TK_FLOAT ){
54706           codeReal(v, (char*)pLeft->token.z, pLeft->token.n, 1, target);
54707         }else{
54708           codeInteger(v, pLeft, 1, target);
54709         }
54710       }else{
54711         regFree1 = r1 = sqlite3GetTempReg(pParse);
54712         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
54713         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
54714         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
54715         testcase( regFree2==0 );
54716       }
54717       inReg = target;
54718       break;
54719     }
54720     case TK_BITNOT:
54721     case TK_NOT: {
54722       assert( TK_BITNOT==OP_BitNot );
54723       assert( TK_NOT==OP_Not );
54724       testcase( op==TK_BITNOT );
54725       testcase( op==TK_NOT );
54726       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
54727       testcase( inReg==target );
54728       testcase( usedAsColumnCache(pParse, inReg, inReg) );
54729       inReg = sqlite3ExprWritableRegister(pParse, inReg, target);
54730       sqlite3VdbeAddOp1(v, op, inReg);
54731       break;
54732     }
54733     case TK_ISNULL:
54734     case TK_NOTNULL: {
54735       int addr;
54736       assert( TK_ISNULL==OP_IsNull );
54737       assert( TK_NOTNULL==OP_NotNull );
54738       testcase( op==TK_ISNULL );
54739       testcase( op==TK_NOTNULL );
54740       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
54741       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
54742       testcase( regFree1==0 );
54743       addr = sqlite3VdbeAddOp1(v, op, r1);
54744       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
54745       sqlite3VdbeJumpHere(v, addr);
54746       break;
54747     }
54748     case TK_AGG_FUNCTION: {
54749       AggInfo *pInfo = pExpr->pAggInfo;
54750       if( pInfo==0 ){
54751         sqlite3ErrorMsg(pParse, "misuse of aggregate: %T",
54752             &pExpr->span);
54753       }else{
54754         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
54755       }
54756       break;
54757     }
54758     case TK_CONST_FUNC:
54759     case TK_FUNCTION: {
54760       ExprList *pList = pExpr->pList;
54761       int nExpr = pList ? pList->nExpr : 0;
54762       FuncDef *pDef;
54763       int nId;
54764       const char *zId;
54765       int constMask = 0;
54766       int i;
54767       u8 enc = ENC(db);
54768       CollSeq *pColl = 0;
54769
54770       testcase( op==TK_CONST_FUNC );
54771       testcase( op==TK_FUNCTION );
54772       zId = (char*)pExpr->token.z;
54773       nId = pExpr->token.n;
54774       pDef = sqlite3FindFunction(db, zId, nId, nExpr, enc, 0);
54775       assert( pDef!=0 );
54776       if( pList ){
54777         nExpr = pList->nExpr;
54778         r1 = sqlite3GetTempRange(pParse, nExpr);
54779         sqlite3ExprCodeExprList(pParse, pList, r1, 1);
54780       }else{
54781         nExpr = r1 = 0;
54782       }
54783 #ifndef SQLITE_OMIT_VIRTUALTABLE
54784       /* Possibly overload the function if the first argument is
54785       ** a virtual table column.
54786       **
54787       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
54788       ** second argument, not the first, as the argument to test to
54789       ** see if it is a column in a virtual table.  This is done because
54790       ** the left operand of infix functions (the operand we want to
54791       ** control overloading) ends up as the second argument to the
54792       ** function.  The expression "A glob B" is equivalent to 
54793       ** "glob(B,A).  We want to use the A in "A glob B" to test
54794       ** for function overloading.  But we use the B term in "glob(B,A)".
54795       */
54796       if( nExpr>=2 && (pExpr->flags & EP_InfixFunc) ){
54797         pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[1].pExpr);
54798       }else if( nExpr>0 ){
54799         pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[0].pExpr);
54800       }
54801 #endif
54802       for(i=0; i<nExpr && i<32; i++){
54803         if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
54804           constMask |= (1<<i);
54805         }
54806         if( pDef->needCollSeq && !pColl ){
54807           pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
54808         }
54809       }
54810       if( pDef->needCollSeq ){
54811         if( !pColl ) pColl = db->pDfltColl; 
54812         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
54813       }
54814       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
54815                         (char*)pDef, P4_FUNCDEF);
54816       sqlite3VdbeChangeP5(v, nExpr);
54817       if( nExpr ){
54818         sqlite3ReleaseTempRange(pParse, r1, nExpr);
54819       }
54820       sqlite3ExprCacheAffinityChange(pParse, r1, nExpr);
54821       break;
54822     }
54823 #ifndef SQLITE_OMIT_SUBQUERY
54824     case TK_EXISTS:
54825     case TK_SELECT: {
54826       testcase( op==TK_EXISTS );
54827       testcase( op==TK_SELECT );
54828       if( pExpr->iColumn==0 ){
54829         sqlite3CodeSubselect(pParse, pExpr, 0);
54830       }
54831       inReg = pExpr->iColumn;
54832       break;
54833     }
54834     case TK_IN: {
54835       int rNotFound = 0;
54836       int rMayHaveNull = 0;
54837       int j2, j3, j4, j5;
54838       char affinity;
54839       int eType;
54840
54841       VdbeNoopComment((v, "begin IN expr r%d", target));
54842       eType = sqlite3FindInIndex(pParse, pExpr, &rMayHaveNull);
54843       if( rMayHaveNull ){
54844         rNotFound = ++pParse->nMem;
54845       }
54846
54847       /* Figure out the affinity to use to create a key from the results
54848       ** of the expression. affinityStr stores a static string suitable for
54849       ** P4 of OP_MakeRecord.
54850       */
54851       affinity = comparisonAffinity(pExpr);
54852
54853
54854       /* Code the <expr> from "<expr> IN (...)". The temporary table
54855       ** pExpr->iTable contains the values that make up the (...) set.
54856       */
54857       pParse->disableColCache++;
54858       sqlite3ExprCode(pParse, pExpr->pLeft, target);
54859       pParse->disableColCache--;
54860       j2 = sqlite3VdbeAddOp1(v, OP_IsNull, target);
54861       if( eType==IN_INDEX_ROWID ){
54862         j3 = sqlite3VdbeAddOp1(v, OP_MustBeInt, target);
54863         j4 = sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, 0, target);
54864         sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
54865         j5 = sqlite3VdbeAddOp0(v, OP_Goto);
54866         sqlite3VdbeJumpHere(v, j3);
54867         sqlite3VdbeJumpHere(v, j4);
54868         sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
54869       }else{
54870         r2 = regFree2 = sqlite3GetTempReg(pParse);
54871
54872         /* Create a record and test for set membership. If the set contains
54873         ** the value, then jump to the end of the test code. The target
54874         ** register still contains the true (1) value written to it earlier.
54875         */
54876         sqlite3VdbeAddOp4(v, OP_MakeRecord, target, 1, r2, &affinity, 1);
54877         sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
54878         j5 = sqlite3VdbeAddOp3(v, OP_Found, pExpr->iTable, 0, r2);
54879
54880         /* If the set membership test fails, then the result of the 
54881         ** "x IN (...)" expression must be either 0 or NULL. If the set
54882         ** contains no NULL values, then the result is 0. If the set 
54883         ** contains one or more NULL values, then the result of the
54884         ** expression is also NULL.
54885         */
54886         if( rNotFound==0 ){
54887           /* This branch runs if it is known at compile time (now) that 
54888           ** the set contains no NULL values. This happens as the result
54889           ** of a "NOT NULL" constraint in the database schema. No need
54890           ** to test the data structure at runtime in this case.
54891           */
54892           sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
54893         }else{
54894           /* This block populates the rNotFound register with either NULL
54895           ** or 0 (an integer value). If the data structure contains one
54896           ** or more NULLs, then set rNotFound to NULL. Otherwise, set it
54897           ** to 0. If register rMayHaveNull is already set to some value
54898           ** other than NULL, then the test has already been run and 
54899           ** rNotFound is already populated.
54900           */
54901           static const char nullRecord[] = { 0x02, 0x00 };
54902           j3 = sqlite3VdbeAddOp1(v, OP_NotNull, rMayHaveNull);
54903           sqlite3VdbeAddOp2(v, OP_Null, 0, rNotFound);
54904           sqlite3VdbeAddOp4(v, OP_Blob, 2, rMayHaveNull, 0, 
54905                              nullRecord, P4_STATIC);
54906           j4 = sqlite3VdbeAddOp3(v, OP_Found, pExpr->iTable, 0, rMayHaveNull);
54907           sqlite3VdbeAddOp2(v, OP_Integer, 0, rNotFound);
54908           sqlite3VdbeJumpHere(v, j4);
54909           sqlite3VdbeJumpHere(v, j3);
54910
54911           /* Copy the value of register rNotFound (which is either NULL or 0)
54912           ** into the target register. This will be the result of the
54913           ** expression.
54914           */
54915           sqlite3VdbeAddOp2(v, OP_Copy, rNotFound, target);
54916         }
54917       }
54918       sqlite3VdbeJumpHere(v, j2);
54919       sqlite3VdbeJumpHere(v, j5);
54920       VdbeComment((v, "end IN expr r%d", target));
54921       break;
54922     }
54923 #endif
54924     /*
54925     **    x BETWEEN y AND z
54926     **
54927     ** This is equivalent to
54928     **
54929     **    x>=y AND x<=z
54930     **
54931     ** X is stored in pExpr->pLeft.
54932     ** Y is stored in pExpr->pList->a[0].pExpr.
54933     ** Z is stored in pExpr->pList->a[1].pExpr.
54934     */
54935     case TK_BETWEEN: {
54936       Expr *pLeft = pExpr->pLeft;
54937       struct ExprList_item *pLItem = pExpr->pList->a;
54938       Expr *pRight = pLItem->pExpr;
54939
54940       codeCompareOperands(pParse, pLeft, &r1, &regFree1,
54941                                   pRight, &r2, &regFree2);
54942       testcase( regFree1==0 );
54943       testcase( regFree2==0 );
54944       r3 = sqlite3GetTempReg(pParse);
54945       r4 = sqlite3GetTempReg(pParse);
54946       codeCompare(pParse, pLeft, pRight, OP_Ge,
54947                   r1, r2, r3, SQLITE_STOREP2);
54948       pLItem++;
54949       pRight = pLItem->pExpr;
54950       sqlite3ReleaseTempReg(pParse, regFree2);
54951       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
54952       testcase( regFree2==0 );
54953       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
54954       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
54955       sqlite3ReleaseTempReg(pParse, r3);
54956       sqlite3ReleaseTempReg(pParse, r4);
54957       break;
54958     }
54959     case TK_UPLUS: {
54960       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
54961       break;
54962     }
54963
54964     /*
54965     ** Form A:
54966     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
54967     **
54968     ** Form B:
54969     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
54970     **
54971     ** Form A is can be transformed into the equivalent form B as follows:
54972     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
54973     **        WHEN x=eN THEN rN ELSE y END
54974     **
54975     ** X (if it exists) is in pExpr->pLeft.
54976     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
54977     ** ELSE clause and no other term matches, then the result of the
54978     ** exprssion is NULL.
54979     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
54980     **
54981     ** The result of the expression is the Ri for the first matching Ei,
54982     ** or if there is no matching Ei, the ELSE term Y, or if there is
54983     ** no ELSE term, NULL.
54984     */
54985     case TK_CASE: {
54986       int endLabel;                     /* GOTO label for end of CASE stmt */
54987       int nextCase;                     /* GOTO label for next WHEN clause */
54988       int nExpr;                        /* 2x number of WHEN terms */
54989       int i;                            /* Loop counter */
54990       ExprList *pEList;                 /* List of WHEN terms */
54991       struct ExprList_item *aListelem;  /* Array of WHEN terms */
54992       Expr opCompare;                   /* The X==Ei expression */
54993       Expr cacheX;                      /* Cached expression X */
54994       Expr *pX;                         /* The X expression */
54995       Expr *pTest;                      /* X==Ei (form A) or just Ei (form B) */
54996
54997       assert(pExpr->pList);
54998       assert((pExpr->pList->nExpr % 2) == 0);
54999       assert(pExpr->pList->nExpr > 0);
55000       pEList = pExpr->pList;
55001       aListelem = pEList->a;
55002       nExpr = pEList->nExpr;
55003       endLabel = sqlite3VdbeMakeLabel(v);
55004       if( (pX = pExpr->pLeft)!=0 ){
55005         cacheX = *pX;
55006         testcase( pX->op==TK_COLUMN || pX->op==TK_REGISTER );
55007         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
55008         testcase( regFree1==0 );
55009         cacheX.op = TK_REGISTER;
55010         opCompare.op = TK_EQ;
55011         opCompare.pLeft = &cacheX;
55012         pTest = &opCompare;
55013       }
55014       pParse->disableColCache++;
55015       for(i=0; i<nExpr; i=i+2){
55016         if( pX ){
55017           opCompare.pRight = aListelem[i].pExpr;
55018         }else{
55019           pTest = aListelem[i].pExpr;
55020         }
55021         nextCase = sqlite3VdbeMakeLabel(v);
55022         testcase( pTest->op==TK_COLUMN || pTest->op==TK_REGISTER );
55023         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
55024         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
55025         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
55026         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
55027         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
55028         sqlite3VdbeResolveLabel(v, nextCase);
55029       }
55030       if( pExpr->pRight ){
55031         sqlite3ExprCode(pParse, pExpr->pRight, target);
55032       }else{
55033         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
55034       }
55035       sqlite3VdbeResolveLabel(v, endLabel);
55036       assert( pParse->disableColCache>0 );
55037       pParse->disableColCache--;
55038       break;
55039     }
55040 #ifndef SQLITE_OMIT_TRIGGER
55041     case TK_RAISE: {
55042       if( !pParse->trigStack ){
55043         sqlite3ErrorMsg(pParse,
55044                        "RAISE() may only be used within a trigger-program");
55045         return 0;
55046       }
55047       if( pExpr->iColumn!=OE_Ignore ){
55048          assert( pExpr->iColumn==OE_Rollback ||
55049                  pExpr->iColumn == OE_Abort ||
55050                  pExpr->iColumn == OE_Fail );
55051          sqlite3DequoteExpr(db, pExpr);
55052          sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn, 0,
55053                         (char*)pExpr->token.z, pExpr->token.n);
55054       } else {
55055          assert( pExpr->iColumn == OE_Ignore );
55056          sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0);
55057          sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
55058          VdbeComment((v, "raise(IGNORE)"));
55059       }
55060       break;
55061     }
55062 #endif
55063   }
55064   sqlite3ReleaseTempReg(pParse, regFree1);
55065   sqlite3ReleaseTempReg(pParse, regFree2);
55066   return inReg;
55067 }
55068
55069 /*
55070 ** Generate code to evaluate an expression and store the results
55071 ** into a register.  Return the register number where the results
55072 ** are stored.
55073 **
55074 ** If the register is a temporary register that can be deallocated,
55075 ** then write its number into *pReg.  If the result register is not
55076 ** a temporary, then set *pReg to zero.
55077 */
55078 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
55079   int r1 = sqlite3GetTempReg(pParse);
55080   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
55081   if( r2==r1 ){
55082     *pReg = r1;
55083   }else{
55084     sqlite3ReleaseTempReg(pParse, r1);
55085     *pReg = 0;
55086   }
55087   return r2;
55088 }
55089
55090 /*
55091 ** Generate code that will evaluate expression pExpr and store the
55092 ** results in register target.  The results are guaranteed to appear
55093 ** in register target.
55094 */
55095 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
55096   int inReg;
55097
55098   assert( target>0 && target<=pParse->nMem );
55099   inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
55100   assert( pParse->pVdbe || pParse->db->mallocFailed );
55101   if( inReg!=target && pParse->pVdbe ){
55102     sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
55103   }
55104   return target;
55105 }
55106
55107 /*
55108 ** Generate code that evalutes the given expression and puts the result
55109 ** in register target.
55110 **
55111 ** Also make a copy of the expression results into another "cache" register
55112 ** and modify the expression so that the next time it is evaluated,
55113 ** the result is a copy of the cache register.
55114 **
55115 ** This routine is used for expressions that are used multiple 
55116 ** times.  They are evaluated once and the results of the expression
55117 ** are reused.
55118 */
55119 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
55120   Vdbe *v = pParse->pVdbe;
55121   int inReg;
55122   inReg = sqlite3ExprCode(pParse, pExpr, target);
55123   assert( target>0 );
55124   if( pExpr->op!=TK_REGISTER ){  
55125     int iMem;
55126     iMem = ++pParse->nMem;
55127     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
55128     pExpr->iTable = iMem;
55129     pExpr->op = TK_REGISTER;
55130   }
55131   return inReg;
55132 }
55133
55134 /*
55135 ** Return TRUE if pExpr is an constant expression that is appropriate
55136 ** for factoring out of a loop.  Appropriate expressions are:
55137 **
55138 **    *  Any expression that evaluates to two or more opcodes.
55139 **
55140 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, 
55141 **       or OP_Variable that does not need to be placed in a 
55142 **       specific register.
55143 **
55144 ** There is no point in factoring out single-instruction constant
55145 ** expressions that need to be placed in a particular register.  
55146 ** We could factor them out, but then we would end up adding an
55147 ** OP_SCopy instruction to move the value into the correct register
55148 ** later.  We might as well just use the original instruction and
55149 ** avoid the OP_SCopy.
55150 */
55151 static int isAppropriateForFactoring(Expr *p){
55152   if( !sqlite3ExprIsConstantNotJoin(p) ){
55153     return 0;  /* Only constant expressions are appropriate for factoring */
55154   }
55155   if( (p->flags & EP_FixedDest)==0 ){
55156     return 1;  /* Any constant without a fixed destination is appropriate */
55157   }
55158   while( p->op==TK_UPLUS ) p = p->pLeft;
55159   switch( p->op ){
55160 #ifndef SQLITE_OMIT_BLOB_LITERAL
55161     case TK_BLOB:
55162 #endif
55163     case TK_VARIABLE:
55164     case TK_INTEGER:
55165     case TK_FLOAT:
55166     case TK_NULL:
55167     case TK_STRING: {
55168       testcase( p->op==TK_BLOB );
55169       testcase( p->op==TK_VARIABLE );
55170       testcase( p->op==TK_INTEGER );
55171       testcase( p->op==TK_FLOAT );
55172       testcase( p->op==TK_NULL );
55173       testcase( p->op==TK_STRING );
55174       /* Single-instruction constants with a fixed destination are
55175       ** better done in-line.  If we factor them, they will just end
55176       ** up generating an OP_SCopy to move the value to the destination
55177       ** register. */
55178       return 0;
55179     }
55180     case TK_UMINUS: {
55181        if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
55182          return 0;
55183        }
55184        break;
55185     }
55186     default: {
55187       break;
55188     }
55189   }
55190   return 1;
55191 }
55192
55193 /*
55194 ** If pExpr is a constant expression that is appropriate for
55195 ** factoring out of a loop, then evaluate the expression
55196 ** into a register and convert the expression into a TK_REGISTER
55197 ** expression.
55198 */
55199 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
55200   Parse *pParse = pWalker->pParse;
55201   switch( pExpr->op ){
55202     case TK_REGISTER: {
55203       return 1;
55204     }
55205     case TK_FUNCTION:
55206     case TK_AGG_FUNCTION:
55207     case TK_CONST_FUNC: {
55208       /* The arguments to a function have a fixed destination.
55209       ** Mark them this way to avoid generated unneeded OP_SCopy
55210       ** instructions. 
55211       */
55212       ExprList *pList = pExpr->pList;
55213       if( pList ){
55214         int i = pList->nExpr;
55215         struct ExprList_item *pItem = pList->a;
55216         for(; i>0; i--, pItem++){
55217           if( pItem->pExpr ) pItem->pExpr->flags |= EP_FixedDest;
55218         }
55219       }
55220       break;
55221     }
55222   }
55223   if( isAppropriateForFactoring(pExpr) ){
55224     int r1 = ++pParse->nMem;
55225     int r2;
55226     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
55227     if( r1!=r2 ) sqlite3ReleaseTempReg(pParse, r1);
55228     pExpr->op = TK_REGISTER;
55229     pExpr->iTable = r2;
55230     return WRC_Prune;
55231   }
55232   return WRC_Continue;
55233 }
55234
55235 /*
55236 ** Preevaluate constant subexpressions within pExpr and store the
55237 ** results in registers.  Modify pExpr so that the constant subexpresions
55238 ** are TK_REGISTER opcodes that refer to the precomputed values.
55239 */
55240 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
55241   Walker w;
55242   w.xExprCallback = evalConstExpr;
55243   w.xSelectCallback = 0;
55244   w.pParse = pParse;
55245   sqlite3WalkExpr(&w, pExpr);
55246 }
55247
55248
55249 /*
55250 ** Generate code that pushes the value of every element of the given
55251 ** expression list into a sequence of registers beginning at target.
55252 **
55253 ** Return the number of elements evaluated.
55254 */
55255 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
55256   Parse *pParse,     /* Parsing context */
55257   ExprList *pList,   /* The expression list to be coded */
55258   int target,        /* Where to write results */
55259   int doHardCopy     /* Make a hard copy of every element */
55260 ){
55261   struct ExprList_item *pItem;
55262   int i, n;
55263   assert( pList!=0 );
55264   assert( target>0 );
55265   n = pList->nExpr;
55266   for(pItem=pList->a, i=0; i<n; i++, pItem++){
55267     if( pItem->iAlias ){
55268       int iReg = codeAlias(pParse, pItem->iAlias, pItem->pExpr);
55269       Vdbe *v = sqlite3GetVdbe(pParse);
55270       sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target+i);
55271     }else{
55272       sqlite3ExprCode(pParse, pItem->pExpr, target+i);
55273     }
55274     if( doHardCopy ){
55275       sqlite3ExprHardCopy(pParse, target, n);
55276     }
55277   }
55278   return n;
55279 }
55280
55281 /*
55282 ** Generate code for a boolean expression such that a jump is made
55283 ** to the label "dest" if the expression is true but execution
55284 ** continues straight thru if the expression is false.
55285 **
55286 ** If the expression evaluates to NULL (neither true nor false), then
55287 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
55288 **
55289 ** This code depends on the fact that certain token values (ex: TK_EQ)
55290 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
55291 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
55292 ** the make process cause these values to align.  Assert()s in the code
55293 ** below verify that the numbers are aligned correctly.
55294 */
55295 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
55296   Vdbe *v = pParse->pVdbe;
55297   int op = 0;
55298   int regFree1 = 0;
55299   int regFree2 = 0;
55300   int r1, r2;
55301
55302   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
55303   if( v==0 || pExpr==0 ) return;
55304   op = pExpr->op;
55305   switch( op ){
55306     case TK_AND: {
55307       int d2 = sqlite3VdbeMakeLabel(v);
55308       testcase( jumpIfNull==0 );
55309       testcase( pParse->disableColCache==0 );
55310       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
55311       pParse->disableColCache++;
55312       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
55313       assert( pParse->disableColCache>0 );
55314       pParse->disableColCache--;
55315       sqlite3VdbeResolveLabel(v, d2);
55316       break;
55317     }
55318     case TK_OR: {
55319       testcase( jumpIfNull==0 );
55320       testcase( pParse->disableColCache==0 );
55321       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
55322       pParse->disableColCache++;
55323       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
55324       assert( pParse->disableColCache>0 );
55325       pParse->disableColCache--;
55326       break;
55327     }
55328     case TK_NOT: {
55329       testcase( jumpIfNull==0 );
55330       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
55331       break;
55332     }
55333     case TK_LT:
55334     case TK_LE:
55335     case TK_GT:
55336     case TK_GE:
55337     case TK_NE:
55338     case TK_EQ: {
55339       assert( TK_LT==OP_Lt );
55340       assert( TK_LE==OP_Le );
55341       assert( TK_GT==OP_Gt );
55342       assert( TK_GE==OP_Ge );
55343       assert( TK_EQ==OP_Eq );
55344       assert( TK_NE==OP_Ne );
55345       testcase( op==TK_LT );
55346       testcase( op==TK_LE );
55347       testcase( op==TK_GT );
55348       testcase( op==TK_GE );
55349       testcase( op==TK_EQ );
55350       testcase( op==TK_NE );
55351       testcase( jumpIfNull==0 );
55352       codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
55353                                   pExpr->pRight, &r2, &regFree2);
55354       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
55355                   r1, r2, dest, jumpIfNull);
55356       testcase( regFree1==0 );
55357       testcase( regFree2==0 );
55358       break;
55359     }
55360     case TK_ISNULL:
55361     case TK_NOTNULL: {
55362       assert( TK_ISNULL==OP_IsNull );
55363       assert( TK_NOTNULL==OP_NotNull );
55364       testcase( op==TK_ISNULL );
55365       testcase( op==TK_NOTNULL );
55366       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
55367       sqlite3VdbeAddOp2(v, op, r1, dest);
55368       testcase( regFree1==0 );
55369       break;
55370     }
55371     case TK_BETWEEN: {
55372       /*    x BETWEEN y AND z
55373       **
55374       ** Is equivalent to 
55375       **
55376       **    x>=y AND x<=z
55377       **
55378       ** Code it as such, taking care to do the common subexpression
55379       ** elementation of x.
55380       */
55381       Expr exprAnd;
55382       Expr compLeft;
55383       Expr compRight;
55384       Expr exprX;
55385
55386       exprX = *pExpr->pLeft;
55387       exprAnd.op = TK_AND;
55388       exprAnd.pLeft = &compLeft;
55389       exprAnd.pRight = &compRight;
55390       compLeft.op = TK_GE;
55391       compLeft.pLeft = &exprX;
55392       compLeft.pRight = pExpr->pList->a[0].pExpr;
55393       compRight.op = TK_LE;
55394       compRight.pLeft = &exprX;
55395       compRight.pRight = pExpr->pList->a[1].pExpr;
55396       exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
55397       testcase( regFree1==0 );
55398       exprX.op = TK_REGISTER;
55399       testcase( jumpIfNull==0 );
55400       sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
55401       break;
55402     }
55403     default: {
55404       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
55405       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
55406       testcase( regFree1==0 );
55407       testcase( jumpIfNull==0 );
55408       break;
55409     }
55410   }
55411   sqlite3ReleaseTempReg(pParse, regFree1);
55412   sqlite3ReleaseTempReg(pParse, regFree2);  
55413 }
55414
55415 /*
55416 ** Generate code for a boolean expression such that a jump is made
55417 ** to the label "dest" if the expression is false but execution
55418 ** continues straight thru if the expression is true.
55419 **
55420 ** If the expression evaluates to NULL (neither true nor false) then
55421 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
55422 ** is 0.
55423 */
55424 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
55425   Vdbe *v = pParse->pVdbe;
55426   int op = 0;
55427   int regFree1 = 0;
55428   int regFree2 = 0;
55429   int r1, r2;
55430
55431   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
55432   if( v==0 || pExpr==0 ) return;
55433
55434   /* The value of pExpr->op and op are related as follows:
55435   **
55436   **       pExpr->op            op
55437   **       ---------          ----------
55438   **       TK_ISNULL          OP_NotNull
55439   **       TK_NOTNULL         OP_IsNull
55440   **       TK_NE              OP_Eq
55441   **       TK_EQ              OP_Ne
55442   **       TK_GT              OP_Le
55443   **       TK_LE              OP_Gt
55444   **       TK_GE              OP_Lt
55445   **       TK_LT              OP_Ge
55446   **
55447   ** For other values of pExpr->op, op is undefined and unused.
55448   ** The value of TK_ and OP_ constants are arranged such that we
55449   ** can compute the mapping above using the following expression.
55450   ** Assert()s verify that the computation is correct.
55451   */
55452   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
55453
55454   /* Verify correct alignment of TK_ and OP_ constants
55455   */
55456   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
55457   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
55458   assert( pExpr->op!=TK_NE || op==OP_Eq );
55459   assert( pExpr->op!=TK_EQ || op==OP_Ne );
55460   assert( pExpr->op!=TK_LT || op==OP_Ge );
55461   assert( pExpr->op!=TK_LE || op==OP_Gt );
55462   assert( pExpr->op!=TK_GT || op==OP_Le );
55463   assert( pExpr->op!=TK_GE || op==OP_Lt );
55464
55465   switch( pExpr->op ){
55466     case TK_AND: {
55467       testcase( jumpIfNull==0 );
55468       testcase( pParse->disableColCache==0 );
55469       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
55470       pParse->disableColCache++;
55471       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
55472       assert( pParse->disableColCache>0 );
55473       pParse->disableColCache--;
55474       break;
55475     }
55476     case TK_OR: {
55477       int d2 = sqlite3VdbeMakeLabel(v);
55478       testcase( jumpIfNull==0 );
55479       testcase( pParse->disableColCache==0 );
55480       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
55481       pParse->disableColCache++;
55482       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
55483       assert( pParse->disableColCache>0 );
55484       pParse->disableColCache--;
55485       sqlite3VdbeResolveLabel(v, d2);
55486       break;
55487     }
55488     case TK_NOT: {
55489       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
55490       break;
55491     }
55492     case TK_LT:
55493     case TK_LE:
55494     case TK_GT:
55495     case TK_GE:
55496     case TK_NE:
55497     case TK_EQ: {
55498       testcase( op==TK_LT );
55499       testcase( op==TK_LE );
55500       testcase( op==TK_GT );
55501       testcase( op==TK_GE );
55502       testcase( op==TK_EQ );
55503       testcase( op==TK_NE );
55504       testcase( jumpIfNull==0 );
55505       codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
55506                                   pExpr->pRight, &r2, &regFree2);
55507       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
55508                   r1, r2, dest, jumpIfNull);
55509       testcase( regFree1==0 );
55510       testcase( regFree2==0 );
55511       break;
55512     }
55513     case TK_ISNULL:
55514     case TK_NOTNULL: {
55515       testcase( op==TK_ISNULL );
55516       testcase( op==TK_NOTNULL );
55517       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
55518       sqlite3VdbeAddOp2(v, op, r1, dest);
55519       testcase( regFree1==0 );
55520       break;
55521     }
55522     case TK_BETWEEN: {
55523       /*    x BETWEEN y AND z
55524       **
55525       ** Is equivalent to 
55526       **
55527       **    x>=y AND x<=z
55528       **
55529       ** Code it as such, taking care to do the common subexpression
55530       ** elementation of x.
55531       */
55532       Expr exprAnd;
55533       Expr compLeft;
55534       Expr compRight;
55535       Expr exprX;
55536
55537       exprX = *pExpr->pLeft;
55538       exprAnd.op = TK_AND;
55539       exprAnd.pLeft = &compLeft;
55540       exprAnd.pRight = &compRight;
55541       compLeft.op = TK_GE;
55542       compLeft.pLeft = &exprX;
55543       compLeft.pRight = pExpr->pList->a[0].pExpr;
55544       compRight.op = TK_LE;
55545       compRight.pLeft = &exprX;
55546       compRight.pRight = pExpr->pList->a[1].pExpr;
55547       exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
55548       testcase( regFree1==0 );
55549       exprX.op = TK_REGISTER;
55550       testcase( jumpIfNull==0 );
55551       sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
55552       break;
55553     }
55554     default: {
55555       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
55556       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
55557       testcase( regFree1==0 );
55558       testcase( jumpIfNull==0 );
55559       break;
55560     }
55561   }
55562   sqlite3ReleaseTempReg(pParse, regFree1);
55563   sqlite3ReleaseTempReg(pParse, regFree2);
55564 }
55565
55566 /*
55567 ** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
55568 ** if they are identical and return FALSE if they differ in any way.
55569 **
55570 ** Sometimes this routine will return FALSE even if the two expressions
55571 ** really are equivalent.  If we cannot prove that the expressions are
55572 ** identical, we return FALSE just to be safe.  So if this routine
55573 ** returns false, then you do not really know for certain if the two
55574 ** expressions are the same.  But if you get a TRUE return, then you
55575 ** can be sure the expressions are the same.  In the places where
55576 ** this routine is used, it does not hurt to get an extra FALSE - that
55577 ** just might result in some slightly slower code.  But returning
55578 ** an incorrect TRUE could lead to a malfunction.
55579 */
55580 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
55581   int i;
55582   if( pA==0||pB==0 ){
55583     return pB==pA;
55584   }
55585   if( pA->op!=pB->op ) return 0;
55586   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
55587   if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
55588   if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
55589   if( pA->pList ){
55590     if( pB->pList==0 ) return 0;
55591     if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
55592     for(i=0; i<pA->pList->nExpr; i++){
55593       if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
55594         return 0;
55595       }
55596     }
55597   }else if( pB->pList ){
55598     return 0;
55599   }
55600   if( pA->pSelect || pB->pSelect ) return 0;
55601   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
55602   if( pA->op!=TK_COLUMN && pA->token.z ){
55603     if( pB->token.z==0 ) return 0;
55604     if( pB->token.n!=pA->token.n ) return 0;
55605     if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){
55606       return 0;
55607     }
55608   }
55609   return 1;
55610 }
55611
55612
55613 /*
55614 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
55615 ** the new element.  Return a negative number if malloc fails.
55616 */
55617 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
55618   int i;
55619   pInfo->aCol = sqlite3ArrayAllocate(
55620        db,
55621        pInfo->aCol,
55622        sizeof(pInfo->aCol[0]),
55623        3,
55624        &pInfo->nColumn,
55625        &pInfo->nColumnAlloc,
55626        &i
55627   );
55628   return i;
55629 }    
55630
55631 /*
55632 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
55633 ** the new element.  Return a negative number if malloc fails.
55634 */
55635 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
55636   int i;
55637   pInfo->aFunc = sqlite3ArrayAllocate(
55638        db, 
55639        pInfo->aFunc,
55640        sizeof(pInfo->aFunc[0]),
55641        3,
55642        &pInfo->nFunc,
55643        &pInfo->nFuncAlloc,
55644        &i
55645   );
55646   return i;
55647 }    
55648
55649 /*
55650 ** This is the xExprCallback for a tree walker.  It is used to
55651 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
55652 ** for additional information.
55653 */
55654 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
55655   int i;
55656   NameContext *pNC = pWalker->u.pNC;
55657   Parse *pParse = pNC->pParse;
55658   SrcList *pSrcList = pNC->pSrcList;
55659   AggInfo *pAggInfo = pNC->pAggInfo;
55660
55661   switch( pExpr->op ){
55662     case TK_AGG_COLUMN:
55663     case TK_COLUMN: {
55664       testcase( pExpr->op==TK_AGG_COLUMN );
55665       testcase( pExpr->op==TK_COLUMN );
55666       /* Check to see if the column is in one of the tables in the FROM
55667       ** clause of the aggregate query */
55668       if( pSrcList ){
55669         struct SrcList_item *pItem = pSrcList->a;
55670         for(i=0; i<pSrcList->nSrc; i++, pItem++){
55671           struct AggInfo_col *pCol;
55672           if( pExpr->iTable==pItem->iCursor ){
55673             /* If we reach this point, it means that pExpr refers to a table
55674             ** that is in the FROM clause of the aggregate query.  
55675             **
55676             ** Make an entry for the column in pAggInfo->aCol[] if there
55677             ** is not an entry there already.
55678             */
55679             int k;
55680             pCol = pAggInfo->aCol;
55681             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
55682               if( pCol->iTable==pExpr->iTable &&
55683                   pCol->iColumn==pExpr->iColumn ){
55684                 break;
55685               }
55686             }
55687             if( (k>=pAggInfo->nColumn)
55688              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
55689             ){
55690               pCol = &pAggInfo->aCol[k];
55691               pCol->pTab = pExpr->pTab;
55692               pCol->iTable = pExpr->iTable;
55693               pCol->iColumn = pExpr->iColumn;
55694               pCol->iMem = ++pParse->nMem;
55695               pCol->iSorterColumn = -1;
55696               pCol->pExpr = pExpr;
55697               if( pAggInfo->pGroupBy ){
55698                 int j, n;
55699                 ExprList *pGB = pAggInfo->pGroupBy;
55700                 struct ExprList_item *pTerm = pGB->a;
55701                 n = pGB->nExpr;
55702                 for(j=0; j<n; j++, pTerm++){
55703                   Expr *pE = pTerm->pExpr;
55704                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
55705                       pE->iColumn==pExpr->iColumn ){
55706                     pCol->iSorterColumn = j;
55707                     break;
55708                   }
55709                 }
55710               }
55711               if( pCol->iSorterColumn<0 ){
55712                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
55713               }
55714             }
55715             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
55716             ** because it was there before or because we just created it).
55717             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
55718             ** pAggInfo->aCol[] entry.
55719             */
55720             pExpr->pAggInfo = pAggInfo;
55721             pExpr->op = TK_AGG_COLUMN;
55722             pExpr->iAgg = k;
55723             break;
55724           } /* endif pExpr->iTable==pItem->iCursor */
55725         } /* end loop over pSrcList */
55726       }
55727       return WRC_Prune;
55728     }
55729     case TK_AGG_FUNCTION: {
55730       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
55731       ** to be ignored */
55732       if( pNC->nDepth==0 ){
55733         /* Check to see if pExpr is a duplicate of another aggregate 
55734         ** function that is already in the pAggInfo structure
55735         */
55736         struct AggInfo_func *pItem = pAggInfo->aFunc;
55737         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
55738           if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
55739             break;
55740           }
55741         }
55742         if( i>=pAggInfo->nFunc ){
55743           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
55744           */
55745           u8 enc = ENC(pParse->db);
55746           i = addAggInfoFunc(pParse->db, pAggInfo);
55747           if( i>=0 ){
55748             pItem = &pAggInfo->aFunc[i];
55749             pItem->pExpr = pExpr;
55750             pItem->iMem = ++pParse->nMem;
55751             pItem->pFunc = sqlite3FindFunction(pParse->db,
55752                    (char*)pExpr->token.z, pExpr->token.n,
55753                    pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
55754             if( pExpr->flags & EP_Distinct ){
55755               pItem->iDistinct = pParse->nTab++;
55756             }else{
55757               pItem->iDistinct = -1;
55758             }
55759           }
55760         }
55761         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
55762         */
55763         pExpr->iAgg = i;
55764         pExpr->pAggInfo = pAggInfo;
55765         return WRC_Prune;
55766       }
55767     }
55768   }
55769   return WRC_Continue;
55770 }
55771 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
55772   NameContext *pNC = pWalker->u.pNC;
55773   if( pNC->nDepth==0 ){
55774     pNC->nDepth++;
55775     sqlite3WalkSelect(pWalker, pSelect);
55776     pNC->nDepth--;
55777     return WRC_Prune;
55778   }else{
55779     return WRC_Continue;
55780   }
55781 }
55782
55783 /*
55784 ** Analyze the given expression looking for aggregate functions and
55785 ** for variables that need to be added to the pParse->aAgg[] array.
55786 ** Make additional entries to the pParse->aAgg[] array as necessary.
55787 **
55788 ** This routine should only be called after the expression has been
55789 ** analyzed by sqlite3ResolveExprNames().
55790 */
55791 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
55792   Walker w;
55793   w.xExprCallback = analyzeAggregate;
55794   w.xSelectCallback = analyzeAggregatesInSelect;
55795   w.u.pNC = pNC;
55796   sqlite3WalkExpr(&w, pExpr);
55797 }
55798
55799 /*
55800 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
55801 ** expression list.  Return the number of errors.
55802 **
55803 ** If an error is found, the analysis is cut short.
55804 */
55805 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
55806   struct ExprList_item *pItem;
55807   int i;
55808   if( pList ){
55809     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
55810       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
55811     }
55812   }
55813 }
55814
55815 /*
55816 ** Allocate or deallocate temporary use registers during code generation.
55817 */
55818 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
55819   if( pParse->nTempReg==0 ){
55820     return ++pParse->nMem;
55821   }
55822   return pParse->aTempReg[--pParse->nTempReg];
55823 }
55824 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
55825   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
55826     sqlite3ExprWritableRegister(pParse, iReg, iReg);
55827     pParse->aTempReg[pParse->nTempReg++] = iReg;
55828   }
55829 }
55830
55831 /*
55832 ** Allocate or deallocate a block of nReg consecutive registers
55833 */
55834 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
55835   int i, n;
55836   i = pParse->iRangeReg;
55837   n = pParse->nRangeReg;
55838   if( nReg<=n && !usedAsColumnCache(pParse, i, i+n-1) ){
55839     pParse->iRangeReg += nReg;
55840     pParse->nRangeReg -= nReg;
55841   }else{
55842     i = pParse->nMem+1;
55843     pParse->nMem += nReg;
55844   }
55845   return i;
55846 }
55847 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
55848   if( nReg>pParse->nRangeReg ){
55849     pParse->nRangeReg = nReg;
55850     pParse->iRangeReg = iReg;
55851   }
55852 }
55853
55854 /************** End of expr.c ************************************************/
55855 /************** Begin file alter.c *******************************************/
55856 /*
55857 ** 2005 February 15
55858 **
55859 ** The author disclaims copyright to this source code.  In place of
55860 ** a legal notice, here is a blessing:
55861 **
55862 **    May you do good and not evil.
55863 **    May you find forgiveness for yourself and forgive others.
55864 **    May you share freely, never taking more than you give.
55865 **
55866 *************************************************************************
55867 ** This file contains C code routines that used to generate VDBE code
55868 ** that implements the ALTER TABLE command.
55869 **
55870 ** $Id: alter.c,v 1.48 2008/08/08 14:19:41 drh Exp $
55871 */
55872
55873 /*
55874 ** The code in this file only exists if we are not omitting the
55875 ** ALTER TABLE logic from the build.
55876 */
55877 #ifndef SQLITE_OMIT_ALTERTABLE
55878
55879
55880 /*
55881 ** This function is used by SQL generated to implement the 
55882 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
55883 ** CREATE INDEX command. The second is a table name. The table name in 
55884 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
55885 ** argument and the result returned. Examples:
55886 **
55887 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
55888 **     -> 'CREATE TABLE def(a, b, c)'
55889 **
55890 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
55891 **     -> 'CREATE INDEX i ON def(a, b, c)'
55892 */
55893 static void renameTableFunc(
55894   sqlite3_context *context,
55895   int argc,
55896   sqlite3_value **argv
55897 ){
55898   unsigned char const *zSql = sqlite3_value_text(argv[0]);
55899   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
55900
55901   int token;
55902   Token tname;
55903   unsigned char const *zCsr = zSql;
55904   int len = 0;
55905   char *zRet;
55906
55907   sqlite3 *db = sqlite3_context_db_handle(context);
55908
55909   /* The principle used to locate the table name in the CREATE TABLE 
55910   ** statement is that the table name is the first non-space token that
55911   ** is immediately followed by a TK_LP or TK_USING token.
55912   */
55913   if( zSql ){
55914     do {
55915       if( !*zCsr ){
55916         /* Ran out of input before finding an opening bracket. Return NULL. */
55917         return;
55918       }
55919
55920       /* Store the token that zCsr points to in tname. */
55921       tname.z = zCsr;
55922       tname.n = len;
55923
55924       /* Advance zCsr to the next token. Store that token type in 'token',
55925       ** and its length in 'len' (to be used next iteration of this loop).
55926       */
55927       do {
55928         zCsr += len;
55929         len = sqlite3GetToken(zCsr, &token);
55930       } while( token==TK_SPACE );
55931       assert( len>0 );
55932     } while( token!=TK_LP && token!=TK_USING );
55933
55934     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", tname.z - zSql, zSql, 
55935        zTableName, tname.z+tname.n);
55936     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
55937   }
55938 }
55939
55940 #ifndef SQLITE_OMIT_TRIGGER
55941 /* This function is used by SQL generated to implement the
55942 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
55943 ** statement. The second is a table name. The table name in the CREATE 
55944 ** TRIGGER statement is replaced with the third argument and the result 
55945 ** returned. This is analagous to renameTableFunc() above, except for CREATE
55946 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
55947 */
55948 static void renameTriggerFunc(
55949   sqlite3_context *context,
55950   int argc,
55951   sqlite3_value **argv
55952 ){
55953   unsigned char const *zSql = sqlite3_value_text(argv[0]);
55954   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
55955
55956   int token;
55957   Token tname;
55958   int dist = 3;
55959   unsigned char const *zCsr = zSql;
55960   int len = 0;
55961   char *zRet;
55962
55963   sqlite3 *db = sqlite3_context_db_handle(context);
55964
55965   /* The principle used to locate the table name in the CREATE TRIGGER 
55966   ** statement is that the table name is the first token that is immediatedly
55967   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
55968   ** of TK_WHEN, TK_BEGIN or TK_FOR.
55969   */
55970   if( zSql ){
55971     do {
55972
55973       if( !*zCsr ){
55974         /* Ran out of input before finding the table name. Return NULL. */
55975         return;
55976       }
55977
55978       /* Store the token that zCsr points to in tname. */
55979       tname.z = zCsr;
55980       tname.n = len;
55981
55982       /* Advance zCsr to the next token. Store that token type in 'token',
55983       ** and its length in 'len' (to be used next iteration of this loop).
55984       */
55985       do {
55986         zCsr += len;
55987         len = sqlite3GetToken(zCsr, &token);
55988       }while( token==TK_SPACE );
55989       assert( len>0 );
55990
55991       /* Variable 'dist' stores the number of tokens read since the most
55992       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN 
55993       ** token is read and 'dist' equals 2, the condition stated above
55994       ** to be met.
55995       **
55996       ** Note that ON cannot be a database, table or column name, so
55997       ** there is no need to worry about syntax like 
55998       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
55999       */
56000       dist++;
56001       if( token==TK_DOT || token==TK_ON ){
56002         dist = 0;
56003       }
56004     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
56005
56006     /* Variable tname now contains the token that is the old table-name
56007     ** in the CREATE TRIGGER statement.
56008     */
56009     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", tname.z - zSql, zSql, 
56010        zTableName, tname.z+tname.n);
56011     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
56012   }
56013 }
56014 #endif   /* !SQLITE_OMIT_TRIGGER */
56015
56016 /*
56017 ** Register built-in functions used to help implement ALTER TABLE
56018 */
56019 SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3 *db){
56020   sqlite3CreateFunc(db, "sqlite_rename_table", 2, SQLITE_UTF8, 0,
56021                          renameTableFunc, 0, 0);
56022 #ifndef SQLITE_OMIT_TRIGGER
56023   sqlite3CreateFunc(db, "sqlite_rename_trigger", 2, SQLITE_UTF8, 0,
56024                          renameTriggerFunc, 0, 0);
56025 #endif
56026 }
56027
56028 /*
56029 ** Generate the text of a WHERE expression which can be used to select all
56030 ** temporary triggers on table pTab from the sqlite_temp_master table. If
56031 ** table pTab has no temporary triggers, or is itself stored in the 
56032 ** temporary database, NULL is returned.
56033 */
56034 static char *whereTempTriggers(Parse *pParse, Table *pTab){
56035   Trigger *pTrig;
56036   char *zWhere = 0;
56037   char *tmp = 0;
56038   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
56039
56040   /* If the table is not located in the temp-db (in which case NULL is 
56041   ** returned, loop through the tables list of triggers. For each trigger
56042   ** that is not part of the temp-db schema, add a clause to the WHERE 
56043   ** expression being built up in zWhere.
56044   */
56045   if( pTab->pSchema!=pTempSchema ){
56046     sqlite3 *db = pParse->db;
56047     for( pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext ){
56048       if( pTrig->pSchema==pTempSchema ){
56049         if( !zWhere ){
56050           zWhere = sqlite3MPrintf(db, "name=%Q", pTrig->name);
56051         }else{
56052           tmp = zWhere;
56053           zWhere = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, pTrig->name);
56054           sqlite3DbFree(db, tmp);
56055         }
56056       }
56057     }
56058   }
56059   return zWhere;
56060 }
56061
56062 /*
56063 ** Generate code to drop and reload the internal representation of table
56064 ** pTab from the database, including triggers and temporary triggers.
56065 ** Argument zName is the name of the table in the database schema at
56066 ** the time the generated code is executed. This can be different from
56067 ** pTab->zName if this function is being called to code part of an 
56068 ** "ALTER TABLE RENAME TO" statement.
56069 */
56070 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
56071   Vdbe *v;
56072   char *zWhere;
56073   int iDb;                   /* Index of database containing pTab */
56074 #ifndef SQLITE_OMIT_TRIGGER
56075   Trigger *pTrig;
56076 #endif
56077
56078   v = sqlite3GetVdbe(pParse);
56079   if( !v ) return;
56080   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
56081   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
56082   assert( iDb>=0 );
56083
56084 #ifndef SQLITE_OMIT_TRIGGER
56085   /* Drop any table triggers from the internal schema. */
56086   for(pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext){
56087     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
56088     assert( iTrigDb==iDb || iTrigDb==1 );
56089     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->name, 0);
56090   }
56091 #endif
56092
56093   /* Drop the table and index from the internal schema */
56094   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
56095
56096   /* Reload the table, index and permanent trigger schemas. */
56097   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
56098   if( !zWhere ) return;
56099   sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
56100
56101 #ifndef SQLITE_OMIT_TRIGGER
56102   /* Now, if the table is not stored in the temp database, reload any temp 
56103   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. 
56104   */
56105   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
56106     sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
56107   }
56108 #endif
56109 }
56110
56111 /*
56112 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
56113 ** command. 
56114 */
56115 SQLITE_PRIVATE void sqlite3AlterRenameTable(
56116   Parse *pParse,            /* Parser context. */
56117   SrcList *pSrc,            /* The table to rename. */
56118   Token *pName              /* The new table name. */
56119 ){
56120   int iDb;                  /* Database that contains the table */
56121   char *zDb;                /* Name of database iDb */
56122   Table *pTab;              /* Table being renamed */
56123   char *zName = 0;          /* NULL-terminated version of pName */ 
56124   sqlite3 *db = pParse->db; /* Database connection */
56125   int nTabName;             /* Number of UTF-8 characters in zTabName */
56126   const char *zTabName;     /* Original name of the table */
56127   Vdbe *v;
56128 #ifndef SQLITE_OMIT_TRIGGER
56129   char *zWhere = 0;         /* Where clause to locate temp triggers */
56130 #endif
56131   int isVirtualRename = 0;  /* True if this is a v-table with an xRename() */
56132   
56133   if( db->mallocFailed ) goto exit_rename_table;
56134   assert( pSrc->nSrc==1 );
56135   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
56136
56137   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
56138   if( !pTab ) goto exit_rename_table;
56139   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
56140   zDb = db->aDb[iDb].zName;
56141
56142   /* Get a NULL terminated version of the new table name. */
56143   zName = sqlite3NameFromToken(db, pName);
56144   if( !zName ) goto exit_rename_table;
56145
56146   /* Check that a table or index named 'zName' does not already exist
56147   ** in database iDb. If so, this is an error.
56148   */
56149   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
56150     sqlite3ErrorMsg(pParse, 
56151         "there is already another table or index with this name: %s", zName);
56152     goto exit_rename_table;
56153   }
56154
56155   /* Make sure it is not a system table being altered, or a reserved name
56156   ** that the table is being renamed to.
56157   */
56158   if( strlen(pTab->zName)>6 && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7) ){
56159     sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
56160     goto exit_rename_table;
56161   }
56162   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
56163     goto exit_rename_table;
56164   }
56165
56166 #ifndef SQLITE_OMIT_VIEW
56167   if( pTab->pSelect ){
56168     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
56169     goto exit_rename_table;
56170   }
56171 #endif
56172
56173 #ifndef SQLITE_OMIT_AUTHORIZATION
56174   /* Invoke the authorization callback. */
56175   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
56176     goto exit_rename_table;
56177   }
56178 #endif
56179
56180 #ifndef SQLITE_OMIT_VIRTUALTABLE
56181   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
56182     goto exit_rename_table;
56183   }
56184   if( IsVirtual(pTab) && pTab->pMod->pModule->xRename ){
56185     isVirtualRename = 1;
56186   }
56187 #endif
56188
56189   /* Begin a transaction and code the VerifyCookie for database iDb. 
56190   ** Then modify the schema cookie (since the ALTER TABLE modifies the
56191   ** schema). Open a statement transaction if the table is a virtual
56192   ** table.
56193   */
56194   v = sqlite3GetVdbe(pParse);
56195   if( v==0 ){
56196     goto exit_rename_table;
56197   }
56198   sqlite3BeginWriteOperation(pParse, isVirtualRename, iDb);
56199   sqlite3ChangeCookie(pParse, iDb);
56200
56201   /* If this is a virtual table, invoke the xRename() function if
56202   ** one is defined. The xRename() callback will modify the names
56203   ** of any resources used by the v-table implementation (including other
56204   ** SQLite tables) that are identified by the name of the virtual table.
56205   */
56206 #ifndef SQLITE_OMIT_VIRTUALTABLE
56207   if( isVirtualRename ){
56208     int i = ++pParse->nMem;
56209     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
56210     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pTab->pVtab, P4_VTAB);
56211   }
56212 #endif
56213
56214   /* figure out how many UTF-8 characters are in zName */
56215   zTabName = pTab->zName;
56216   nTabName = sqlite3Utf8CharLen(zTabName, -1);
56217
56218   /* Modify the sqlite_master table to use the new table name. */
56219   sqlite3NestedParse(pParse,
56220       "UPDATE %Q.%s SET "
56221 #ifdef SQLITE_OMIT_TRIGGER
56222           "sql = sqlite_rename_table(sql, %Q), "
56223 #else
56224           "sql = CASE "
56225             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
56226             "ELSE sqlite_rename_table(sql, %Q) END, "
56227 #endif
56228           "tbl_name = %Q, "
56229           "name = CASE "
56230             "WHEN type='table' THEN %Q "
56231             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
56232              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
56233             "ELSE name END "
56234       "WHERE tbl_name=%Q AND "
56235           "(type='table' OR type='index' OR type='trigger');", 
56236       zDb, SCHEMA_TABLE(iDb), zName, zName, zName, 
56237 #ifndef SQLITE_OMIT_TRIGGER
56238       zName,
56239 #endif
56240       zName, nTabName, zTabName
56241   );
56242
56243 #ifndef SQLITE_OMIT_AUTOINCREMENT
56244   /* If the sqlite_sequence table exists in this database, then update 
56245   ** it with the new table name.
56246   */
56247   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
56248     sqlite3NestedParse(pParse,
56249         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
56250         zDb, zName, pTab->zName);
56251   }
56252 #endif
56253
56254 #ifndef SQLITE_OMIT_TRIGGER
56255   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
56256   ** table. Don't do this if the table being ALTERed is itself located in
56257   ** the temp database.
56258   */
56259   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
56260     sqlite3NestedParse(pParse, 
56261         "UPDATE sqlite_temp_master SET "
56262             "sql = sqlite_rename_trigger(sql, %Q), "
56263             "tbl_name = %Q "
56264             "WHERE %s;", zName, zName, zWhere);
56265     sqlite3DbFree(db, zWhere);
56266   }
56267 #endif
56268
56269   /* Drop and reload the internal table schema. */
56270   reloadTableSchema(pParse, pTab, zName);
56271
56272 exit_rename_table:
56273   sqlite3SrcListDelete(db, pSrc);
56274   sqlite3DbFree(db, zName);
56275 }
56276
56277
56278 /*
56279 ** This function is called after an "ALTER TABLE ... ADD" statement
56280 ** has been parsed. Argument pColDef contains the text of the new
56281 ** column definition.
56282 **
56283 ** The Table structure pParse->pNewTable was extended to include
56284 ** the new column during parsing.
56285 */
56286 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
56287   Table *pNew;              /* Copy of pParse->pNewTable */
56288   Table *pTab;              /* Table being altered */
56289   int iDb;                  /* Database number */
56290   const char *zDb;          /* Database name */
56291   const char *zTab;         /* Table name */
56292   char *zCol;               /* Null-terminated column definition */
56293   Column *pCol;             /* The new column */
56294   Expr *pDflt;              /* Default value for the new column */
56295   sqlite3 *db;              /* The database connection; */
56296
56297   if( pParse->nErr ) return;
56298   pNew = pParse->pNewTable;
56299   assert( pNew );
56300
56301   db = pParse->db;
56302   assert( sqlite3BtreeHoldsAllMutexes(db) );
56303   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
56304   zDb = db->aDb[iDb].zName;
56305   zTab = pNew->zName;
56306   pCol = &pNew->aCol[pNew->nCol-1];
56307   pDflt = pCol->pDflt;
56308   pTab = sqlite3FindTable(db, zTab, zDb);
56309   assert( pTab );
56310
56311 #ifndef SQLITE_OMIT_AUTHORIZATION
56312   /* Invoke the authorization callback. */
56313   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
56314     return;
56315   }
56316 #endif
56317
56318   /* If the default value for the new column was specified with a 
56319   ** literal NULL, then set pDflt to 0. This simplifies checking
56320   ** for an SQL NULL default below.
56321   */
56322   if( pDflt && pDflt->op==TK_NULL ){
56323     pDflt = 0;
56324   }
56325
56326   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
56327   ** If there is a NOT NULL constraint, then the default value for the
56328   ** column must not be NULL.
56329   */
56330   if( pCol->isPrimKey ){
56331     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
56332     return;
56333   }
56334   if( pNew->pIndex ){
56335     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
56336     return;
56337   }
56338   if( pCol->notNull && !pDflt ){
56339     sqlite3ErrorMsg(pParse, 
56340         "Cannot add a NOT NULL column with default value NULL");
56341     return;
56342   }
56343
56344   /* Ensure the default expression is something that sqlite3ValueFromExpr()
56345   ** can handle (i.e. not CURRENT_TIME etc.)
56346   */
56347   if( pDflt ){
56348     sqlite3_value *pVal;
56349     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
56350       db->mallocFailed = 1;
56351       return;
56352     }
56353     if( !pVal ){
56354       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
56355       return;
56356     }
56357     sqlite3ValueFree(pVal);
56358   }
56359
56360   /* Modify the CREATE TABLE statement. */
56361   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
56362   if( zCol ){
56363     char *zEnd = &zCol[pColDef->n-1];
56364     while( (zEnd>zCol && *zEnd==';') || isspace(*(unsigned char *)zEnd) ){
56365       *zEnd-- = '\0';
56366     }
56367     sqlite3NestedParse(pParse, 
56368         "UPDATE \"%w\".%s SET "
56369           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
56370         "WHERE type = 'table' AND name = %Q", 
56371       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
56372       zTab
56373     );
56374     sqlite3DbFree(db, zCol);
56375   }
56376
56377   /* If the default value of the new column is NULL, then set the file
56378   ** format to 2. If the default value of the new column is not NULL,
56379   ** the file format becomes 3.
56380   */
56381   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
56382
56383   /* Reload the schema of the modified table. */
56384   reloadTableSchema(pParse, pTab, pTab->zName);
56385 }
56386
56387 /*
56388 ** This function is called by the parser after the table-name in
56389 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
56390 ** pSrc is the full-name of the table being altered.
56391 **
56392 ** This routine makes a (partial) copy of the Table structure
56393 ** for the table being altered and sets Parse.pNewTable to point
56394 ** to it. Routines called by the parser as the column definition
56395 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
56396 ** the copy. The copy of the Table structure is deleted by tokenize.c 
56397 ** after parsing is finished.
56398 **
56399 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
56400 ** coding the "ALTER TABLE ... ADD" statement.
56401 */
56402 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
56403   Table *pNew;
56404   Table *pTab;
56405   Vdbe *v;
56406   int iDb;
56407   int i;
56408   int nAlloc;
56409   sqlite3 *db = pParse->db;
56410
56411   /* Look up the table being altered. */
56412   assert( pParse->pNewTable==0 );
56413   assert( sqlite3BtreeHoldsAllMutexes(db) );
56414   if( db->mallocFailed ) goto exit_begin_add_column;
56415   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
56416   if( !pTab ) goto exit_begin_add_column;
56417
56418 #ifndef SQLITE_OMIT_VIRTUALTABLE
56419   if( IsVirtual(pTab) ){
56420     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
56421     goto exit_begin_add_column;
56422   }
56423 #endif
56424
56425   /* Make sure this is not an attempt to ALTER a view. */
56426   if( pTab->pSelect ){
56427     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
56428     goto exit_begin_add_column;
56429   }
56430
56431   assert( pTab->addColOffset>0 );
56432   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
56433
56434   /* Put a copy of the Table struct in Parse.pNewTable for the
56435   ** sqlite3AddColumn() function and friends to modify.
56436   */
56437   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
56438   if( !pNew ) goto exit_begin_add_column;
56439   pParse->pNewTable = pNew;
56440   pNew->nRef = 1;
56441   pNew->db = db;
56442   pNew->nCol = pTab->nCol;
56443   assert( pNew->nCol>0 );
56444   nAlloc = (((pNew->nCol-1)/8)*8)+8;
56445   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
56446   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
56447   pNew->zName = sqlite3DbStrDup(db, pTab->zName);
56448   if( !pNew->aCol || !pNew->zName ){
56449     db->mallocFailed = 1;
56450     goto exit_begin_add_column;
56451   }
56452   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
56453   for(i=0; i<pNew->nCol; i++){
56454     Column *pCol = &pNew->aCol[i];
56455     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
56456     pCol->zColl = 0;
56457     pCol->zType = 0;
56458     pCol->pDflt = 0;
56459   }
56460   pNew->pSchema = db->aDb[iDb].pSchema;
56461   pNew->addColOffset = pTab->addColOffset;
56462   pNew->nRef = 1;
56463
56464   /* Begin a transaction and increment the schema cookie.  */
56465   sqlite3BeginWriteOperation(pParse, 0, iDb);
56466   v = sqlite3GetVdbe(pParse);
56467   if( !v ) goto exit_begin_add_column;
56468   sqlite3ChangeCookie(pParse, iDb);
56469
56470 exit_begin_add_column:
56471   sqlite3SrcListDelete(db, pSrc);
56472   return;
56473 }
56474 #endif  /* SQLITE_ALTER_TABLE */
56475
56476 /************** End of alter.c ***********************************************/
56477 /************** Begin file analyze.c *****************************************/
56478 /*
56479 ** 2005 July 8
56480 **
56481 ** The author disclaims copyright to this source code.  In place of
56482 ** a legal notice, here is a blessing:
56483 **
56484 **    May you do good and not evil.
56485 **    May you find forgiveness for yourself and forgive others.
56486 **    May you share freely, never taking more than you give.
56487 **
56488 *************************************************************************
56489 ** This file contains code associated with the ANALYZE command.
56490 **
56491 ** @(#) $Id: analyze.c,v 1.43 2008/07/28 19:34:53 drh Exp $
56492 */
56493 #ifndef SQLITE_OMIT_ANALYZE
56494
56495 /*
56496 ** This routine generates code that opens the sqlite_stat1 table on cursor
56497 ** iStatCur.
56498 **
56499 ** If the sqlite_stat1 tables does not previously exist, it is created.
56500 ** If it does previously exist, all entires associated with table zWhere
56501 ** are removed.  If zWhere==0 then all entries are removed.
56502 */
56503 static void openStatTable(
56504   Parse *pParse,          /* Parsing context */
56505   int iDb,                /* The database we are looking in */
56506   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
56507   const char *zWhere      /* Delete entries associated with this table */
56508 ){
56509   sqlite3 *db = pParse->db;
56510   Db *pDb;
56511   int iRootPage;
56512   int createStat1 = 0;
56513   Table *pStat;
56514   Vdbe *v = sqlite3GetVdbe(pParse);
56515
56516   if( v==0 ) return;
56517   assert( sqlite3BtreeHoldsAllMutexes(db) );
56518   assert( sqlite3VdbeDb(v)==db );
56519   pDb = &db->aDb[iDb];
56520   if( (pStat = sqlite3FindTable(db, "sqlite_stat1", pDb->zName))==0 ){
56521     /* The sqlite_stat1 tables does not exist.  Create it.  
56522     ** Note that a side-effect of the CREATE TABLE statement is to leave
56523     ** the rootpage of the new table in register pParse->regRoot.  This is
56524     ** important because the OpenWrite opcode below will be needing it. */
56525     sqlite3NestedParse(pParse,
56526       "CREATE TABLE %Q.sqlite_stat1(tbl,idx,stat)",
56527       pDb->zName
56528     );
56529     iRootPage = pParse->regRoot;
56530     createStat1 = 1;  /* Cause rootpage to be taken from top of stack */
56531   }else if( zWhere ){
56532     /* The sqlite_stat1 table exists.  Delete all entries associated with
56533     ** the table zWhere. */
56534     sqlite3NestedParse(pParse,
56535        "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q",
56536        pDb->zName, zWhere
56537     );
56538     iRootPage = pStat->tnum;
56539   }else{
56540     /* The sqlite_stat1 table already exists.  Delete all rows. */
56541     iRootPage = pStat->tnum;
56542     sqlite3VdbeAddOp2(v, OP_Clear, pStat->tnum, iDb);
56543   }
56544
56545   /* Open the sqlite_stat1 table for writing. Unless it was created
56546   ** by this vdbe program, lock it for writing at the shared-cache level. 
56547   ** If this vdbe did create the sqlite_stat1 table, then it must have 
56548   ** already obtained a schema-lock, making the write-lock redundant.
56549   */
56550   if( !createStat1 ){
56551     sqlite3TableLock(pParse, iDb, iRootPage, 1, "sqlite_stat1");
56552   }
56553   sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, 3);
56554   sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur, iRootPage, iDb);
56555   sqlite3VdbeChangeP5(v, createStat1);
56556 }
56557
56558 /*
56559 ** Generate code to do an analysis of all indices associated with
56560 ** a single table.
56561 */
56562 static void analyzeOneTable(
56563   Parse *pParse,   /* Parser context */
56564   Table *pTab,     /* Table whose indices are to be analyzed */
56565   int iStatCur,    /* Cursor that writes to the sqlite_stat1 table */
56566   int iMem         /* Available memory locations begin here */
56567 ){
56568   Index *pIdx;     /* An index to being analyzed */
56569   int iIdxCur;     /* Cursor number for index being analyzed */
56570   int nCol;        /* Number of columns in the index */
56571   Vdbe *v;         /* The virtual machine being built up */
56572   int i;           /* Loop counter */
56573   int topOfLoop;   /* The top of the loop */
56574   int endOfLoop;   /* The end of the loop */
56575   int addr;        /* The address of an instruction */
56576   int iDb;         /* Index of database containing pTab */
56577
56578   v = sqlite3GetVdbe(pParse);
56579   if( v==0 || pTab==0 || pTab->pIndex==0 ){
56580     /* Do no analysis for tables that have no indices */
56581     return;
56582   }
56583   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
56584   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
56585   assert( iDb>=0 );
56586 #ifndef SQLITE_OMIT_AUTHORIZATION
56587   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
56588       pParse->db->aDb[iDb].zName ) ){
56589     return;
56590   }
56591 #endif
56592
56593   /* Establish a read-lock on the table at the shared-cache level. */
56594   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
56595
56596   iIdxCur = pParse->nTab;
56597   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
56598     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
56599     int regFields;    /* Register block for building records */
56600     int regRec;       /* Register holding completed record */
56601     int regTemp;      /* Temporary use register */
56602     int regCol;       /* Content of a column from the table being analyzed */
56603     int regRowid;     /* Rowid for the inserted record */
56604     int regF2;
56605
56606     /* Open a cursor to the index to be analyzed
56607     */
56608     assert( iDb==sqlite3SchemaToIndex(pParse->db, pIdx->pSchema) );
56609     nCol = pIdx->nColumn;
56610     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, nCol+1);
56611     sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
56612         (char *)pKey, P4_KEYINFO_HANDOFF);
56613     VdbeComment((v, "%s", pIdx->zName));
56614     regFields = iMem+nCol*2;
56615     regTemp = regRowid = regCol = regFields+3;
56616     regRec = regCol+1;
56617     if( regRec>pParse->nMem ){
56618       pParse->nMem = regRec;
56619     }
56620
56621     /* Memory cells are used as follows:
56622     **
56623     **    mem[iMem]:             The total number of rows in the table.
56624     **    mem[iMem+1]:           Number of distinct values in column 1
56625     **    ...
56626     **    mem[iMem+nCol]:        Number of distinct values in column N
56627     **    mem[iMem+nCol+1]       Last observed value of column 1
56628     **    ...
56629     **    mem[iMem+nCol+nCol]:   Last observed value of column N
56630     **
56631     ** Cells iMem through iMem+nCol are initialized to 0.  The others
56632     ** are initialized to NULL.
56633     */
56634     for(i=0; i<=nCol; i++){
56635       sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
56636     }
56637     for(i=0; i<nCol; i++){
56638       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
56639     }
56640
56641     /* Do the analysis.
56642     */
56643     endOfLoop = sqlite3VdbeMakeLabel(v);
56644     sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
56645     topOfLoop = sqlite3VdbeCurrentAddr(v);
56646     sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
56647     for(i=0; i<nCol; i++){
56648       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
56649       sqlite3VdbeAddOp3(v, OP_Ne, regCol, 0, iMem+nCol+i+1);
56650       /**** TODO:  add collating sequence *****/
56651       sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
56652     }
56653     sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
56654     for(i=0; i<nCol; i++){
56655       sqlite3VdbeJumpHere(v, topOfLoop + 2*(i + 1));
56656       sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
56657       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
56658     }
56659     sqlite3VdbeResolveLabel(v, endOfLoop);
56660     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
56661     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
56662
56663     /* Store the results.  
56664     **
56665     ** The result is a single row of the sqlite_stat1 table.  The first
56666     ** two columns are the names of the table and index.  The third column
56667     ** is a string composed of a list of integer statistics about the
56668     ** index.  The first integer in the list is the total number of entires
56669     ** in the index.  There is one additional integer in the list for each
56670     ** column of the table.  This additional integer is a guess of how many
56671     ** rows of the table the index will select.  If D is the count of distinct
56672     ** values and K is the total number of rows, then the integer is computed
56673     ** as:
56674     **
56675     **        I = (K+D-1)/D
56676     **
56677     ** If K==0 then no entry is made into the sqlite_stat1 table.  
56678     ** If K>0 then it is always the case the D>0 so division by zero
56679     ** is never possible.
56680     */
56681     addr = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
56682     sqlite3VdbeAddOp4(v, OP_String8, 0, regFields, 0, pTab->zName, 0);
56683     sqlite3VdbeAddOp4(v, OP_String8, 0, regFields+1, 0, pIdx->zName, 0);
56684     regF2 = regFields+2;
56685     sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regF2);
56686     for(i=0; i<nCol; i++){
56687       sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
56688       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regF2, regF2);
56689       sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
56690       sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
56691       sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
56692       sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
56693       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regF2, regF2);
56694     }
56695     sqlite3VdbeAddOp4(v, OP_MakeRecord, regFields, 3, regRec, "aaa", 0);
56696     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
56697     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
56698     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
56699     sqlite3VdbeJumpHere(v, addr);
56700   }
56701 }
56702
56703 /*
56704 ** Generate code that will cause the most recent index analysis to
56705 ** be laoded into internal hash tables where is can be used.
56706 */
56707 static void loadAnalysis(Parse *pParse, int iDb){
56708   Vdbe *v = sqlite3GetVdbe(pParse);
56709   if( v ){
56710     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
56711   }
56712 }
56713
56714 /*
56715 ** Generate code that will do an analysis of an entire database
56716 */
56717 static void analyzeDatabase(Parse *pParse, int iDb){
56718   sqlite3 *db = pParse->db;
56719   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
56720   HashElem *k;
56721   int iStatCur;
56722   int iMem;
56723
56724   sqlite3BeginWriteOperation(pParse, 0, iDb);
56725   iStatCur = pParse->nTab++;
56726   openStatTable(pParse, iDb, iStatCur, 0);
56727   iMem = pParse->nMem+1;
56728   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
56729     Table *pTab = (Table*)sqliteHashData(k);
56730     analyzeOneTable(pParse, pTab, iStatCur, iMem);
56731   }
56732   loadAnalysis(pParse, iDb);
56733 }
56734
56735 /*
56736 ** Generate code that will do an analysis of a single table in
56737 ** a database.
56738 */
56739 static void analyzeTable(Parse *pParse, Table *pTab){
56740   int iDb;
56741   int iStatCur;
56742
56743   assert( pTab!=0 );
56744   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
56745   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
56746   sqlite3BeginWriteOperation(pParse, 0, iDb);
56747   iStatCur = pParse->nTab++;
56748   openStatTable(pParse, iDb, iStatCur, pTab->zName);
56749   analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem+1);
56750   loadAnalysis(pParse, iDb);
56751 }
56752
56753 /*
56754 ** Generate code for the ANALYZE command.  The parser calls this routine
56755 ** when it recognizes an ANALYZE command.
56756 **
56757 **        ANALYZE                            -- 1
56758 **        ANALYZE  <database>                -- 2
56759 **        ANALYZE  ?<database>.?<tablename>  -- 3
56760 **
56761 ** Form 1 causes all indices in all attached databases to be analyzed.
56762 ** Form 2 analyzes all indices the single database named.
56763 ** Form 3 analyzes all indices associated with the named table.
56764 */
56765 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
56766   sqlite3 *db = pParse->db;
56767   int iDb;
56768   int i;
56769   char *z, *zDb;
56770   Table *pTab;
56771   Token *pTableName;
56772
56773   /* Read the database schema. If an error occurs, leave an error message
56774   ** and code in pParse and return NULL. */
56775   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
56776   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
56777     return;
56778   }
56779
56780   if( pName1==0 ){
56781     /* Form 1:  Analyze everything */
56782     for(i=0; i<db->nDb; i++){
56783       if( i==1 ) continue;  /* Do not analyze the TEMP database */
56784       analyzeDatabase(pParse, i);
56785     }
56786   }else if( pName2==0 || pName2->n==0 ){
56787     /* Form 2:  Analyze the database or table named */
56788     iDb = sqlite3FindDb(db, pName1);
56789     if( iDb>=0 ){
56790       analyzeDatabase(pParse, iDb);
56791     }else{
56792       z = sqlite3NameFromToken(db, pName1);
56793       if( z ){
56794         pTab = sqlite3LocateTable(pParse, 0, z, 0);
56795         sqlite3DbFree(db, z);
56796         if( pTab ){
56797           analyzeTable(pParse, pTab);
56798         }
56799       }
56800     }
56801   }else{
56802     /* Form 3: Analyze the fully qualified table name */
56803     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
56804     if( iDb>=0 ){
56805       zDb = db->aDb[iDb].zName;
56806       z = sqlite3NameFromToken(db, pTableName);
56807       if( z ){
56808         pTab = sqlite3LocateTable(pParse, 0, z, zDb);
56809         sqlite3DbFree(db, z);
56810         if( pTab ){
56811           analyzeTable(pParse, pTab);
56812         }
56813       }
56814     }   
56815   }
56816 }
56817
56818 /*
56819 ** Used to pass information from the analyzer reader through to the
56820 ** callback routine.
56821 */
56822 typedef struct analysisInfo analysisInfo;
56823 struct analysisInfo {
56824   sqlite3 *db;
56825   const char *zDatabase;
56826 };
56827
56828 /*
56829 ** This callback is invoked once for each index when reading the
56830 ** sqlite_stat1 table.  
56831 **
56832 **     argv[0] = name of the index
56833 **     argv[1] = results of analysis - on integer for each column
56834 */
56835 static int analysisLoader(void *pData, int argc, char **argv, char **azNotUsed){
56836   analysisInfo *pInfo = (analysisInfo*)pData;
56837   Index *pIndex;
56838   int i, c;
56839   unsigned int v;
56840   const char *z;
56841
56842   assert( argc==2 );
56843   if( argv==0 || argv[0]==0 || argv[1]==0 ){
56844     return 0;
56845   }
56846   pIndex = sqlite3FindIndex(pInfo->db, argv[0], pInfo->zDatabase);
56847   if( pIndex==0 ){
56848     return 0;
56849   }
56850   z = argv[1];
56851   for(i=0; *z && i<=pIndex->nColumn; i++){
56852     v = 0;
56853     while( (c=z[0])>='0' && c<='9' ){
56854       v = v*10 + c - '0';
56855       z++;
56856     }
56857     pIndex->aiRowEst[i] = v;
56858     if( *z==' ' ) z++;
56859   }
56860   return 0;
56861 }
56862
56863 /*
56864 ** Load the content of the sqlite_stat1 table into the index hash tables.
56865 */
56866 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
56867   analysisInfo sInfo;
56868   HashElem *i;
56869   char *zSql;
56870   int rc;
56871
56872   assert( iDb>=0 && iDb<db->nDb );
56873   assert( db->aDb[iDb].pBt!=0 );
56874   assert( sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
56875
56876   /* Clear any prior statistics */
56877   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
56878     Index *pIdx = sqliteHashData(i);
56879     sqlite3DefaultRowEst(pIdx);
56880   }
56881
56882   /* Check to make sure the sqlite_stat1 table existss */
56883   sInfo.db = db;
56884   sInfo.zDatabase = db->aDb[iDb].zName;
56885   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
56886      return SQLITE_ERROR;
56887   }
56888
56889
56890   /* Load new statistics out of the sqlite_stat1 table */
56891   zSql = sqlite3MPrintf(db, "SELECT idx, stat FROM %Q.sqlite_stat1",
56892                         sInfo.zDatabase);
56893   (void)sqlite3SafetyOff(db);
56894   rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
56895   (void)sqlite3SafetyOn(db);
56896   sqlite3DbFree(db, zSql);
56897   return rc;
56898 }
56899
56900
56901 #endif /* SQLITE_OMIT_ANALYZE */
56902
56903 /************** End of analyze.c *********************************************/
56904 /************** Begin file attach.c ******************************************/
56905 /*
56906 ** 2003 April 6
56907 **
56908 ** The author disclaims copyright to this source code.  In place of
56909 ** a legal notice, here is a blessing:
56910 **
56911 **    May you do good and not evil.
56912 **    May you find forgiveness for yourself and forgive others.
56913 **    May you share freely, never taking more than you give.
56914 **
56915 *************************************************************************
56916 ** This file contains code used to implement the ATTACH and DETACH commands.
56917 **
56918 ** $Id: attach.c,v 1.78 2008/08/20 16:35:10 drh Exp $
56919 */
56920
56921 #ifndef SQLITE_OMIT_ATTACH
56922 /*
56923 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
56924 ** is slightly different from resolving a normal SQL expression, because simple
56925 ** identifiers are treated as strings, not possible column names or aliases.
56926 **
56927 ** i.e. if the parser sees:
56928 **
56929 **     ATTACH DATABASE abc AS def
56930 **
56931 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
56932 ** looking for columns of the same name.
56933 **
56934 ** This only applies to the root node of pExpr, so the statement:
56935 **
56936 **     ATTACH DATABASE abc||def AS 'db2'
56937 **
56938 ** will fail because neither abc or def can be resolved.
56939 */
56940 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
56941 {
56942   int rc = SQLITE_OK;
56943   if( pExpr ){
56944     if( pExpr->op!=TK_ID ){
56945       rc = sqlite3ResolveExprNames(pName, pExpr);
56946       if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
56947         sqlite3ErrorMsg(pName->pParse, "invalid name: \"%T\"", &pExpr->span);
56948         return SQLITE_ERROR;
56949       }
56950     }else{
56951       pExpr->op = TK_STRING;
56952     }
56953   }
56954   return rc;
56955 }
56956
56957 /*
56958 ** An SQL user-function registered to do the work of an ATTACH statement. The
56959 ** three arguments to the function come directly from an attach statement:
56960 **
56961 **     ATTACH DATABASE x AS y KEY z
56962 **
56963 **     SELECT sqlite_attach(x, y, z)
56964 **
56965 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
56966 ** third argument.
56967 */
56968 static void attachFunc(
56969   sqlite3_context *context,
56970   int argc,
56971   sqlite3_value **argv
56972 ){
56973   int i;
56974   int rc = 0;
56975   sqlite3 *db = sqlite3_context_db_handle(context);
56976   const char *zName;
56977   const char *zFile;
56978   Db *aNew;
56979   char *zErrDyn = 0;
56980   char zErr[128];
56981
56982   zFile = (const char *)sqlite3_value_text(argv[0]);
56983   zName = (const char *)sqlite3_value_text(argv[1]);
56984   if( zFile==0 ) zFile = "";
56985   if( zName==0 ) zName = "";
56986
56987   /* Check for the following errors:
56988   **
56989   **     * Too many attached databases,
56990   **     * Transaction currently open
56991   **     * Specified database name already being used.
56992   */
56993   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
56994     sqlite3_snprintf(
56995       sizeof(zErr), zErr, "too many attached databases - max %d", 
56996       db->aLimit[SQLITE_LIMIT_ATTACHED]
56997     );
56998     goto attach_error;
56999   }
57000   if( !db->autoCommit ){
57001     sqlite3_snprintf(sizeof(zErr), zErr,
57002                      "cannot ATTACH database within transaction");
57003     goto attach_error;
57004   }
57005   for(i=0; i<db->nDb; i++){
57006     char *z = db->aDb[i].zName;
57007     if( z && zName && sqlite3StrICmp(z, zName)==0 ){
57008       sqlite3_snprintf(sizeof(zErr), zErr, 
57009                        "database %s is already in use", zName);
57010       goto attach_error;
57011     }
57012   }
57013
57014   /* Allocate the new entry in the db->aDb[] array and initialise the schema
57015   ** hash tables.
57016   */
57017   if( db->aDb==db->aDbStatic ){
57018     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
57019     if( aNew==0 ) return;
57020     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
57021   }else{
57022     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
57023     if( aNew==0 ) return;
57024   }
57025   db->aDb = aNew;
57026   aNew = &db->aDb[db->nDb++];
57027   memset(aNew, 0, sizeof(*aNew));
57028
57029   /* Open the database file. If the btree is successfully opened, use
57030   ** it to obtain the database schema. At this point the schema may
57031   ** or may not be initialised.
57032   */
57033   rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE,
57034                            db->openFlags | SQLITE_OPEN_MAIN_DB,
57035                            &aNew->pBt);
57036   if( rc==SQLITE_OK ){
57037     Pager *pPager;
57038     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
57039     if( !aNew->pSchema ){
57040       rc = SQLITE_NOMEM;
57041     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
57042       sqlite3_snprintf(sizeof(zErr), zErr, 
57043         "attached databases must use the same text encoding as main database");
57044       goto attach_error;
57045     }
57046     pPager = sqlite3BtreePager(aNew->pBt);
57047     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
57048     sqlite3PagerJournalMode(pPager, db->dfltJournalMode);
57049   }
57050   aNew->zName = sqlite3DbStrDup(db, zName);
57051   aNew->safety_level = 3;
57052
57053 #if SQLITE_HAS_CODEC
57054   {
57055     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
57056     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
57057     int nKey;
57058     char *zKey;
57059     int t = sqlite3_value_type(argv[2]);
57060     switch( t ){
57061       case SQLITE_INTEGER:
57062       case SQLITE_FLOAT:
57063         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
57064         rc = SQLITE_ERROR;
57065         break;
57066         
57067       case SQLITE_TEXT:
57068       case SQLITE_BLOB:
57069         nKey = sqlite3_value_bytes(argv[2]);
57070         zKey = (char *)sqlite3_value_blob(argv[2]);
57071         sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
57072         break;
57073
57074       case SQLITE_NULL:
57075         /* No key specified.  Use the key from the main database */
57076         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
57077         sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
57078         break;
57079     }
57080   }
57081 #endif
57082
57083   /* If the file was opened successfully, read the schema for the new database.
57084   ** If this fails, or if opening the file failed, then close the file and 
57085   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
57086   ** we found it.
57087   */
57088   if( rc==SQLITE_OK ){
57089     (void)sqlite3SafetyOn(db);
57090     sqlite3BtreeEnterAll(db);
57091     rc = sqlite3Init(db, &zErrDyn);
57092     sqlite3BtreeLeaveAll(db);
57093     (void)sqlite3SafetyOff(db);
57094   }
57095   if( rc ){
57096     int iDb = db->nDb - 1;
57097     assert( iDb>=2 );
57098     if( db->aDb[iDb].pBt ){
57099       sqlite3BtreeClose(db->aDb[iDb].pBt);
57100       db->aDb[iDb].pBt = 0;
57101       db->aDb[iDb].pSchema = 0;
57102     }
57103     sqlite3ResetInternalSchema(db, 0);
57104     db->nDb = iDb;
57105     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
57106       db->mallocFailed = 1;
57107       sqlite3_snprintf(sizeof(zErr),zErr, "out of memory");
57108     }else{
57109       sqlite3_snprintf(sizeof(zErr),zErr, "unable to open database: %s", zFile);
57110     }
57111     goto attach_error;
57112   }
57113   
57114   return;
57115
57116 attach_error:
57117   /* Return an error if we get here */
57118   if( zErrDyn ){
57119     sqlite3_result_error(context, zErrDyn, -1);
57120     sqlite3DbFree(db, zErrDyn);
57121   }else{
57122     zErr[sizeof(zErr)-1] = 0;
57123     sqlite3_result_error(context, zErr, -1);
57124   }
57125   if( rc ) sqlite3_result_error_code(context, rc);
57126 }
57127
57128 /*
57129 ** An SQL user-function registered to do the work of an DETACH statement. The
57130 ** three arguments to the function come directly from a detach statement:
57131 **
57132 **     DETACH DATABASE x
57133 **
57134 **     SELECT sqlite_detach(x)
57135 */
57136 static void detachFunc(
57137   sqlite3_context *context,
57138   int argc,
57139   sqlite3_value **argv
57140 ){
57141   const char *zName = (const char *)sqlite3_value_text(argv[0]);
57142   sqlite3 *db = sqlite3_context_db_handle(context);
57143   int i;
57144   Db *pDb = 0;
57145   char zErr[128];
57146
57147   if( zName==0 ) zName = "";
57148   for(i=0; i<db->nDb; i++){
57149     pDb = &db->aDb[i];
57150     if( pDb->pBt==0 ) continue;
57151     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
57152   }
57153
57154   if( i>=db->nDb ){
57155     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
57156     goto detach_error;
57157   }
57158   if( i<2 ){
57159     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
57160     goto detach_error;
57161   }
57162   if( !db->autoCommit ){
57163     sqlite3_snprintf(sizeof(zErr), zErr,
57164                      "cannot DETACH database within transaction");
57165     goto detach_error;
57166   }
57167   if( sqlite3BtreeIsInReadTrans(pDb->pBt) ){
57168     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
57169     goto detach_error;
57170   }
57171
57172   sqlite3BtreeClose(pDb->pBt);
57173   pDb->pBt = 0;
57174   pDb->pSchema = 0;
57175   sqlite3ResetInternalSchema(db, 0);
57176   return;
57177
57178 detach_error:
57179   sqlite3_result_error(context, zErr, -1);
57180 }
57181
57182 /*
57183 ** This procedure generates VDBE code for a single invocation of either the
57184 ** sqlite_detach() or sqlite_attach() SQL user functions.
57185 */
57186 static void codeAttach(
57187   Parse *pParse,       /* The parser context */
57188   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
57189   const char *zFunc,   /* Either "sqlite_attach" or "sqlite_detach */
57190   int nFunc,           /* Number of args to pass to zFunc */
57191   Expr *pAuthArg,      /* Expression to pass to authorization callback */
57192   Expr *pFilename,     /* Name of database file */
57193   Expr *pDbname,       /* Name of the database to use internally */
57194   Expr *pKey           /* Database key for encryption extension */
57195 ){
57196   int rc;
57197   NameContext sName;
57198   Vdbe *v;
57199   FuncDef *pFunc;
57200   sqlite3* db = pParse->db;
57201   int regArgs;
57202
57203 #ifndef SQLITE_OMIT_AUTHORIZATION
57204   assert( db->mallocFailed || pAuthArg );
57205   if( pAuthArg ){
57206     char *zAuthArg = sqlite3NameFromToken(db, &pAuthArg->span);
57207     if( !zAuthArg ){
57208       goto attach_end;
57209     }
57210     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
57211     sqlite3DbFree(db, zAuthArg);
57212     if(rc!=SQLITE_OK ){
57213       goto attach_end;
57214     }
57215   }
57216 #endif /* SQLITE_OMIT_AUTHORIZATION */
57217
57218   memset(&sName, 0, sizeof(NameContext));
57219   sName.pParse = pParse;
57220
57221   if( 
57222       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
57223       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
57224       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
57225   ){
57226     pParse->nErr++;
57227     goto attach_end;
57228   }
57229
57230   v = sqlite3GetVdbe(pParse);
57231   regArgs = sqlite3GetTempRange(pParse, 4);
57232   sqlite3ExprCode(pParse, pFilename, regArgs);
57233   sqlite3ExprCode(pParse, pDbname, regArgs+1);
57234   sqlite3ExprCode(pParse, pKey, regArgs+2);
57235
57236   assert( v || db->mallocFailed );
57237   if( v ){
57238     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-nFunc, regArgs+3);
57239     sqlite3VdbeChangeP5(v, nFunc);
57240     pFunc = sqlite3FindFunction(db, zFunc, strlen(zFunc), nFunc, SQLITE_UTF8,0);
57241     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
57242
57243     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
57244     ** statement only). For DETACH, set it to false (expire all existing
57245     ** statements).
57246     */
57247     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
57248   }
57249   
57250 attach_end:
57251   sqlite3ExprDelete(db, pFilename);
57252   sqlite3ExprDelete(db, pDbname);
57253   sqlite3ExprDelete(db, pKey);
57254 }
57255
57256 /*
57257 ** Called by the parser to compile a DETACH statement.
57258 **
57259 **     DETACH pDbname
57260 */
57261 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
57262   codeAttach(pParse, SQLITE_DETACH, "sqlite_detach", 1, pDbname, 0, 0, pDbname);
57263 }
57264
57265 /*
57266 ** Called by the parser to compile an ATTACH statement.
57267 **
57268 **     ATTACH p AS pDbname KEY pKey
57269 */
57270 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
57271   codeAttach(pParse, SQLITE_ATTACH, "sqlite_attach", 3, p, p, pDbname, pKey);
57272 }
57273 #endif /* SQLITE_OMIT_ATTACH */
57274
57275 /*
57276 ** Register the functions sqlite_attach and sqlite_detach.
57277 */
57278 SQLITE_PRIVATE void sqlite3AttachFunctions(sqlite3 *db){
57279 #ifndef SQLITE_OMIT_ATTACH
57280   static const int enc = SQLITE_UTF8;
57281   sqlite3CreateFunc(db, "sqlite_attach", 3, enc, 0, attachFunc, 0, 0);
57282   sqlite3CreateFunc(db, "sqlite_detach", 1, enc, 0, detachFunc, 0, 0);
57283 #endif
57284 }
57285
57286 /*
57287 ** Initialize a DbFixer structure.  This routine must be called prior
57288 ** to passing the structure to one of the sqliteFixAAAA() routines below.
57289 **
57290 ** The return value indicates whether or not fixation is required.  TRUE
57291 ** means we do need to fix the database references, FALSE means we do not.
57292 */
57293 SQLITE_PRIVATE int sqlite3FixInit(
57294   DbFixer *pFix,      /* The fixer to be initialized */
57295   Parse *pParse,      /* Error messages will be written here */
57296   int iDb,            /* This is the database that must be used */
57297   const char *zType,  /* "view", "trigger", or "index" */
57298   const Token *pName  /* Name of the view, trigger, or index */
57299 ){
57300   sqlite3 *db;
57301
57302   if( iDb<0 || iDb==1 ) return 0;
57303   db = pParse->db;
57304   assert( db->nDb>iDb );
57305   pFix->pParse = pParse;
57306   pFix->zDb = db->aDb[iDb].zName;
57307   pFix->zType = zType;
57308   pFix->pName = pName;
57309   return 1;
57310 }
57311
57312 /*
57313 ** The following set of routines walk through the parse tree and assign
57314 ** a specific database to all table references where the database name
57315 ** was left unspecified in the original SQL statement.  The pFix structure
57316 ** must have been initialized by a prior call to sqlite3FixInit().
57317 **
57318 ** These routines are used to make sure that an index, trigger, or
57319 ** view in one database does not refer to objects in a different database.
57320 ** (Exception: indices, triggers, and views in the TEMP database are
57321 ** allowed to refer to anything.)  If a reference is explicitly made
57322 ** to an object in a different database, an error message is added to
57323 ** pParse->zErrMsg and these routines return non-zero.  If everything
57324 ** checks out, these routines return 0.
57325 */
57326 SQLITE_PRIVATE int sqlite3FixSrcList(
57327   DbFixer *pFix,       /* Context of the fixation */
57328   SrcList *pList       /* The Source list to check and modify */
57329 ){
57330   int i;
57331   const char *zDb;
57332   struct SrcList_item *pItem;
57333
57334   if( pList==0 ) return 0;
57335   zDb = pFix->zDb;
57336   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
57337     if( pItem->zDatabase==0 ){
57338       pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
57339     }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
57340       sqlite3ErrorMsg(pFix->pParse,
57341          "%s %T cannot reference objects in database %s",
57342          pFix->zType, pFix->pName, pItem->zDatabase);
57343       return 1;
57344     }
57345 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
57346     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
57347     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
57348 #endif
57349   }
57350   return 0;
57351 }
57352 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
57353 SQLITE_PRIVATE int sqlite3FixSelect(
57354   DbFixer *pFix,       /* Context of the fixation */
57355   Select *pSelect      /* The SELECT statement to be fixed to one database */
57356 ){
57357   while( pSelect ){
57358     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
57359       return 1;
57360     }
57361     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
57362       return 1;
57363     }
57364     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
57365       return 1;
57366     }
57367     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
57368       return 1;
57369     }
57370     pSelect = pSelect->pPrior;
57371   }
57372   return 0;
57373 }
57374 SQLITE_PRIVATE int sqlite3FixExpr(
57375   DbFixer *pFix,     /* Context of the fixation */
57376   Expr *pExpr        /* The expression to be fixed to one database */
57377 ){
57378   while( pExpr ){
57379     if( sqlite3FixSelect(pFix, pExpr->pSelect) ){
57380       return 1;
57381     }
57382     if( sqlite3FixExprList(pFix, pExpr->pList) ){
57383       return 1;
57384     }
57385     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
57386       return 1;
57387     }
57388     pExpr = pExpr->pLeft;
57389   }
57390   return 0;
57391 }
57392 SQLITE_PRIVATE int sqlite3FixExprList(
57393   DbFixer *pFix,     /* Context of the fixation */
57394   ExprList *pList    /* The expression to be fixed to one database */
57395 ){
57396   int i;
57397   struct ExprList_item *pItem;
57398   if( pList==0 ) return 0;
57399   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
57400     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
57401       return 1;
57402     }
57403   }
57404   return 0;
57405 }
57406 #endif
57407
57408 #ifndef SQLITE_OMIT_TRIGGER
57409 SQLITE_PRIVATE int sqlite3FixTriggerStep(
57410   DbFixer *pFix,     /* Context of the fixation */
57411   TriggerStep *pStep /* The trigger step be fixed to one database */
57412 ){
57413   while( pStep ){
57414     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
57415       return 1;
57416     }
57417     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
57418       return 1;
57419     }
57420     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
57421       return 1;
57422     }
57423     pStep = pStep->pNext;
57424   }
57425   return 0;
57426 }
57427 #endif
57428
57429 /************** End of attach.c **********************************************/
57430 /************** Begin file auth.c ********************************************/
57431 /*
57432 ** 2003 January 11
57433 **
57434 ** The author disclaims copyright to this source code.  In place of
57435 ** a legal notice, here is a blessing:
57436 **
57437 **    May you do good and not evil.
57438 **    May you find forgiveness for yourself and forgive others.
57439 **    May you share freely, never taking more than you give.
57440 **
57441 *************************************************************************
57442 ** This file contains code used to implement the sqlite3_set_authorizer()
57443 ** API.  This facility is an optional feature of the library.  Embedded
57444 ** systems that do not need this facility may omit it by recompiling
57445 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
57446 **
57447 ** $Id: auth.c,v 1.29 2007/09/18 15:55:07 drh Exp $
57448 */
57449
57450 /*
57451 ** All of the code in this file may be omitted by defining a single
57452 ** macro.
57453 */
57454 #ifndef SQLITE_OMIT_AUTHORIZATION
57455
57456 /*
57457 ** Set or clear the access authorization function.
57458 **
57459 ** The access authorization function is be called during the compilation
57460 ** phase to verify that the user has read and/or write access permission on
57461 ** various fields of the database.  The first argument to the auth function
57462 ** is a copy of the 3rd argument to this routine.  The second argument
57463 ** to the auth function is one of these constants:
57464 **
57465 **       SQLITE_CREATE_INDEX
57466 **       SQLITE_CREATE_TABLE
57467 **       SQLITE_CREATE_TEMP_INDEX
57468 **       SQLITE_CREATE_TEMP_TABLE
57469 **       SQLITE_CREATE_TEMP_TRIGGER
57470 **       SQLITE_CREATE_TEMP_VIEW
57471 **       SQLITE_CREATE_TRIGGER
57472 **       SQLITE_CREATE_VIEW
57473 **       SQLITE_DELETE
57474 **       SQLITE_DROP_INDEX
57475 **       SQLITE_DROP_TABLE
57476 **       SQLITE_DROP_TEMP_INDEX
57477 **       SQLITE_DROP_TEMP_TABLE
57478 **       SQLITE_DROP_TEMP_TRIGGER
57479 **       SQLITE_DROP_TEMP_VIEW
57480 **       SQLITE_DROP_TRIGGER
57481 **       SQLITE_DROP_VIEW
57482 **       SQLITE_INSERT
57483 **       SQLITE_PRAGMA
57484 **       SQLITE_READ
57485 **       SQLITE_SELECT
57486 **       SQLITE_TRANSACTION
57487 **       SQLITE_UPDATE
57488 **
57489 ** The third and fourth arguments to the auth function are the name of
57490 ** the table and the column that are being accessed.  The auth function
57491 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
57492 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
57493 ** means that the SQL statement will never-run - the sqlite3_exec() call
57494 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
57495 ** should run but attempts to read the specified column will return NULL
57496 ** and attempts to write the column will be ignored.
57497 **
57498 ** Setting the auth function to NULL disables this hook.  The default
57499 ** setting of the auth function is NULL.
57500 */
57501 SQLITE_API int sqlite3_set_authorizer(
57502   sqlite3 *db,
57503   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
57504   void *pArg
57505 ){
57506   sqlite3_mutex_enter(db->mutex);
57507   db->xAuth = xAuth;
57508   db->pAuthArg = pArg;
57509   sqlite3ExpirePreparedStatements(db);
57510   sqlite3_mutex_leave(db->mutex);
57511   return SQLITE_OK;
57512 }
57513
57514 /*
57515 ** Write an error message into pParse->zErrMsg that explains that the
57516 ** user-supplied authorization function returned an illegal value.
57517 */
57518 static void sqliteAuthBadReturnCode(Parse *pParse, int rc){
57519   sqlite3ErrorMsg(pParse, "illegal return value (%d) from the "
57520     "authorization function - should be SQLITE_OK, SQLITE_IGNORE, "
57521     "or SQLITE_DENY", rc);
57522   pParse->rc = SQLITE_ERROR;
57523 }
57524
57525 /*
57526 ** The pExpr should be a TK_COLUMN expression.  The table referred to
57527 ** is in pTabList or else it is the NEW or OLD table of a trigger.  
57528 ** Check to see if it is OK to read this particular column.
57529 **
57530 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
57531 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
57532 ** then generate an error.
57533 */
57534 SQLITE_PRIVATE void sqlite3AuthRead(
57535   Parse *pParse,        /* The parser context */
57536   Expr *pExpr,          /* The expression to check authorization on */
57537   Schema *pSchema,      /* The schema of the expression */
57538   SrcList *pTabList     /* All table that pExpr might refer to */
57539 ){
57540   sqlite3 *db = pParse->db;
57541   int rc;
57542   Table *pTab = 0;      /* The table being read */
57543   const char *zCol;     /* Name of the column of the table */
57544   int iSrc;             /* Index in pTabList->a[] of table being read */
57545   const char *zDBase;   /* Name of database being accessed */
57546   TriggerStack *pStack; /* The stack of current triggers */
57547   int iDb;              /* The index of the database the expression refers to */
57548
57549   if( db->xAuth==0 ) return;
57550   if( pExpr->op!=TK_COLUMN ) return;
57551   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
57552   if( iDb<0 ){
57553     /* An attempt to read a column out of a subquery or other
57554     ** temporary table. */
57555     return;
57556   }
57557   for(iSrc=0; pTabList && iSrc<pTabList->nSrc; iSrc++){
57558     if( pExpr->iTable==pTabList->a[iSrc].iCursor ) break;
57559   }
57560   if( iSrc>=0 && pTabList && iSrc<pTabList->nSrc ){
57561     pTab = pTabList->a[iSrc].pTab;
57562   }else if( (pStack = pParse->trigStack)!=0 ){
57563     /* This must be an attempt to read the NEW or OLD pseudo-tables
57564     ** of a trigger.
57565     */
57566     assert( pExpr->iTable==pStack->newIdx || pExpr->iTable==pStack->oldIdx );
57567     pTab = pStack->pTab;
57568   }
57569   if( pTab==0 ) return;
57570   if( pExpr->iColumn>=0 ){
57571     assert( pExpr->iColumn<pTab->nCol );
57572     zCol = pTab->aCol[pExpr->iColumn].zName;
57573   }else if( pTab->iPKey>=0 ){
57574     assert( pTab->iPKey<pTab->nCol );
57575     zCol = pTab->aCol[pTab->iPKey].zName;
57576   }else{
57577     zCol = "ROWID";
57578   }
57579   assert( iDb>=0 && iDb<db->nDb );
57580   zDBase = db->aDb[iDb].zName;
57581   rc = db->xAuth(db->pAuthArg, SQLITE_READ, pTab->zName, zCol, zDBase, 
57582                  pParse->zAuthContext);
57583   if( rc==SQLITE_IGNORE ){
57584     pExpr->op = TK_NULL;
57585   }else if( rc==SQLITE_DENY ){
57586     if( db->nDb>2 || iDb!=0 ){
57587       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited", 
57588          zDBase, pTab->zName, zCol);
57589     }else{
57590       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited",pTab->zName,zCol);
57591     }
57592     pParse->rc = SQLITE_AUTH;
57593   }else if( rc!=SQLITE_OK ){
57594     sqliteAuthBadReturnCode(pParse, rc);
57595   }
57596 }
57597
57598 /*
57599 ** Do an authorization check using the code and arguments given.  Return
57600 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
57601 ** is returned, then the error count and error message in pParse are
57602 ** modified appropriately.
57603 */
57604 SQLITE_PRIVATE int sqlite3AuthCheck(
57605   Parse *pParse,
57606   int code,
57607   const char *zArg1,
57608   const char *zArg2,
57609   const char *zArg3
57610 ){
57611   sqlite3 *db = pParse->db;
57612   int rc;
57613
57614   /* Don't do any authorization checks if the database is initialising
57615   ** or if the parser is being invoked from within sqlite3_declare_vtab.
57616   */
57617   if( db->init.busy || IN_DECLARE_VTAB ){
57618     return SQLITE_OK;
57619   }
57620
57621   if( db->xAuth==0 ){
57622     return SQLITE_OK;
57623   }
57624   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
57625   if( rc==SQLITE_DENY ){
57626     sqlite3ErrorMsg(pParse, "not authorized");
57627     pParse->rc = SQLITE_AUTH;
57628   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
57629     rc = SQLITE_DENY;
57630     sqliteAuthBadReturnCode(pParse, rc);
57631   }
57632   return rc;
57633 }
57634
57635 /*
57636 ** Push an authorization context.  After this routine is called, the
57637 ** zArg3 argument to authorization callbacks will be zContext until
57638 ** popped.  Or if pParse==0, this routine is a no-op.
57639 */
57640 SQLITE_PRIVATE void sqlite3AuthContextPush(
57641   Parse *pParse,
57642   AuthContext *pContext, 
57643   const char *zContext
57644 ){
57645   pContext->pParse = pParse;
57646   if( pParse ){
57647     pContext->zAuthContext = pParse->zAuthContext;
57648     pParse->zAuthContext = zContext;
57649   }
57650 }
57651
57652 /*
57653 ** Pop an authorization context that was previously pushed
57654 ** by sqlite3AuthContextPush
57655 */
57656 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
57657   if( pContext->pParse ){
57658     pContext->pParse->zAuthContext = pContext->zAuthContext;
57659     pContext->pParse = 0;
57660   }
57661 }
57662
57663 #endif /* SQLITE_OMIT_AUTHORIZATION */
57664
57665 /************** End of auth.c ************************************************/
57666 /************** Begin file build.c *******************************************/
57667 /*
57668 ** 2001 September 15
57669 **
57670 ** The author disclaims copyright to this source code.  In place of
57671 ** a legal notice, here is a blessing:
57672 **
57673 **    May you do good and not evil.
57674 **    May you find forgiveness for yourself and forgive others.
57675 **    May you share freely, never taking more than you give.
57676 **
57677 *************************************************************************
57678 ** This file contains C code routines that are called by the SQLite parser
57679 ** when syntax rules are reduced.  The routines in this file handle the
57680 ** following kinds of SQL syntax:
57681 **
57682 **     CREATE TABLE
57683 **     DROP TABLE
57684 **     CREATE INDEX
57685 **     DROP INDEX
57686 **     creating ID lists
57687 **     BEGIN TRANSACTION
57688 **     COMMIT
57689 **     ROLLBACK
57690 **
57691 ** $Id: build.c,v 1.496 2008/08/20 16:35:10 drh Exp $
57692 */
57693
57694 /*
57695 ** This routine is called when a new SQL statement is beginning to
57696 ** be parsed.  Initialize the pParse structure as needed.
57697 */
57698 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
57699   pParse->explain = explainFlag;
57700   pParse->nVar = 0;
57701 }
57702
57703 #ifndef SQLITE_OMIT_SHARED_CACHE
57704 /*
57705 ** The TableLock structure is only used by the sqlite3TableLock() and
57706 ** codeTableLocks() functions.
57707 */
57708 struct TableLock {
57709   int iDb;             /* The database containing the table to be locked */
57710   int iTab;            /* The root page of the table to be locked */
57711   u8 isWriteLock;      /* True for write lock.  False for a read lock */
57712   const char *zName;   /* Name of the table */
57713 };
57714
57715 /*
57716 ** Record the fact that we want to lock a table at run-time.  
57717 **
57718 ** The table to be locked has root page iTab and is found in database iDb.
57719 ** A read or a write lock can be taken depending on isWritelock.
57720 **
57721 ** This routine just records the fact that the lock is desired.  The
57722 ** code to make the lock occur is generated by a later call to
57723 ** codeTableLocks() which occurs during sqlite3FinishCoding().
57724 */
57725 SQLITE_PRIVATE void sqlite3TableLock(
57726   Parse *pParse,     /* Parsing context */
57727   int iDb,           /* Index of the database containing the table to lock */
57728   int iTab,          /* Root page number of the table to be locked */
57729   u8 isWriteLock,    /* True for a write lock */
57730   const char *zName  /* Name of the table to be locked */
57731 ){
57732   int i;
57733   int nBytes;
57734   TableLock *p;
57735
57736   if( iDb<0 ){
57737     return;
57738   }
57739
57740   for(i=0; i<pParse->nTableLock; i++){
57741     p = &pParse->aTableLock[i];
57742     if( p->iDb==iDb && p->iTab==iTab ){
57743       p->isWriteLock = (p->isWriteLock || isWriteLock);
57744       return;
57745     }
57746   }
57747
57748   nBytes = sizeof(TableLock) * (pParse->nTableLock+1);
57749   pParse->aTableLock = 
57750       sqlite3DbReallocOrFree(pParse->db, pParse->aTableLock, nBytes);
57751   if( pParse->aTableLock ){
57752     p = &pParse->aTableLock[pParse->nTableLock++];
57753     p->iDb = iDb;
57754     p->iTab = iTab;
57755     p->isWriteLock = isWriteLock;
57756     p->zName = zName;
57757   }else{
57758     pParse->nTableLock = 0;
57759     pParse->db->mallocFailed = 1;
57760   }
57761 }
57762
57763 /*
57764 ** Code an OP_TableLock instruction for each table locked by the
57765 ** statement (configured by calls to sqlite3TableLock()).
57766 */
57767 static void codeTableLocks(Parse *pParse){
57768   int i;
57769   Vdbe *pVdbe; 
57770
57771   if( 0==(pVdbe = sqlite3GetVdbe(pParse)) ){
57772     return;
57773   }
57774
57775   for(i=0; i<pParse->nTableLock; i++){
57776     TableLock *p = &pParse->aTableLock[i];
57777     int p1 = p->iDb;
57778     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
57779                       p->zName, P4_STATIC);
57780   }
57781 }
57782 #else
57783   #define codeTableLocks(x)
57784 #endif
57785
57786 /*
57787 ** This routine is called after a single SQL statement has been
57788 ** parsed and a VDBE program to execute that statement has been
57789 ** prepared.  This routine puts the finishing touches on the
57790 ** VDBE program and resets the pParse structure for the next
57791 ** parse.
57792 **
57793 ** Note that if an error occurred, it might be the case that
57794 ** no VDBE code was generated.
57795 */
57796 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
57797   sqlite3 *db;
57798   Vdbe *v;
57799
57800   db = pParse->db;
57801   if( db->mallocFailed ) return;
57802   if( pParse->nested ) return;
57803   if( pParse->nErr ) return;
57804
57805   /* Begin by generating some termination code at the end of the
57806   ** vdbe program
57807   */
57808   v = sqlite3GetVdbe(pParse);
57809   if( v ){
57810     sqlite3VdbeAddOp0(v, OP_Halt);
57811
57812     /* The cookie mask contains one bit for each database file open.
57813     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
57814     ** set for each database that is used.  Generate code to start a
57815     ** transaction on each used database and to verify the schema cookie
57816     ** on each used database.
57817     */
57818     if( pParse->cookieGoto>0 ){
57819       u32 mask;
57820       int iDb;
57821       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
57822       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
57823         if( (mask & pParse->cookieMask)==0 ) continue;
57824         sqlite3VdbeUsesBtree(v, iDb);
57825         sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
57826         sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
57827       }
57828 #ifndef SQLITE_OMIT_VIRTUALTABLE
57829       {
57830         int i;
57831         for(i=0; i<pParse->nVtabLock; i++){
57832           char *vtab = (char *)pParse->apVtabLock[i]->pVtab;
57833           sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
57834         }
57835         pParse->nVtabLock = 0;
57836       }
57837 #endif
57838
57839       /* Once all the cookies have been verified and transactions opened, 
57840       ** obtain the required table-locks. This is a no-op unless the 
57841       ** shared-cache feature is enabled.
57842       */
57843       codeTableLocks(pParse);
57844       sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
57845     }
57846
57847 #ifndef SQLITE_OMIT_TRACE
57848     if( !db->init.busy ){
57849       /* Change the P4 argument of the first opcode (which will always be
57850       ** an OP_Trace) to be the complete text of the current SQL statement.
57851       */
57852       VdbeOp *pOp = sqlite3VdbeGetOp(v, 0);
57853       if( pOp && pOp->opcode==OP_Trace ){
57854         sqlite3VdbeChangeP4(v, 0, pParse->zSql, pParse->zTail-pParse->zSql);
57855       }
57856     }
57857 #endif /* SQLITE_OMIT_TRACE */
57858   }
57859
57860
57861   /* Get the VDBE program ready for execution
57862   */
57863   if( v && pParse->nErr==0 && !db->mallocFailed ){
57864 #ifdef SQLITE_DEBUG
57865     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
57866     sqlite3VdbeTrace(v, trace);
57867 #endif
57868     assert( pParse->disableColCache==0 );  /* Disables and re-enables match */
57869     sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem+3,
57870                          pParse->nTab+3, pParse->explain);
57871     pParse->rc = SQLITE_DONE;
57872     pParse->colNamesSet = 0;
57873   }else if( pParse->rc==SQLITE_OK ){
57874     pParse->rc = SQLITE_ERROR;
57875   }
57876   pParse->nTab = 0;
57877   pParse->nMem = 0;
57878   pParse->nSet = 0;
57879   pParse->nVar = 0;
57880   pParse->cookieMask = 0;
57881   pParse->cookieGoto = 0;
57882 }
57883
57884 /*
57885 ** Run the parser and code generator recursively in order to generate
57886 ** code for the SQL statement given onto the end of the pParse context
57887 ** currently under construction.  When the parser is run recursively
57888 ** this way, the final OP_Halt is not appended and other initialization
57889 ** and finalization steps are omitted because those are handling by the
57890 ** outermost parser.
57891 **
57892 ** Not everything is nestable.  This facility is designed to permit
57893 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
57894 ** care if you decide to try to use this routine for some other purposes.
57895 */
57896 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
57897   va_list ap;
57898   char *zSql;
57899   char *zErrMsg = 0;
57900   sqlite3 *db = pParse->db;
57901 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
57902   char saveBuf[SAVE_SZ];
57903
57904   if( pParse->nErr ) return;
57905   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
57906   va_start(ap, zFormat);
57907   zSql = sqlite3VMPrintf(db, zFormat, ap);
57908   va_end(ap);
57909   if( zSql==0 ){
57910     return;   /* A malloc must have failed */
57911   }
57912   pParse->nested++;
57913   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
57914   memset(&pParse->nVar, 0, SAVE_SZ);
57915   sqlite3RunParser(pParse, zSql, &zErrMsg);
57916   sqlite3DbFree(db, zErrMsg);
57917   sqlite3DbFree(db, zSql);
57918   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
57919   pParse->nested--;
57920 }
57921
57922 /*
57923 ** Locate the in-memory structure that describes a particular database
57924 ** table given the name of that table and (optionally) the name of the
57925 ** database containing the table.  Return NULL if not found.
57926 **
57927 ** If zDatabase is 0, all databases are searched for the table and the
57928 ** first matching table is returned.  (No checking for duplicate table
57929 ** names is done.)  The search order is TEMP first, then MAIN, then any
57930 ** auxiliary databases added using the ATTACH command.
57931 **
57932 ** See also sqlite3LocateTable().
57933 */
57934 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
57935   Table *p = 0;
57936   int i;
57937   int nName;
57938   assert( zName!=0 );
57939   nName = sqlite3Strlen(db, zName) + 1;
57940   for(i=OMIT_TEMPDB; i<db->nDb; i++){
57941     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
57942     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
57943     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
57944     if( p ) break;
57945   }
57946   return p;
57947 }
57948
57949 /*
57950 ** Locate the in-memory structure that describes a particular database
57951 ** table given the name of that table and (optionally) the name of the
57952 ** database containing the table.  Return NULL if not found.  Also leave an
57953 ** error message in pParse->zErrMsg.
57954 **
57955 ** The difference between this routine and sqlite3FindTable() is that this
57956 ** routine leaves an error message in pParse->zErrMsg where
57957 ** sqlite3FindTable() does not.
57958 */
57959 SQLITE_PRIVATE Table *sqlite3LocateTable(
57960   Parse *pParse,         /* context in which to report errors */
57961   int isView,            /* True if looking for a VIEW rather than a TABLE */
57962   const char *zName,     /* Name of the table we are looking for */
57963   const char *zDbase     /* Name of the database.  Might be NULL */
57964 ){
57965   Table *p;
57966
57967   /* Read the database schema. If an error occurs, leave an error message
57968   ** and code in pParse and return NULL. */
57969   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
57970     return 0;
57971   }
57972
57973   p = sqlite3FindTable(pParse->db, zName, zDbase);
57974   if( p==0 ){
57975     const char *zMsg = isView ? "no such view" : "no such table";
57976     if( zDbase ){
57977       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
57978     }else{
57979       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
57980     }
57981     pParse->checkSchema = 1;
57982   }
57983   return p;
57984 }
57985
57986 /*
57987 ** Locate the in-memory structure that describes 
57988 ** a particular index given the name of that index
57989 ** and the name of the database that contains the index.
57990 ** Return NULL if not found.
57991 **
57992 ** If zDatabase is 0, all databases are searched for the
57993 ** table and the first matching index is returned.  (No checking
57994 ** for duplicate index names is done.)  The search order is
57995 ** TEMP first, then MAIN, then any auxiliary databases added
57996 ** using the ATTACH command.
57997 */
57998 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
57999   Index *p = 0;
58000   int i;
58001   int nName = sqlite3Strlen(db, zName)+1;
58002   for(i=OMIT_TEMPDB; i<db->nDb; i++){
58003     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
58004     Schema *pSchema = db->aDb[j].pSchema;
58005     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
58006     assert( pSchema || (j==1 && !db->aDb[1].pBt) );
58007     if( pSchema ){
58008       p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
58009     }
58010     if( p ) break;
58011   }
58012   return p;
58013 }
58014
58015 /*
58016 ** Reclaim the memory used by an index
58017 */
58018 static void freeIndex(Index *p){
58019   sqlite3 *db = p->pTable->db;
58020   sqlite3DbFree(db, p->zColAff);
58021   sqlite3DbFree(db, p);
58022 }
58023
58024 /*
58025 ** Remove the given index from the index hash table, and free
58026 ** its memory structures.
58027 **
58028 ** The index is removed from the database hash tables but
58029 ** it is not unlinked from the Table that it indexes.
58030 ** Unlinking from the Table must be done by the calling function.
58031 */
58032 static void sqliteDeleteIndex(Index *p){
58033   Index *pOld;
58034   const char *zName = p->zName;
58035
58036   pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName, strlen(zName)+1, 0);
58037   assert( pOld==0 || pOld==p );
58038   freeIndex(p);
58039 }
58040
58041 /*
58042 ** For the index called zIdxName which is found in the database iDb,
58043 ** unlike that index from its Table then remove the index from
58044 ** the index hash table and free all memory structures associated
58045 ** with the index.
58046 */
58047 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
58048   Index *pIndex;
58049   int len;
58050   Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
58051
58052   len = sqlite3Strlen(db, zIdxName);
58053   pIndex = sqlite3HashInsert(pHash, zIdxName, len+1, 0);
58054   if( pIndex ){
58055     if( pIndex->pTable->pIndex==pIndex ){
58056       pIndex->pTable->pIndex = pIndex->pNext;
58057     }else{
58058       Index *p;
58059       for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
58060       if( p && p->pNext==pIndex ){
58061         p->pNext = pIndex->pNext;
58062       }
58063     }
58064     freeIndex(pIndex);
58065   }
58066   db->flags |= SQLITE_InternChanges;
58067 }
58068
58069 /*
58070 ** Erase all schema information from the in-memory hash tables of
58071 ** a single database.  This routine is called to reclaim memory
58072 ** before the database closes.  It is also called during a rollback
58073 ** if there were schema changes during the transaction or if a
58074 ** schema-cookie mismatch occurs.
58075 **
58076 ** If iDb<=0 then reset the internal schema tables for all database
58077 ** files.  If iDb>=2 then reset the internal schema for only the
58078 ** single file indicated.
58079 */
58080 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
58081   int i, j;
58082   assert( iDb>=0 && iDb<db->nDb );
58083
58084   if( iDb==0 ){
58085     sqlite3BtreeEnterAll(db);
58086   }
58087   for(i=iDb; i<db->nDb; i++){
58088     Db *pDb = &db->aDb[i];
58089     if( pDb->pSchema ){
58090       assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
58091       sqlite3SchemaFree(pDb->pSchema);
58092     }
58093     if( iDb>0 ) return;
58094   }
58095   assert( iDb==0 );
58096   db->flags &= ~SQLITE_InternChanges;
58097   sqlite3BtreeLeaveAll(db);
58098
58099   /* If one or more of the auxiliary database files has been closed,
58100   ** then remove them from the auxiliary database list.  We take the
58101   ** opportunity to do this here since we have just deleted all of the
58102   ** schema hash tables and therefore do not have to make any changes
58103   ** to any of those tables.
58104   */
58105   for(i=0; i<db->nDb; i++){
58106     struct Db *pDb = &db->aDb[i];
58107     if( pDb->pBt==0 ){
58108       if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
58109       pDb->pAux = 0;
58110     }
58111   }
58112   for(i=j=2; i<db->nDb; i++){
58113     struct Db *pDb = &db->aDb[i];
58114     if( pDb->pBt==0 ){
58115       sqlite3DbFree(db, pDb->zName);
58116       pDb->zName = 0;
58117       continue;
58118     }
58119     if( j<i ){
58120       db->aDb[j] = db->aDb[i];
58121     }
58122     j++;
58123   }
58124   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
58125   db->nDb = j;
58126   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
58127     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
58128     sqlite3DbFree(db, db->aDb);
58129     db->aDb = db->aDbStatic;
58130   }
58131 }
58132
58133 /*
58134 ** This routine is called when a commit occurs.
58135 */
58136 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
58137   db->flags &= ~SQLITE_InternChanges;
58138 }
58139
58140 /*
58141 ** Clear the column names from a table or view.
58142 */
58143 static void sqliteResetColumnNames(Table *pTable){
58144   int i;
58145   Column *pCol;
58146   sqlite3 *db = pTable->db;
58147   assert( pTable!=0 );
58148   if( (pCol = pTable->aCol)!=0 ){
58149     for(i=0; i<pTable->nCol; i++, pCol++){
58150       sqlite3DbFree(db, pCol->zName);
58151       sqlite3ExprDelete(db, pCol->pDflt);
58152       sqlite3DbFree(db, pCol->zType);
58153       sqlite3DbFree(db, pCol->zColl);
58154     }
58155     sqlite3DbFree(db, pTable->aCol);
58156   }
58157   pTable->aCol = 0;
58158   pTable->nCol = 0;
58159 }
58160
58161 /*
58162 ** Remove the memory data structures associated with the given
58163 ** Table.  No changes are made to disk by this routine.
58164 **
58165 ** This routine just deletes the data structure.  It does not unlink
58166 ** the table data structure from the hash table.  Nor does it remove
58167 ** foreign keys from the sqlite.aFKey hash table.  But it does destroy
58168 ** memory structures of the indices and foreign keys associated with 
58169 ** the table.
58170 */
58171 SQLITE_PRIVATE void sqlite3DeleteTable(Table *pTable){
58172   Index *pIndex, *pNext;
58173   FKey *pFKey, *pNextFKey;
58174   sqlite3 *db;
58175
58176   if( pTable==0 ) return;
58177   db = pTable->db;
58178
58179   /* Do not delete the table until the reference count reaches zero. */
58180   pTable->nRef--;
58181   if( pTable->nRef>0 ){
58182     return;
58183   }
58184   assert( pTable->nRef==0 );
58185
58186   /* Delete all indices associated with this table
58187   */
58188   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
58189     pNext = pIndex->pNext;
58190     assert( pIndex->pSchema==pTable->pSchema );
58191     sqliteDeleteIndex(pIndex);
58192   }
58193
58194 #ifndef SQLITE_OMIT_FOREIGN_KEY
58195   /* Delete all foreign keys associated with this table.  The keys
58196   ** should have already been unlinked from the pSchema->aFKey hash table 
58197   */
58198   for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
58199     pNextFKey = pFKey->pNextFrom;
58200     assert( sqlite3HashFind(&pTable->pSchema->aFKey,
58201                            pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey );
58202     sqlite3DbFree(db, pFKey);
58203   }
58204 #endif
58205
58206   /* Delete the Table structure itself.
58207   */
58208   sqliteResetColumnNames(pTable);
58209   sqlite3DbFree(db, pTable->zName);
58210   sqlite3DbFree(db, pTable->zColAff);
58211   sqlite3SelectDelete(db, pTable->pSelect);
58212 #ifndef SQLITE_OMIT_CHECK
58213   sqlite3ExprDelete(db, pTable->pCheck);
58214 #endif
58215   sqlite3VtabClear(pTable);
58216   sqlite3DbFree(db, pTable);
58217 }
58218
58219 /*
58220 ** Unlink the given table from the hash tables and the delete the
58221 ** table structure with all its indices and foreign keys.
58222 */
58223 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
58224   Table *p;
58225   FKey *pF1, *pF2;
58226   Db *pDb;
58227
58228   assert( db!=0 );
58229   assert( iDb>=0 && iDb<db->nDb );
58230   assert( zTabName && zTabName[0] );
58231   pDb = &db->aDb[iDb];
58232   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, strlen(zTabName)+1,0);
58233   if( p ){
58234 #ifndef SQLITE_OMIT_FOREIGN_KEY
58235     for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
58236       int nTo = strlen(pF1->zTo) + 1;
58237       pF2 = sqlite3HashFind(&pDb->pSchema->aFKey, pF1->zTo, nTo);
58238       if( pF2==pF1 ){
58239         sqlite3HashInsert(&pDb->pSchema->aFKey, pF1->zTo, nTo, pF1->pNextTo);
58240       }else{
58241         while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
58242         if( pF2 ){
58243           pF2->pNextTo = pF1->pNextTo;
58244         }
58245       }
58246     }
58247 #endif
58248     sqlite3DeleteTable(p);
58249   }
58250   db->flags |= SQLITE_InternChanges;
58251 }
58252
58253 /*
58254 ** Given a token, return a string that consists of the text of that
58255 ** token with any quotations removed.  Space to hold the returned string
58256 ** is obtained from sqliteMalloc() and must be freed by the calling
58257 ** function.
58258 **
58259 ** Tokens are often just pointers into the original SQL text and so
58260 ** are not \000 terminated and are not persistent.  The returned string
58261 ** is \000 terminated and is persistent.
58262 */
58263 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
58264   char *zName;
58265   if( pName ){
58266     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
58267     sqlite3Dequote(zName);
58268   }else{
58269     zName = 0;
58270   }
58271   return zName;
58272 }
58273
58274 /*
58275 ** Open the sqlite_master table stored in database number iDb for
58276 ** writing. The table is opened using cursor 0.
58277 */
58278 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
58279   Vdbe *v = sqlite3GetVdbe(p);
58280   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
58281   sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, 5);/* sqlite_master has 5 columns */
58282   sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
58283 }
58284
58285 /*
58286 ** The token *pName contains the name of a database (either "main" or
58287 ** "temp" or the name of an attached db). This routine returns the
58288 ** index of the named database in db->aDb[], or -1 if the named db 
58289 ** does not exist.
58290 */
58291 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
58292   int i = -1;    /* Database number */
58293   int n;         /* Number of characters in the name */
58294   Db *pDb;       /* A database whose name space is being searched */
58295   char *zName;   /* Name we are searching for */
58296
58297   zName = sqlite3NameFromToken(db, pName);
58298   if( zName ){
58299     n = strlen(zName);
58300     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
58301       if( (!OMIT_TEMPDB || i!=1 ) && n==strlen(pDb->zName) && 
58302           0==sqlite3StrICmp(pDb->zName, zName) ){
58303         break;
58304       }
58305     }
58306     sqlite3DbFree(db, zName);
58307   }
58308   return i;
58309 }
58310
58311 /* The table or view or trigger name is passed to this routine via tokens
58312 ** pName1 and pName2. If the table name was fully qualified, for example:
58313 **
58314 ** CREATE TABLE xxx.yyy (...);
58315 ** 
58316 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
58317 ** the table name is not fully qualified, i.e.:
58318 **
58319 ** CREATE TABLE yyy(...);
58320 **
58321 ** Then pName1 is set to "yyy" and pName2 is "".
58322 **
58323 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
58324 ** pName2) that stores the unqualified table name.  The index of the
58325 ** database "xxx" is returned.
58326 */
58327 SQLITE_PRIVATE int sqlite3TwoPartName(
58328   Parse *pParse,      /* Parsing and code generating context */
58329   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
58330   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
58331   Token **pUnqual     /* Write the unqualified object name here */
58332 ){
58333   int iDb;                    /* Database holding the object */
58334   sqlite3 *db = pParse->db;
58335
58336   if( pName2 && pName2->n>0 ){
58337     assert( !db->init.busy );
58338     *pUnqual = pName2;
58339     iDb = sqlite3FindDb(db, pName1);
58340     if( iDb<0 ){
58341       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
58342       pParse->nErr++;
58343       return -1;
58344     }
58345   }else{
58346     assert( db->init.iDb==0 || db->init.busy );
58347     iDb = db->init.iDb;
58348     *pUnqual = pName1;
58349   }
58350   return iDb;
58351 }
58352
58353 /*
58354 ** This routine is used to check if the UTF-8 string zName is a legal
58355 ** unqualified name for a new schema object (table, index, view or
58356 ** trigger). All names are legal except those that begin with the string
58357 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
58358 ** is reserved for internal use.
58359 */
58360 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
58361   if( !pParse->db->init.busy && pParse->nested==0 
58362           && (pParse->db->flags & SQLITE_WriteSchema)==0
58363           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
58364     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
58365     return SQLITE_ERROR;
58366   }
58367   return SQLITE_OK;
58368 }
58369
58370 /*
58371 ** Begin constructing a new table representation in memory.  This is
58372 ** the first of several action routines that get called in response
58373 ** to a CREATE TABLE statement.  In particular, this routine is called
58374 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
58375 ** flag is true if the table should be stored in the auxiliary database
58376 ** file instead of in the main database file.  This is normally the case
58377 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
58378 ** CREATE and TABLE.
58379 **
58380 ** The new table record is initialized and put in pParse->pNewTable.
58381 ** As more of the CREATE TABLE statement is parsed, additional action
58382 ** routines will be called to add more information to this record.
58383 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
58384 ** is called to complete the construction of the new table record.
58385 */
58386 SQLITE_PRIVATE void sqlite3StartTable(
58387   Parse *pParse,   /* Parser context */
58388   Token *pName1,   /* First part of the name of the table or view */
58389   Token *pName2,   /* Second part of the name of the table or view */
58390   int isTemp,      /* True if this is a TEMP table */
58391   int isView,      /* True if this is a VIEW */
58392   int isVirtual,   /* True if this is a VIRTUAL table */
58393   int noErr        /* Do nothing if table already exists */
58394 ){
58395   Table *pTable;
58396   char *zName = 0; /* The name of the new table */
58397   sqlite3 *db = pParse->db;
58398   Vdbe *v;
58399   int iDb;         /* Database number to create the table in */
58400   Token *pName;    /* Unqualified name of the table to create */
58401
58402   /* The table or view name to create is passed to this routine via tokens
58403   ** pName1 and pName2. If the table name was fully qualified, for example:
58404   **
58405   ** CREATE TABLE xxx.yyy (...);
58406   ** 
58407   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
58408   ** the table name is not fully qualified, i.e.:
58409   **
58410   ** CREATE TABLE yyy(...);
58411   **
58412   ** Then pName1 is set to "yyy" and pName2 is "".
58413   **
58414   ** The call below sets the pName pointer to point at the token (pName1 or
58415   ** pName2) that stores the unqualified table name. The variable iDb is
58416   ** set to the index of the database that the table or view is to be
58417   ** created in.
58418   */
58419   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
58420   if( iDb<0 ) return;
58421   if( !OMIT_TEMPDB && isTemp && iDb>1 ){
58422     /* If creating a temp table, the name may not be qualified */
58423     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
58424     return;
58425   }
58426   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
58427
58428   pParse->sNameToken = *pName;
58429   zName = sqlite3NameFromToken(db, pName);
58430   if( zName==0 ) return;
58431   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
58432     goto begin_table_error;
58433   }
58434   if( db->init.iDb==1 ) isTemp = 1;
58435 #ifndef SQLITE_OMIT_AUTHORIZATION
58436   assert( (isTemp & 1)==isTemp );
58437   {
58438     int code;
58439     char *zDb = db->aDb[iDb].zName;
58440     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
58441       goto begin_table_error;
58442     }
58443     if( isView ){
58444       if( !OMIT_TEMPDB && isTemp ){
58445         code = SQLITE_CREATE_TEMP_VIEW;
58446       }else{
58447         code = SQLITE_CREATE_VIEW;
58448       }
58449     }else{
58450       if( !OMIT_TEMPDB && isTemp ){
58451         code = SQLITE_CREATE_TEMP_TABLE;
58452       }else{
58453         code = SQLITE_CREATE_TABLE;
58454       }
58455     }
58456     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
58457       goto begin_table_error;
58458     }
58459   }
58460 #endif
58461
58462   /* Make sure the new table name does not collide with an existing
58463   ** index or table name in the same database.  Issue an error message if
58464   ** it does. The exception is if the statement being parsed was passed
58465   ** to an sqlite3_declare_vtab() call. In that case only the column names
58466   ** and types will be used, so there is no need to test for namespace
58467   ** collisions.
58468   */
58469   if( !IN_DECLARE_VTAB ){
58470     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
58471       goto begin_table_error;
58472     }
58473     pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
58474     if( pTable ){
58475       if( !noErr ){
58476         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
58477       }
58478       goto begin_table_error;
58479     }
58480     if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
58481       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
58482       goto begin_table_error;
58483     }
58484   }
58485
58486   pTable = sqlite3DbMallocZero(db, sizeof(Table));
58487   if( pTable==0 ){
58488     db->mallocFailed = 1;
58489     pParse->rc = SQLITE_NOMEM;
58490     pParse->nErr++;
58491     goto begin_table_error;
58492   }
58493   pTable->zName = zName;
58494   pTable->iPKey = -1;
58495   pTable->pSchema = db->aDb[iDb].pSchema;
58496   pTable->nRef = 1;
58497   pTable->db = db;
58498   if( pParse->pNewTable ) sqlite3DeleteTable(pParse->pNewTable);
58499   pParse->pNewTable = pTable;
58500
58501   /* If this is the magic sqlite_sequence table used by autoincrement,
58502   ** then record a pointer to this table in the main database structure
58503   ** so that INSERT can find the table easily.
58504   */
58505 #ifndef SQLITE_OMIT_AUTOINCREMENT
58506   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
58507     pTable->pSchema->pSeqTab = pTable;
58508   }
58509 #endif
58510
58511   /* Begin generating the code that will insert the table record into
58512   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
58513   ** and allocate the record number for the table entry now.  Before any
58514   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
58515   ** indices to be created and the table record must come before the 
58516   ** indices.  Hence, the record number for the table must be allocated
58517   ** now.
58518   */
58519   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
58520     int j1;
58521     int fileFormat;
58522     int reg1, reg2, reg3;
58523     sqlite3BeginWriteOperation(pParse, 0, iDb);
58524
58525 #ifndef SQLITE_OMIT_VIRTUALTABLE
58526     if( isVirtual ){
58527       sqlite3VdbeAddOp0(v, OP_VBegin);
58528     }
58529 #endif
58530
58531     /* If the file format and encoding in the database have not been set, 
58532     ** set them now.
58533     */
58534     reg1 = pParse->regRowid = ++pParse->nMem;
58535     reg2 = pParse->regRoot = ++pParse->nMem;
58536     reg3 = ++pParse->nMem;
58537     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, 1);   /* file_format */
58538     sqlite3VdbeUsesBtree(v, iDb);
58539     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
58540     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
58541                   1 : SQLITE_MAX_FILE_FORMAT;
58542     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
58543     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, reg3);
58544     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
58545     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 4, reg3);
58546     sqlite3VdbeJumpHere(v, j1);
58547
58548     /* This just creates a place-holder record in the sqlite_master table.
58549     ** The record created does not contain anything yet.  It will be replaced
58550     ** by the real entry in code generated at sqlite3EndTable().
58551     **
58552     ** The rowid for the new entry is left on the top of the stack.
58553     ** The rowid value is needed by the code that sqlite3EndTable will
58554     ** generate.
58555     */
58556 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
58557     if( isView || isVirtual ){
58558       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
58559     }else
58560 #endif
58561     {
58562       sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
58563     }
58564     sqlite3OpenMasterTable(pParse, iDb);
58565     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
58566     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
58567     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
58568     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
58569     sqlite3VdbeAddOp0(v, OP_Close);
58570   }
58571
58572   /* Normal (non-error) return. */
58573   return;
58574
58575   /* If an error occurs, we jump here */
58576 begin_table_error:
58577   sqlite3DbFree(db, zName);
58578   return;
58579 }
58580
58581 /*
58582 ** This macro is used to compare two strings in a case-insensitive manner.
58583 ** It is slightly faster than calling sqlite3StrICmp() directly, but
58584 ** produces larger code.
58585 **
58586 ** WARNING: This macro is not compatible with the strcmp() family. It
58587 ** returns true if the two strings are equal, otherwise false.
58588 */
58589 #define STRICMP(x, y) (\
58590 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
58591 sqlite3UpperToLower[*(unsigned char *)(y)]     \
58592 && sqlite3StrICmp((x)+1,(y)+1)==0 )
58593
58594 /*
58595 ** Add a new column to the table currently being constructed.
58596 **
58597 ** The parser calls this routine once for each column declaration
58598 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
58599 ** first to get things going.  Then this routine is called for each
58600 ** column.
58601 */
58602 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
58603   Table *p;
58604   int i;
58605   char *z;
58606   Column *pCol;
58607   sqlite3 *db = pParse->db;
58608   if( (p = pParse->pNewTable)==0 ) return;
58609 #if SQLITE_MAX_COLUMN
58610   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
58611     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
58612     return;
58613   }
58614 #endif
58615   z = sqlite3NameFromToken(pParse->db, pName);
58616   if( z==0 ) return;
58617   for(i=0; i<p->nCol; i++){
58618     if( STRICMP(z, p->aCol[i].zName) ){
58619       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
58620       sqlite3DbFree(db, z);
58621       return;
58622     }
58623   }
58624   if( (p->nCol & 0x7)==0 ){
58625     Column *aNew;
58626     aNew = sqlite3DbRealloc(pParse->db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
58627     if( aNew==0 ){
58628       sqlite3DbFree(db, z);
58629       return;
58630     }
58631     p->aCol = aNew;
58632   }
58633   pCol = &p->aCol[p->nCol];
58634   memset(pCol, 0, sizeof(p->aCol[0]));
58635   pCol->zName = z;
58636  
58637   /* If there is no type specified, columns have the default affinity
58638   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
58639   ** be called next to set pCol->affinity correctly.
58640   */
58641   pCol->affinity = SQLITE_AFF_NONE;
58642   p->nCol++;
58643 }
58644
58645 /*
58646 ** This routine is called by the parser while in the middle of
58647 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
58648 ** been seen on a column.  This routine sets the notNull flag on
58649 ** the column currently under construction.
58650 */
58651 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
58652   Table *p;
58653   int i;
58654   if( (p = pParse->pNewTable)==0 ) return;
58655   i = p->nCol-1;
58656   if( i>=0 ) p->aCol[i].notNull = onError;
58657 }
58658
58659 /*
58660 ** Scan the column type name zType (length nType) and return the
58661 ** associated affinity type.
58662 **
58663 ** This routine does a case-independent search of zType for the 
58664 ** substrings in the following table. If one of the substrings is
58665 ** found, the corresponding affinity is returned. If zType contains
58666 ** more than one of the substrings, entries toward the top of 
58667 ** the table take priority. For example, if zType is 'BLOBINT', 
58668 ** SQLITE_AFF_INTEGER is returned.
58669 **
58670 ** Substring     | Affinity
58671 ** --------------------------------
58672 ** 'INT'         | SQLITE_AFF_INTEGER
58673 ** 'CHAR'        | SQLITE_AFF_TEXT
58674 ** 'CLOB'        | SQLITE_AFF_TEXT
58675 ** 'TEXT'        | SQLITE_AFF_TEXT
58676 ** 'BLOB'        | SQLITE_AFF_NONE
58677 ** 'REAL'        | SQLITE_AFF_REAL
58678 ** 'FLOA'        | SQLITE_AFF_REAL
58679 ** 'DOUB'        | SQLITE_AFF_REAL
58680 **
58681 ** If none of the substrings in the above table are found,
58682 ** SQLITE_AFF_NUMERIC is returned.
58683 */
58684 SQLITE_PRIVATE char sqlite3AffinityType(const Token *pType){
58685   u32 h = 0;
58686   char aff = SQLITE_AFF_NUMERIC;
58687   const unsigned char *zIn = pType->z;
58688   const unsigned char *zEnd = &pType->z[pType->n];
58689
58690   while( zIn!=zEnd ){
58691     h = (h<<8) + sqlite3UpperToLower[*zIn];
58692     zIn++;
58693     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
58694       aff = SQLITE_AFF_TEXT; 
58695     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
58696       aff = SQLITE_AFF_TEXT;
58697     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
58698       aff = SQLITE_AFF_TEXT;
58699     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
58700         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
58701       aff = SQLITE_AFF_NONE;
58702 #ifndef SQLITE_OMIT_FLOATING_POINT
58703     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
58704         && aff==SQLITE_AFF_NUMERIC ){
58705       aff = SQLITE_AFF_REAL;
58706     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
58707         && aff==SQLITE_AFF_NUMERIC ){
58708       aff = SQLITE_AFF_REAL;
58709     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
58710         && aff==SQLITE_AFF_NUMERIC ){
58711       aff = SQLITE_AFF_REAL;
58712 #endif
58713     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
58714       aff = SQLITE_AFF_INTEGER;
58715       break;
58716     }
58717   }
58718
58719   return aff;
58720 }
58721
58722 /*
58723 ** This routine is called by the parser while in the middle of
58724 ** parsing a CREATE TABLE statement.  The pFirst token is the first
58725 ** token in the sequence of tokens that describe the type of the
58726 ** column currently under construction.   pLast is the last token
58727 ** in the sequence.  Use this information to construct a string
58728 ** that contains the typename of the column and store that string
58729 ** in zType.
58730 */ 
58731 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
58732   Table *p;
58733   int i;
58734   Column *pCol;
58735   sqlite3 *db;
58736
58737   if( (p = pParse->pNewTable)==0 ) return;
58738   i = p->nCol-1;
58739   if( i<0 ) return;
58740   pCol = &p->aCol[i];
58741   db = pParse->db;
58742   sqlite3DbFree(db, pCol->zType);
58743   pCol->zType = sqlite3NameFromToken(db, pType);
58744   pCol->affinity = sqlite3AffinityType(pType);
58745 }
58746
58747 /*
58748 ** The expression is the default value for the most recently added column
58749 ** of the table currently under construction.
58750 **
58751 ** Default value expressions must be constant.  Raise an exception if this
58752 ** is not the case.
58753 **
58754 ** This routine is called by the parser while in the middle of
58755 ** parsing a CREATE TABLE statement.
58756 */
58757 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){
58758   Table *p;
58759   Column *pCol;
58760   sqlite3 *db = pParse->db;
58761   if( (p = pParse->pNewTable)!=0 ){
58762     pCol = &(p->aCol[p->nCol-1]);
58763     if( !sqlite3ExprIsConstantOrFunction(pExpr) ){
58764       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
58765           pCol->zName);
58766     }else{
58767       Expr *pCopy;
58768       sqlite3ExprDelete(db, pCol->pDflt);
58769       pCol->pDflt = pCopy = sqlite3ExprDup(db, pExpr);
58770       if( pCopy ){
58771         sqlite3TokenCopy(db, &pCopy->span, &pExpr->span);
58772       }
58773     }
58774   }
58775   sqlite3ExprDelete(db, pExpr);
58776 }
58777
58778 /*
58779 ** Designate the PRIMARY KEY for the table.  pList is a list of names 
58780 ** of columns that form the primary key.  If pList is NULL, then the
58781 ** most recently added column of the table is the primary key.
58782 **
58783 ** A table can have at most one primary key.  If the table already has
58784 ** a primary key (and this is the second primary key) then create an
58785 ** error.
58786 **
58787 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
58788 ** then we will try to use that column as the rowid.  Set the Table.iPKey
58789 ** field of the table under construction to be the index of the
58790 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
58791 ** no INTEGER PRIMARY KEY.
58792 **
58793 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
58794 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
58795 */
58796 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
58797   Parse *pParse,    /* Parsing context */
58798   ExprList *pList,  /* List of field names to be indexed */
58799   int onError,      /* What to do with a uniqueness conflict */
58800   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
58801   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
58802 ){
58803   Table *pTab = pParse->pNewTable;
58804   char *zType = 0;
58805   int iCol = -1, i;
58806   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
58807   if( pTab->tabFlags & TF_HasPrimaryKey ){
58808     sqlite3ErrorMsg(pParse, 
58809       "table \"%s\" has more than one primary key", pTab->zName);
58810     goto primary_key_exit;
58811   }
58812   pTab->tabFlags |= TF_HasPrimaryKey;
58813   if( pList==0 ){
58814     iCol = pTab->nCol - 1;
58815     pTab->aCol[iCol].isPrimKey = 1;
58816   }else{
58817     for(i=0; i<pList->nExpr; i++){
58818       for(iCol=0; iCol<pTab->nCol; iCol++){
58819         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
58820           break;
58821         }
58822       }
58823       if( iCol<pTab->nCol ){
58824         pTab->aCol[iCol].isPrimKey = 1;
58825       }
58826     }
58827     if( pList->nExpr>1 ) iCol = -1;
58828   }
58829   if( iCol>=0 && iCol<pTab->nCol ){
58830     zType = pTab->aCol[iCol].zType;
58831   }
58832   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
58833         && sortOrder==SQLITE_SO_ASC ){
58834     pTab->iPKey = iCol;
58835     pTab->keyConf = onError;
58836     assert( autoInc==0 || autoInc==1 );
58837     pTab->tabFlags |= autoInc*TF_Autoincrement;
58838   }else if( autoInc ){
58839 #ifndef SQLITE_OMIT_AUTOINCREMENT
58840     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
58841        "INTEGER PRIMARY KEY");
58842 #endif
58843   }else{
58844     sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
58845     pList = 0;
58846   }
58847
58848 primary_key_exit:
58849   sqlite3ExprListDelete(pParse->db, pList);
58850   return;
58851 }
58852
58853 /*
58854 ** Add a new CHECK constraint to the table currently under construction.
58855 */
58856 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
58857   Parse *pParse,    /* Parsing context */
58858   Expr *pCheckExpr  /* The check expression */
58859 ){
58860   sqlite3 *db = pParse->db;
58861 #ifndef SQLITE_OMIT_CHECK
58862   Table *pTab = pParse->pNewTable;
58863   if( pTab && !IN_DECLARE_VTAB ){
58864     /* The CHECK expression must be duplicated so that tokens refer
58865     ** to malloced space and not the (ephemeral) text of the CREATE TABLE
58866     ** statement */
58867     pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, 
58868                                   sqlite3ExprDup(db, pCheckExpr));
58869   }
58870 #endif
58871   sqlite3ExprDelete(db, pCheckExpr);
58872 }
58873
58874 /*
58875 ** Set the collation function of the most recently parsed table column
58876 ** to the CollSeq given.
58877 */
58878 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
58879   Table *p;
58880   int i;
58881   char *zColl;              /* Dequoted name of collation sequence */
58882   sqlite3 *db;
58883
58884   if( (p = pParse->pNewTable)==0 ) return;
58885   i = p->nCol-1;
58886   db = pParse->db;
58887   zColl = sqlite3NameFromToken(db, pToken);
58888   if( !zColl ) return;
58889
58890   if( sqlite3LocateCollSeq(pParse, zColl, -1) ){
58891     Index *pIdx;
58892     p->aCol[i].zColl = zColl;
58893   
58894     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
58895     ** then an index may have been created on this column before the
58896     ** collation type was added. Correct this if it is the case.
58897     */
58898     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
58899       assert( pIdx->nColumn==1 );
58900       if( pIdx->aiColumn[0]==i ){
58901         pIdx->azColl[0] = p->aCol[i].zColl;
58902       }
58903     }
58904   }else{
58905     sqlite3DbFree(db, zColl);
58906   }
58907 }
58908
58909 /*
58910 ** This function returns the collation sequence for database native text
58911 ** encoding identified by the string zName, length nName.
58912 **
58913 ** If the requested collation sequence is not available, or not available
58914 ** in the database native encoding, the collation factory is invoked to
58915 ** request it. If the collation factory does not supply such a sequence,
58916 ** and the sequence is available in another text encoding, then that is
58917 ** returned instead.
58918 **
58919 ** If no versions of the requested collations sequence are available, or
58920 ** another error occurs, NULL is returned and an error message written into
58921 ** pParse.
58922 **
58923 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
58924 ** invokes the collation factory if the named collation cannot be found
58925 ** and generates an error message.
58926 */
58927 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
58928   sqlite3 *db = pParse->db;
58929   u8 enc = ENC(db);
58930   u8 initbusy = db->init.busy;
58931   CollSeq *pColl;
58932
58933   pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
58934   if( !initbusy && (!pColl || !pColl->xCmp) ){
58935     pColl = sqlite3GetCollSeq(db, pColl, zName, nName);
58936     if( !pColl ){
58937       if( nName<0 ){
58938         nName = sqlite3Strlen(db, zName);
58939       }
58940       sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName);
58941       pColl = 0;
58942     }
58943   }
58944
58945   return pColl;
58946 }
58947
58948
58949 /*
58950 ** Generate code that will increment the schema cookie.
58951 **
58952 ** The schema cookie is used to determine when the schema for the
58953 ** database changes.  After each schema change, the cookie value
58954 ** changes.  When a process first reads the schema it records the
58955 ** cookie.  Thereafter, whenever it goes to access the database,
58956 ** it checks the cookie to make sure the schema has not changed
58957 ** since it was last read.
58958 **
58959 ** This plan is not completely bullet-proof.  It is possible for
58960 ** the schema to change multiple times and for the cookie to be
58961 ** set back to prior value.  But schema changes are infrequent
58962 ** and the probability of hitting the same cookie value is only
58963 ** 1 chance in 2^32.  So we're safe enough.
58964 */
58965 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
58966   int r1 = sqlite3GetTempReg(pParse);
58967   sqlite3 *db = pParse->db;
58968   Vdbe *v = pParse->pVdbe;
58969   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
58970   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 0, r1);
58971   sqlite3ReleaseTempReg(pParse, r1);
58972 }
58973
58974 /*
58975 ** Measure the number of characters needed to output the given
58976 ** identifier.  The number returned includes any quotes used
58977 ** but does not include the null terminator.
58978 **
58979 ** The estimate is conservative.  It might be larger that what is
58980 ** really needed.
58981 */
58982 static int identLength(const char *z){
58983   int n;
58984   for(n=0; *z; n++, z++){
58985     if( *z=='"' ){ n++; }
58986   }
58987   return n + 2;
58988 }
58989
58990 /*
58991 ** Write an identifier onto the end of the given string.  Add
58992 ** quote characters as needed.
58993 */
58994 static void identPut(char *z, int *pIdx, char *zSignedIdent){
58995   unsigned char *zIdent = (unsigned char*)zSignedIdent;
58996   int i, j, needQuote;
58997   i = *pIdx;
58998   for(j=0; zIdent[j]; j++){
58999     if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
59000   }
59001   needQuote =  zIdent[j]!=0 || isdigit(zIdent[0])
59002                   || sqlite3KeywordCode(zIdent, j)!=TK_ID;
59003   if( needQuote ) z[i++] = '"';
59004   for(j=0; zIdent[j]; j++){
59005     z[i++] = zIdent[j];
59006     if( zIdent[j]=='"' ) z[i++] = '"';
59007   }
59008   if( needQuote ) z[i++] = '"';
59009   z[i] = 0;
59010   *pIdx = i;
59011 }
59012
59013 /*
59014 ** Generate a CREATE TABLE statement appropriate for the given
59015 ** table.  Memory to hold the text of the statement is obtained
59016 ** from sqliteMalloc() and must be freed by the calling function.
59017 */
59018 static char *createTableStmt(sqlite3 *db, Table *p, int isTemp){
59019   int i, k, n;
59020   char *zStmt;
59021   char *zSep, *zSep2, *zEnd, *z;
59022   Column *pCol;
59023   n = 0;
59024   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
59025     n += identLength(pCol->zName);
59026     z = pCol->zType;
59027     if( z ){
59028       n += (strlen(z) + 1);
59029     }
59030   }
59031   n += identLength(p->zName);
59032   if( n<50 ){
59033     zSep = "";
59034     zSep2 = ",";
59035     zEnd = ")";
59036   }else{
59037     zSep = "\n  ";
59038     zSep2 = ",\n  ";
59039     zEnd = "\n)";
59040   }
59041   n += 35 + 6*p->nCol;
59042   zStmt = sqlite3Malloc( n );
59043   if( zStmt==0 ){
59044     db->mallocFailed = 1;
59045     return 0;
59046   }
59047   sqlite3_snprintf(n, zStmt,
59048                   !OMIT_TEMPDB&&isTemp ? "CREATE TEMP TABLE ":"CREATE TABLE ");
59049   k = strlen(zStmt);
59050   identPut(zStmt, &k, p->zName);
59051   zStmt[k++] = '(';
59052   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
59053     sqlite3_snprintf(n-k, &zStmt[k], zSep);
59054     k += strlen(&zStmt[k]);
59055     zSep = zSep2;
59056     identPut(zStmt, &k, pCol->zName);
59057     if( (z = pCol->zType)!=0 ){
59058       zStmt[k++] = ' ';
59059       assert( strlen(z)+k+1<=n );
59060       sqlite3_snprintf(n-k, &zStmt[k], "%s", z);
59061       k += strlen(z);
59062     }
59063   }
59064   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
59065   return zStmt;
59066 }
59067
59068 /*
59069 ** This routine is called to report the final ")" that terminates
59070 ** a CREATE TABLE statement.
59071 **
59072 ** The table structure that other action routines have been building
59073 ** is added to the internal hash tables, assuming no errors have
59074 ** occurred.
59075 **
59076 ** An entry for the table is made in the master table on disk, unless
59077 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
59078 ** it means we are reading the sqlite_master table because we just
59079 ** connected to the database or because the sqlite_master table has
59080 ** recently changed, so the entry for this table already exists in
59081 ** the sqlite_master table.  We do not want to create it again.
59082 **
59083 ** If the pSelect argument is not NULL, it means that this routine
59084 ** was called to create a table generated from a 
59085 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
59086 ** the new table will match the result set of the SELECT.
59087 */
59088 SQLITE_PRIVATE void sqlite3EndTable(
59089   Parse *pParse,          /* Parse context */
59090   Token *pCons,           /* The ',' token after the last column defn. */
59091   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
59092   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
59093 ){
59094   Table *p;
59095   sqlite3 *db = pParse->db;
59096   int iDb;
59097
59098   if( (pEnd==0 && pSelect==0) || pParse->nErr || db->mallocFailed ) {
59099     return;
59100   }
59101   p = pParse->pNewTable;
59102   if( p==0 ) return;
59103
59104   assert( !db->init.busy || !pSelect );
59105
59106   iDb = sqlite3SchemaToIndex(db, p->pSchema);
59107
59108 #ifndef SQLITE_OMIT_CHECK
59109   /* Resolve names in all CHECK constraint expressions.
59110   */
59111   if( p->pCheck ){
59112     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
59113     NameContext sNC;                /* Name context for pParse->pNewTable */
59114
59115     memset(&sNC, 0, sizeof(sNC));
59116     memset(&sSrc, 0, sizeof(sSrc));
59117     sSrc.nSrc = 1;
59118     sSrc.a[0].zName = p->zName;
59119     sSrc.a[0].pTab = p;
59120     sSrc.a[0].iCursor = -1;
59121     sNC.pParse = pParse;
59122     sNC.pSrcList = &sSrc;
59123     sNC.isCheck = 1;
59124     if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
59125       return;
59126     }
59127   }
59128 #endif /* !defined(SQLITE_OMIT_CHECK) */
59129
59130   /* If the db->init.busy is 1 it means we are reading the SQL off the
59131   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
59132   ** So do not write to the disk again.  Extract the root page number
59133   ** for the table from the db->init.newTnum field.  (The page number
59134   ** should have been put there by the sqliteOpenCb routine.)
59135   */
59136   if( db->init.busy ){
59137     p->tnum = db->init.newTnum;
59138   }
59139
59140   /* If not initializing, then create a record for the new table
59141   ** in the SQLITE_MASTER table of the database.  The record number
59142   ** for the new table entry should already be on the stack.
59143   **
59144   ** If this is a TEMPORARY table, write the entry into the auxiliary
59145   ** file instead of into the main database file.
59146   */
59147   if( !db->init.busy ){
59148     int n;
59149     Vdbe *v;
59150     char *zType;    /* "view" or "table" */
59151     char *zType2;   /* "VIEW" or "TABLE" */
59152     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
59153
59154     v = sqlite3GetVdbe(pParse);
59155     if( v==0 ) return;
59156
59157     sqlite3VdbeAddOp1(v, OP_Close, 0);
59158
59159     /* Create the rootpage for the new table and push it onto the stack.
59160     ** A view has no rootpage, so just push a zero onto the stack for
59161     ** views.  Initialize zType at the same time.
59162     */
59163     if( p->pSelect==0 ){
59164       /* A regular table */
59165       zType = "table";
59166       zType2 = "TABLE";
59167 #ifndef SQLITE_OMIT_VIEW
59168     }else{
59169       /* A view */
59170       zType = "view";
59171       zType2 = "VIEW";
59172 #endif
59173     }
59174
59175     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
59176     ** statement to populate the new table. The root-page number for the
59177     ** new table is on the top of the vdbe stack.
59178     **
59179     ** Once the SELECT has been coded by sqlite3Select(), it is in a
59180     ** suitable state to query for the column names and types to be used
59181     ** by the new table.
59182     **
59183     ** A shared-cache write-lock is not required to write to the new table,
59184     ** as a schema-lock must have already been obtained to create it. Since
59185     ** a schema-lock excludes all other database users, the write-lock would
59186     ** be redundant.
59187     */
59188     if( pSelect ){
59189       SelectDest dest;
59190       Table *pSelTab;
59191
59192       assert(pParse->nTab==0);
59193       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
59194       sqlite3VdbeChangeP5(v, 1);
59195       pParse->nTab = 2;
59196       sqlite3SelectDestInit(&dest, SRT_Table, 1);
59197       sqlite3Select(pParse, pSelect, &dest);
59198       sqlite3VdbeAddOp1(v, OP_Close, 1);
59199       if( pParse->nErr==0 ){
59200         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
59201         if( pSelTab==0 ) return;
59202         assert( p->aCol==0 );
59203         p->nCol = pSelTab->nCol;
59204         p->aCol = pSelTab->aCol;
59205         pSelTab->nCol = 0;
59206         pSelTab->aCol = 0;
59207         sqlite3DeleteTable(pSelTab);
59208       }
59209     }
59210
59211     /* Compute the complete text of the CREATE statement */
59212     if( pSelect ){
59213       zStmt = createTableStmt(db, p, p->pSchema==db->aDb[1].pSchema);
59214     }else{
59215       n = pEnd->z - pParse->sNameToken.z + 1;
59216       zStmt = sqlite3MPrintf(db, 
59217           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
59218       );
59219     }
59220
59221     /* A slot for the record has already been allocated in the 
59222     ** SQLITE_MASTER table.  We just need to update that slot with all
59223     ** the information we've collected.  The rowid for the preallocated
59224     ** slot is the 2nd item on the stack.  The top of the stack is the
59225     ** root page for the new table (or a 0 if this is a view).
59226     */
59227     sqlite3NestedParse(pParse,
59228       "UPDATE %Q.%s "
59229          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
59230        "WHERE rowid=#%d",
59231       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
59232       zType,
59233       p->zName,
59234       p->zName,
59235       pParse->regRoot,
59236       zStmt,
59237       pParse->regRowid
59238     );
59239     sqlite3DbFree(db, zStmt);
59240     sqlite3ChangeCookie(pParse, iDb);
59241
59242 #ifndef SQLITE_OMIT_AUTOINCREMENT
59243     /* Check to see if we need to create an sqlite_sequence table for
59244     ** keeping track of autoincrement keys.
59245     */
59246     if( p->tabFlags & TF_Autoincrement ){
59247       Db *pDb = &db->aDb[iDb];
59248       if( pDb->pSchema->pSeqTab==0 ){
59249         sqlite3NestedParse(pParse,
59250           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
59251           pDb->zName
59252         );
59253       }
59254     }
59255 #endif
59256
59257     /* Reparse everything to update our internal data structures */
59258     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
59259         sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
59260   }
59261
59262
59263   /* Add the table to the in-memory representation of the database.
59264   */
59265   if( db->init.busy && pParse->nErr==0 ){
59266     Table *pOld;
59267     FKey *pFKey; 
59268     Schema *pSchema = p->pSchema;
59269     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, strlen(p->zName)+1,p);
59270     if( pOld ){
59271       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
59272       db->mallocFailed = 1;
59273       return;
59274     }
59275 #ifndef SQLITE_OMIT_FOREIGN_KEY
59276     for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
59277       void *data;
59278       int nTo = strlen(pFKey->zTo) + 1;
59279       pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo);
59280       data = sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey);
59281       if( data==(void *)pFKey ){
59282         db->mallocFailed = 1;
59283       }
59284     }
59285 #endif
59286     pParse->pNewTable = 0;
59287     db->nTable++;
59288     db->flags |= SQLITE_InternChanges;
59289
59290 #ifndef SQLITE_OMIT_ALTERTABLE
59291     if( !p->pSelect ){
59292       const char *zName = (const char *)pParse->sNameToken.z;
59293       int nName;
59294       assert( !pSelect && pCons && pEnd );
59295       if( pCons->z==0 ){
59296         pCons = pEnd;
59297       }
59298       nName = (const char *)pCons->z - zName;
59299       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
59300     }
59301 #endif
59302   }
59303 }
59304
59305 #ifndef SQLITE_OMIT_VIEW
59306 /*
59307 ** The parser calls this routine in order to create a new VIEW
59308 */
59309 SQLITE_PRIVATE void sqlite3CreateView(
59310   Parse *pParse,     /* The parsing context */
59311   Token *pBegin,     /* The CREATE token that begins the statement */
59312   Token *pName1,     /* The token that holds the name of the view */
59313   Token *pName2,     /* The token that holds the name of the view */
59314   Select *pSelect,   /* A SELECT statement that will become the new view */
59315   int isTemp,        /* TRUE for a TEMPORARY view */
59316   int noErr          /* Suppress error messages if VIEW already exists */
59317 ){
59318   Table *p;
59319   int n;
59320   const unsigned char *z;
59321   Token sEnd;
59322   DbFixer sFix;
59323   Token *pName;
59324   int iDb;
59325   sqlite3 *db = pParse->db;
59326
59327   if( pParse->nVar>0 ){
59328     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
59329     sqlite3SelectDelete(db, pSelect);
59330     return;
59331   }
59332   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
59333   p = pParse->pNewTable;
59334   if( p==0 || pParse->nErr ){
59335     sqlite3SelectDelete(db, pSelect);
59336     return;
59337   }
59338   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
59339   iDb = sqlite3SchemaToIndex(db, p->pSchema);
59340   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
59341     && sqlite3FixSelect(&sFix, pSelect)
59342   ){
59343     sqlite3SelectDelete(db, pSelect);
59344     return;
59345   }
59346
59347   /* Make a copy of the entire SELECT statement that defines the view.
59348   ** This will force all the Expr.token.z values to be dynamically
59349   ** allocated rather than point to the input string - which means that
59350   ** they will persist after the current sqlite3_exec() call returns.
59351   */
59352   p->pSelect = sqlite3SelectDup(db, pSelect);
59353   sqlite3SelectDelete(db, pSelect);
59354   if( db->mallocFailed ){
59355     return;
59356   }
59357   if( !db->init.busy ){
59358     sqlite3ViewGetColumnNames(pParse, p);
59359   }
59360
59361   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
59362   ** the end.
59363   */
59364   sEnd = pParse->sLastToken;
59365   if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
59366     sEnd.z += sEnd.n;
59367   }
59368   sEnd.n = 0;
59369   n = sEnd.z - pBegin->z;
59370   z = (const unsigned char*)pBegin->z;
59371   while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
59372   sEnd.z = &z[n-1];
59373   sEnd.n = 1;
59374
59375   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
59376   sqlite3EndTable(pParse, 0, &sEnd, 0);
59377   return;
59378 }
59379 #endif /* SQLITE_OMIT_VIEW */
59380
59381 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
59382 /*
59383 ** The Table structure pTable is really a VIEW.  Fill in the names of
59384 ** the columns of the view in the pTable structure.  Return the number
59385 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
59386 */
59387 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
59388   Table *pSelTab;   /* A fake table from which we get the result set */
59389   Select *pSel;     /* Copy of the SELECT that implements the view */
59390   int nErr = 0;     /* Number of errors encountered */
59391   int n;            /* Temporarily holds the number of cursors assigned */
59392   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
59393   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
59394
59395   assert( pTable );
59396
59397 #ifndef SQLITE_OMIT_VIRTUALTABLE
59398   if( sqlite3VtabCallConnect(pParse, pTable) ){
59399     return SQLITE_ERROR;
59400   }
59401   if( IsVirtual(pTable) ) return 0;
59402 #endif
59403
59404 #ifndef SQLITE_OMIT_VIEW
59405   /* A positive nCol means the columns names for this view are
59406   ** already known.
59407   */
59408   if( pTable->nCol>0 ) return 0;
59409
59410   /* A negative nCol is a special marker meaning that we are currently
59411   ** trying to compute the column names.  If we enter this routine with
59412   ** a negative nCol, it means two or more views form a loop, like this:
59413   **
59414   **     CREATE VIEW one AS SELECT * FROM two;
59415   **     CREATE VIEW two AS SELECT * FROM one;
59416   **
59417   ** Actually, this error is caught previously and so the following test
59418   ** should always fail.  But we will leave it in place just to be safe.
59419   */
59420   if( pTable->nCol<0 ){
59421     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
59422     return 1;
59423   }
59424   assert( pTable->nCol>=0 );
59425
59426   /* If we get this far, it means we need to compute the table names.
59427   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
59428   ** "*" elements in the results set of the view and will assign cursors
59429   ** to the elements of the FROM clause.  But we do not want these changes
59430   ** to be permanent.  So the computation is done on a copy of the SELECT
59431   ** statement that defines the view.
59432   */
59433   assert( pTable->pSelect );
59434   pSel = sqlite3SelectDup(db, pTable->pSelect);
59435   if( pSel ){
59436     n = pParse->nTab;
59437     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
59438     pTable->nCol = -1;
59439 #ifndef SQLITE_OMIT_AUTHORIZATION
59440     xAuth = db->xAuth;
59441     db->xAuth = 0;
59442     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
59443     db->xAuth = xAuth;
59444 #else
59445     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
59446 #endif
59447     pParse->nTab = n;
59448     if( pSelTab ){
59449       assert( pTable->aCol==0 );
59450       pTable->nCol = pSelTab->nCol;
59451       pTable->aCol = pSelTab->aCol;
59452       pSelTab->nCol = 0;
59453       pSelTab->aCol = 0;
59454       sqlite3DeleteTable(pSelTab);
59455       pTable->pSchema->flags |= DB_UnresetViews;
59456     }else{
59457       pTable->nCol = 0;
59458       nErr++;
59459     }
59460     sqlite3SelectDelete(db, pSel);
59461   } else {
59462     nErr++;
59463   }
59464 #endif /* SQLITE_OMIT_VIEW */
59465   return nErr;  
59466 }
59467 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
59468
59469 #ifndef SQLITE_OMIT_VIEW
59470 /*
59471 ** Clear the column names from every VIEW in database idx.
59472 */
59473 static void sqliteViewResetAll(sqlite3 *db, int idx){
59474   HashElem *i;
59475   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
59476   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
59477     Table *pTab = sqliteHashData(i);
59478     if( pTab->pSelect ){
59479       sqliteResetColumnNames(pTab);
59480     }
59481   }
59482   DbClearProperty(db, idx, DB_UnresetViews);
59483 }
59484 #else
59485 # define sqliteViewResetAll(A,B)
59486 #endif /* SQLITE_OMIT_VIEW */
59487
59488 /*
59489 ** This function is called by the VDBE to adjust the internal schema
59490 ** used by SQLite when the btree layer moves a table root page. The
59491 ** root-page of a table or index in database iDb has changed from iFrom
59492 ** to iTo.
59493 **
59494 ** Ticket #1728:  The symbol table might still contain information
59495 ** on tables and/or indices that are the process of being deleted.
59496 ** If you are unlucky, one of those deleted indices or tables might
59497 ** have the same rootpage number as the real table or index that is
59498 ** being moved.  So we cannot stop searching after the first match 
59499 ** because the first match might be for one of the deleted indices
59500 ** or tables and not the table/index that is actually being moved.
59501 ** We must continue looping until all tables and indices with
59502 ** rootpage==iFrom have been converted to have a rootpage of iTo
59503 ** in order to be certain that we got the right one.
59504 */
59505 #ifndef SQLITE_OMIT_AUTOVACUUM
59506 SQLITE_PRIVATE void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
59507   HashElem *pElem;
59508   Hash *pHash;
59509
59510   pHash = &pDb->pSchema->tblHash;
59511   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
59512     Table *pTab = sqliteHashData(pElem);
59513     if( pTab->tnum==iFrom ){
59514       pTab->tnum = iTo;
59515     }
59516   }
59517   pHash = &pDb->pSchema->idxHash;
59518   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
59519     Index *pIdx = sqliteHashData(pElem);
59520     if( pIdx->tnum==iFrom ){
59521       pIdx->tnum = iTo;
59522     }
59523   }
59524 }
59525 #endif
59526
59527 /*
59528 ** Write code to erase the table with root-page iTable from database iDb.
59529 ** Also write code to modify the sqlite_master table and internal schema
59530 ** if a root-page of another table is moved by the btree-layer whilst
59531 ** erasing iTable (this can happen with an auto-vacuum database).
59532 */ 
59533 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
59534   Vdbe *v = sqlite3GetVdbe(pParse);
59535   int r1 = sqlite3GetTempReg(pParse);
59536   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
59537 #ifndef SQLITE_OMIT_AUTOVACUUM
59538   /* OP_Destroy stores an in integer r1. If this integer
59539   ** is non-zero, then it is the root page number of a table moved to
59540   ** location iTable. The following code modifies the sqlite_master table to
59541   ** reflect this.
59542   **
59543   ** The "#%d" in the SQL is a special constant that means whatever value
59544   ** is on the top of the stack.  See sqlite3RegisterExpr().
59545   */
59546   sqlite3NestedParse(pParse, 
59547      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
59548      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
59549 #endif
59550   sqlite3ReleaseTempReg(pParse, r1);
59551 }
59552
59553 /*
59554 ** Write VDBE code to erase table pTab and all associated indices on disk.
59555 ** Code to update the sqlite_master tables and internal schema definitions
59556 ** in case a root-page belonging to another table is moved by the btree layer
59557 ** is also added (this can happen with an auto-vacuum database).
59558 */
59559 static void destroyTable(Parse *pParse, Table *pTab){
59560 #ifdef SQLITE_OMIT_AUTOVACUUM
59561   Index *pIdx;
59562   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
59563   destroyRootPage(pParse, pTab->tnum, iDb);
59564   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
59565     destroyRootPage(pParse, pIdx->tnum, iDb);
59566   }
59567 #else
59568   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
59569   ** is not defined), then it is important to call OP_Destroy on the
59570   ** table and index root-pages in order, starting with the numerically 
59571   ** largest root-page number. This guarantees that none of the root-pages
59572   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
59573   ** following were coded:
59574   **
59575   ** OP_Destroy 4 0
59576   ** ...
59577   ** OP_Destroy 5 0
59578   **
59579   ** and root page 5 happened to be the largest root-page number in the
59580   ** database, then root page 5 would be moved to page 4 by the 
59581   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
59582   ** a free-list page.
59583   */
59584   int iTab = pTab->tnum;
59585   int iDestroyed = 0;
59586
59587   while( 1 ){
59588     Index *pIdx;
59589     int iLargest = 0;
59590
59591     if( iDestroyed==0 || iTab<iDestroyed ){
59592       iLargest = iTab;
59593     }
59594     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
59595       int iIdx = pIdx->tnum;
59596       assert( pIdx->pSchema==pTab->pSchema );
59597       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
59598         iLargest = iIdx;
59599       }
59600     }
59601     if( iLargest==0 ){
59602       return;
59603     }else{
59604       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
59605       destroyRootPage(pParse, iLargest, iDb);
59606       iDestroyed = iLargest;
59607     }
59608   }
59609 #endif
59610 }
59611
59612 /*
59613 ** This routine is called to do the work of a DROP TABLE statement.
59614 ** pName is the name of the table to be dropped.
59615 */
59616 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
59617   Table *pTab;
59618   Vdbe *v;
59619   sqlite3 *db = pParse->db;
59620   int iDb;
59621
59622   if( pParse->nErr || db->mallocFailed ){
59623     goto exit_drop_table;
59624   }
59625   assert( pName->nSrc==1 );
59626   pTab = sqlite3LocateTable(pParse, isView, 
59627                             pName->a[0].zName, pName->a[0].zDatabase);
59628
59629   if( pTab==0 ){
59630     if( noErr ){
59631       sqlite3ErrorClear(pParse);
59632     }
59633     goto exit_drop_table;
59634   }
59635   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
59636   assert( iDb>=0 && iDb<db->nDb );
59637
59638   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
59639   ** it is initialized.
59640   */
59641   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
59642     goto exit_drop_table;
59643   }
59644 #ifndef SQLITE_OMIT_AUTHORIZATION
59645   {
59646     int code;
59647     const char *zTab = SCHEMA_TABLE(iDb);
59648     const char *zDb = db->aDb[iDb].zName;
59649     const char *zArg2 = 0;
59650     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
59651       goto exit_drop_table;
59652     }
59653     if( isView ){
59654       if( !OMIT_TEMPDB && iDb==1 ){
59655         code = SQLITE_DROP_TEMP_VIEW;
59656       }else{
59657         code = SQLITE_DROP_VIEW;
59658       }
59659 #ifndef SQLITE_OMIT_VIRTUALTABLE
59660     }else if( IsVirtual(pTab) ){
59661       code = SQLITE_DROP_VTABLE;
59662       zArg2 = pTab->pMod->zName;
59663 #endif
59664     }else{
59665       if( !OMIT_TEMPDB && iDb==1 ){
59666         code = SQLITE_DROP_TEMP_TABLE;
59667       }else{
59668         code = SQLITE_DROP_TABLE;
59669       }
59670     }
59671     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
59672       goto exit_drop_table;
59673     }
59674     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
59675       goto exit_drop_table;
59676     }
59677   }
59678 #endif
59679   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
59680     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
59681     goto exit_drop_table;
59682   }
59683
59684 #ifndef SQLITE_OMIT_VIEW
59685   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
59686   ** on a table.
59687   */
59688   if( isView && pTab->pSelect==0 ){
59689     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
59690     goto exit_drop_table;
59691   }
59692   if( !isView && pTab->pSelect ){
59693     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
59694     goto exit_drop_table;
59695   }
59696 #endif
59697
59698   /* Generate code to remove the table from the master table
59699   ** on disk.
59700   */
59701   v = sqlite3GetVdbe(pParse);
59702   if( v ){
59703     Trigger *pTrigger;
59704     Db *pDb = &db->aDb[iDb];
59705     sqlite3BeginWriteOperation(pParse, 1, iDb);
59706
59707 #ifndef SQLITE_OMIT_VIRTUALTABLE
59708     if( IsVirtual(pTab) ){
59709       Vdbe *v = sqlite3GetVdbe(pParse);
59710       if( v ){
59711         sqlite3VdbeAddOp0(v, OP_VBegin);
59712       }
59713     }
59714 #endif
59715
59716     /* Drop all triggers associated with the table being dropped. Code
59717     ** is generated to remove entries from sqlite_master and/or
59718     ** sqlite_temp_master if required.
59719     */
59720     pTrigger = pTab->pTrigger;
59721     while( pTrigger ){
59722       assert( pTrigger->pSchema==pTab->pSchema || 
59723           pTrigger->pSchema==db->aDb[1].pSchema );
59724       sqlite3DropTriggerPtr(pParse, pTrigger);
59725       pTrigger = pTrigger->pNext;
59726     }
59727
59728 #ifndef SQLITE_OMIT_AUTOINCREMENT
59729     /* Remove any entries of the sqlite_sequence table associated with
59730     ** the table being dropped. This is done before the table is dropped
59731     ** at the btree level, in case the sqlite_sequence table needs to
59732     ** move as a result of the drop (can happen in auto-vacuum mode).
59733     */
59734     if( pTab->tabFlags & TF_Autoincrement ){
59735       sqlite3NestedParse(pParse,
59736         "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
59737         pDb->zName, pTab->zName
59738       );
59739     }
59740 #endif
59741
59742     /* Drop all SQLITE_MASTER table and index entries that refer to the
59743     ** table. The program name loops through the master table and deletes
59744     ** every row that refers to a table of the same name as the one being
59745     ** dropped. Triggers are handled seperately because a trigger can be
59746     ** created in the temp database that refers to a table in another
59747     ** database.
59748     */
59749     sqlite3NestedParse(pParse, 
59750         "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
59751         pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
59752
59753     /* Drop any statistics from the sqlite_stat1 table, if it exists */
59754     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
59755       sqlite3NestedParse(pParse,
59756         "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
59757       );
59758     }
59759
59760     if( !isView && !IsVirtual(pTab) ){
59761       destroyTable(pParse, pTab);
59762     }
59763
59764     /* Remove the table entry from SQLite's internal schema and modify
59765     ** the schema cookie.
59766     */
59767     if( IsVirtual(pTab) ){
59768       sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
59769     }
59770     sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
59771     sqlite3ChangeCookie(pParse, iDb);
59772   }
59773   sqliteViewResetAll(db, iDb);
59774
59775 exit_drop_table:
59776   sqlite3SrcListDelete(db, pName);
59777 }
59778
59779 /*
59780 ** This routine is called to create a new foreign key on the table
59781 ** currently under construction.  pFromCol determines which columns
59782 ** in the current table point to the foreign key.  If pFromCol==0 then
59783 ** connect the key to the last column inserted.  pTo is the name of
59784 ** the table referred to.  pToCol is a list of tables in the other
59785 ** pTo table that the foreign key points to.  flags contains all
59786 ** information about the conflict resolution algorithms specified
59787 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
59788 **
59789 ** An FKey structure is created and added to the table currently
59790 ** under construction in the pParse->pNewTable field.  The new FKey
59791 ** is not linked into db->aFKey at this point - that does not happen
59792 ** until sqlite3EndTable().
59793 **
59794 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
59795 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
59796 */
59797 SQLITE_PRIVATE void sqlite3CreateForeignKey(
59798   Parse *pParse,       /* Parsing context */
59799   ExprList *pFromCol,  /* Columns in this table that point to other table */
59800   Token *pTo,          /* Name of the other table */
59801   ExprList *pToCol,    /* Columns in the other table */
59802   int flags            /* Conflict resolution algorithms. */
59803 ){
59804   sqlite3 *db = pParse->db;
59805 #ifndef SQLITE_OMIT_FOREIGN_KEY
59806   FKey *pFKey = 0;
59807   Table *p = pParse->pNewTable;
59808   int nByte;
59809   int i;
59810   int nCol;
59811   char *z;
59812
59813   assert( pTo!=0 );
59814   if( p==0 || pParse->nErr || IN_DECLARE_VTAB ) goto fk_end;
59815   if( pFromCol==0 ){
59816     int iCol = p->nCol-1;
59817     if( iCol<0 ) goto fk_end;
59818     if( pToCol && pToCol->nExpr!=1 ){
59819       sqlite3ErrorMsg(pParse, "foreign key on %s"
59820          " should reference only one column of table %T",
59821          p->aCol[iCol].zName, pTo);
59822       goto fk_end;
59823     }
59824     nCol = 1;
59825   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
59826     sqlite3ErrorMsg(pParse,
59827         "number of columns in foreign key does not match the number of "
59828         "columns in the referenced table");
59829     goto fk_end;
59830   }else{
59831     nCol = pFromCol->nExpr;
59832   }
59833   nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
59834   if( pToCol ){
59835     for(i=0; i<pToCol->nExpr; i++){
59836       nByte += strlen(pToCol->a[i].zName) + 1;
59837     }
59838   }
59839   pFKey = sqlite3DbMallocZero(db, nByte );
59840   if( pFKey==0 ){
59841     goto fk_end;
59842   }
59843   pFKey->pFrom = p;
59844   pFKey->pNextFrom = p->pFKey;
59845   z = (char*)&pFKey[1];
59846   pFKey->aCol = (struct sColMap*)z;
59847   z += sizeof(struct sColMap)*nCol;
59848   pFKey->zTo = z;
59849   memcpy(z, pTo->z, pTo->n);
59850   z[pTo->n] = 0;
59851   z += pTo->n+1;
59852   pFKey->pNextTo = 0;
59853   pFKey->nCol = nCol;
59854   if( pFromCol==0 ){
59855     pFKey->aCol[0].iFrom = p->nCol-1;
59856   }else{
59857     for(i=0; i<nCol; i++){
59858       int j;
59859       for(j=0; j<p->nCol; j++){
59860         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
59861           pFKey->aCol[i].iFrom = j;
59862           break;
59863         }
59864       }
59865       if( j>=p->nCol ){
59866         sqlite3ErrorMsg(pParse, 
59867           "unknown column \"%s\" in foreign key definition", 
59868           pFromCol->a[i].zName);
59869         goto fk_end;
59870       }
59871     }
59872   }
59873   if( pToCol ){
59874     for(i=0; i<nCol; i++){
59875       int n = strlen(pToCol->a[i].zName);
59876       pFKey->aCol[i].zCol = z;
59877       memcpy(z, pToCol->a[i].zName, n);
59878       z[n] = 0;
59879       z += n+1;
59880     }
59881   }
59882   pFKey->isDeferred = 0;
59883   pFKey->deleteConf = flags & 0xff;
59884   pFKey->updateConf = (flags >> 8 ) & 0xff;
59885   pFKey->insertConf = (flags >> 16 ) & 0xff;
59886
59887   /* Link the foreign key to the table as the last step.
59888   */
59889   p->pFKey = pFKey;
59890   pFKey = 0;
59891
59892 fk_end:
59893   sqlite3DbFree(db, pFKey);
59894 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
59895   sqlite3ExprListDelete(db, pFromCol);
59896   sqlite3ExprListDelete(db, pToCol);
59897 }
59898
59899 /*
59900 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
59901 ** clause is seen as part of a foreign key definition.  The isDeferred
59902 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
59903 ** The behavior of the most recently created foreign key is adjusted
59904 ** accordingly.
59905 */
59906 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
59907 #ifndef SQLITE_OMIT_FOREIGN_KEY
59908   Table *pTab;
59909   FKey *pFKey;
59910   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
59911   pFKey->isDeferred = isDeferred;
59912 #endif
59913 }
59914
59915 /*
59916 ** Generate code that will erase and refill index *pIdx.  This is
59917 ** used to initialize a newly created index or to recompute the
59918 ** content of an index in response to a REINDEX command.
59919 **
59920 ** if memRootPage is not negative, it means that the index is newly
59921 ** created.  The register specified by memRootPage contains the
59922 ** root page number of the index.  If memRootPage is negative, then
59923 ** the index already exists and must be cleared before being refilled and
59924 ** the root page number of the index is taken from pIndex->tnum.
59925 */
59926 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
59927   Table *pTab = pIndex->pTable;  /* The table that is indexed */
59928   int iTab = pParse->nTab;       /* Btree cursor used for pTab */
59929   int iIdx = pParse->nTab+1;     /* Btree cursor used for pIndex */
59930   int addr1;                     /* Address of top of loop */
59931   int tnum;                      /* Root page of index */
59932   Vdbe *v;                       /* Generate code into this virtual machine */
59933   KeyInfo *pKey;                 /* KeyInfo for index */
59934   int regIdxKey;                 /* Registers containing the index key */
59935   int regRecord;                 /* Register holding assemblied index record */
59936   sqlite3 *db = pParse->db;      /* The database connection */
59937   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
59938
59939 #ifndef SQLITE_OMIT_AUTHORIZATION
59940   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
59941       db->aDb[iDb].zName ) ){
59942     return;
59943   }
59944 #endif
59945
59946   /* Require a write-lock on the table to perform this operation */
59947   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
59948
59949   v = sqlite3GetVdbe(pParse);
59950   if( v==0 ) return;
59951   if( memRootPage>=0 ){
59952     tnum = memRootPage;
59953   }else{
59954     tnum = pIndex->tnum;
59955     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
59956   }
59957   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
59958   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
59959                     (char *)pKey, P4_KEYINFO_HANDOFF);
59960   if( memRootPage>=0 ){
59961     sqlite3VdbeChangeP5(v, 1);
59962   }
59963   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
59964   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
59965   regRecord = sqlite3GetTempReg(pParse);
59966   regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
59967   if( pIndex->onError!=OE_None ){
59968     int j1, j2;
59969     int regRowid;
59970
59971     regRowid = regIdxKey + pIndex->nColumn;
59972     j1 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdxKey, 0, pIndex->nColumn);
59973     j2 = sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx,
59974                            0, regRowid, SQLITE_INT_TO_PTR(regRecord), P4_INT32);
59975     sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort, 0,
59976                     "indexed columns are not unique", P4_STATIC);
59977     sqlite3VdbeJumpHere(v, j1);
59978     sqlite3VdbeJumpHere(v, j2);
59979   }
59980   sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
59981   sqlite3ReleaseTempReg(pParse, regRecord);
59982   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
59983   sqlite3VdbeJumpHere(v, addr1);
59984   sqlite3VdbeAddOp1(v, OP_Close, iTab);
59985   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
59986 }
59987
59988 /*
59989 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
59990 ** and pTblList is the name of the table that is to be indexed.  Both will 
59991 ** be NULL for a primary key or an index that is created to satisfy a
59992 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
59993 ** as the table to be indexed.  pParse->pNewTable is a table that is
59994 ** currently being constructed by a CREATE TABLE statement.
59995 **
59996 ** pList is a list of columns to be indexed.  pList will be NULL if this
59997 ** is a primary key or unique-constraint on the most recent column added
59998 ** to the table currently under construction.  
59999 */
60000 SQLITE_PRIVATE void sqlite3CreateIndex(
60001   Parse *pParse,     /* All information about this parse */
60002   Token *pName1,     /* First part of index name. May be NULL */
60003   Token *pName2,     /* Second part of index name. May be NULL */
60004   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
60005   ExprList *pList,   /* A list of columns to be indexed */
60006   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
60007   Token *pStart,     /* The CREATE token that begins this statement */
60008   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
60009   int sortOrder,     /* Sort order of primary key when pList==NULL */
60010   int ifNotExist     /* Omit error if index already exists */
60011 ){
60012   Table *pTab = 0;     /* Table to be indexed */
60013   Index *pIndex = 0;   /* The index to be created */
60014   char *zName = 0;     /* Name of the index */
60015   int nName;           /* Number of characters in zName */
60016   int i, j;
60017   Token nullId;        /* Fake token for an empty ID list */
60018   DbFixer sFix;        /* For assigning database names to pTable */
60019   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
60020   sqlite3 *db = pParse->db;
60021   Db *pDb;             /* The specific table containing the indexed database */
60022   int iDb;             /* Index of the database that is being written */
60023   Token *pName = 0;    /* Unqualified name of the index to create */
60024   struct ExprList_item *pListItem; /* For looping over pList */
60025   int nCol;
60026   int nExtra = 0;
60027   char *zExtra;
60028
60029   if( pParse->nErr || db->mallocFailed || IN_DECLARE_VTAB ){
60030     goto exit_create_index;
60031   }
60032
60033   /*
60034   ** Find the table that is to be indexed.  Return early if not found.
60035   */
60036   if( pTblName!=0 ){
60037
60038     /* Use the two-part index name to determine the database 
60039     ** to search for the table. 'Fix' the table name to this db
60040     ** before looking up the table.
60041     */
60042     assert( pName1 && pName2 );
60043     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
60044     if( iDb<0 ) goto exit_create_index;
60045
60046 #ifndef SQLITE_OMIT_TEMPDB
60047     /* If the index name was unqualified, check if the the table
60048     ** is a temp table. If so, set the database to 1. Do not do this
60049     ** if initialising a database schema.
60050     */
60051     if( !db->init.busy ){
60052       pTab = sqlite3SrcListLookup(pParse, pTblName);
60053       if( pName2 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
60054         iDb = 1;
60055       }
60056     }
60057 #endif
60058
60059     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
60060         sqlite3FixSrcList(&sFix, pTblName)
60061     ){
60062       /* Because the parser constructs pTblName from a single identifier,
60063       ** sqlite3FixSrcList can never fail. */
60064       assert(0);
60065     }
60066     pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName, 
60067         pTblName->a[0].zDatabase);
60068     if( !pTab ) goto exit_create_index;
60069     assert( db->aDb[iDb].pSchema==pTab->pSchema );
60070   }else{
60071     assert( pName==0 );
60072     pTab = pParse->pNewTable;
60073     if( !pTab ) goto exit_create_index;
60074     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
60075   }
60076   pDb = &db->aDb[iDb];
60077
60078   if( pTab==0 || pParse->nErr ) goto exit_create_index;
60079   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
60080     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
60081     goto exit_create_index;
60082   }
60083 #ifndef SQLITE_OMIT_VIEW
60084   if( pTab->pSelect ){
60085     sqlite3ErrorMsg(pParse, "views may not be indexed");
60086     goto exit_create_index;
60087   }
60088 #endif
60089 #ifndef SQLITE_OMIT_VIRTUALTABLE
60090   if( IsVirtual(pTab) ){
60091     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
60092     goto exit_create_index;
60093   }
60094 #endif
60095
60096   /*
60097   ** Find the name of the index.  Make sure there is not already another
60098   ** index or table with the same name.  
60099   **
60100   ** Exception:  If we are reading the names of permanent indices from the
60101   ** sqlite_master table (because some other process changed the schema) and
60102   ** one of the index names collides with the name of a temporary table or
60103   ** index, then we will continue to process this index.
60104   **
60105   ** If pName==0 it means that we are
60106   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
60107   ** own name.
60108   */
60109   if( pName ){
60110     zName = sqlite3NameFromToken(db, pName);
60111     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
60112     if( zName==0 ) goto exit_create_index;
60113     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
60114       goto exit_create_index;
60115     }
60116     if( !db->init.busy ){
60117       if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
60118       if( sqlite3FindTable(db, zName, 0)!=0 ){
60119         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
60120         goto exit_create_index;
60121       }
60122     }
60123     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
60124       if( !ifNotExist ){
60125         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
60126       }
60127       goto exit_create_index;
60128     }
60129   }else{
60130     int n;
60131     Index *pLoop;
60132     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
60133     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
60134     if( zName==0 ){
60135       goto exit_create_index;
60136     }
60137   }
60138
60139   /* Check for authorization to create an index.
60140   */
60141 #ifndef SQLITE_OMIT_AUTHORIZATION
60142   {
60143     const char *zDb = pDb->zName;
60144     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
60145       goto exit_create_index;
60146     }
60147     i = SQLITE_CREATE_INDEX;
60148     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
60149     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
60150       goto exit_create_index;
60151     }
60152   }
60153 #endif
60154
60155   /* If pList==0, it means this routine was called to make a primary
60156   ** key out of the last column added to the table under construction.
60157   ** So create a fake list to simulate this.
60158   */
60159   if( pList==0 ){
60160     nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName;
60161     nullId.n = strlen((char*)nullId.z);
60162     pList = sqlite3ExprListAppend(pParse, 0, 0, &nullId);
60163     if( pList==0 ) goto exit_create_index;
60164     pList->a[0].sortOrder = sortOrder;
60165   }
60166
60167   /* Figure out how many bytes of space are required to store explicitly
60168   ** specified collation sequence names.
60169   */
60170   for(i=0; i<pList->nExpr; i++){
60171     Expr *pExpr;
60172     CollSeq *pColl;
60173     if( (pExpr = pList->a[i].pExpr)!=0 && (pColl = pExpr->pColl)!=0 ){
60174       nExtra += (1 + strlen(pColl->zName));
60175     }
60176   }
60177
60178   /* 
60179   ** Allocate the index structure. 
60180   */
60181   nName = strlen(zName);
60182   nCol = pList->nExpr;
60183   pIndex = sqlite3DbMallocZero(db, 
60184       sizeof(Index) +              /* Index structure  */
60185       sizeof(int)*nCol +           /* Index.aiColumn   */
60186       sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
60187       sizeof(char *)*nCol +        /* Index.azColl     */
60188       sizeof(u8)*nCol +            /* Index.aSortOrder */
60189       nName + 1 +                  /* Index.zName      */
60190       nExtra                       /* Collation sequence names */
60191   );
60192   if( db->mallocFailed ){
60193     goto exit_create_index;
60194   }
60195   pIndex->azColl = (char**)(&pIndex[1]);
60196   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
60197   pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
60198   pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
60199   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
60200   zExtra = (char *)(&pIndex->zName[nName+1]);
60201   memcpy(pIndex->zName, zName, nName+1);
60202   pIndex->pTable = pTab;
60203   pIndex->nColumn = pList->nExpr;
60204   pIndex->onError = onError;
60205   pIndex->autoIndex = pName==0;
60206   pIndex->pSchema = db->aDb[iDb].pSchema;
60207
60208   /* Check to see if we should honor DESC requests on index columns
60209   */
60210   if( pDb->pSchema->file_format>=4 ){
60211     sortOrderMask = -1;   /* Honor DESC */
60212   }else{
60213     sortOrderMask = 0;    /* Ignore DESC */
60214   }
60215
60216   /* Scan the names of the columns of the table to be indexed and
60217   ** load the column indices into the Index structure.  Report an error
60218   ** if any column is not found.
60219   */
60220   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
60221     const char *zColName = pListItem->zName;
60222     Column *pTabCol;
60223     int requestedSortOrder;
60224     char *zColl;                   /* Collation sequence name */
60225
60226     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
60227       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
60228     }
60229     if( j>=pTab->nCol ){
60230       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
60231         pTab->zName, zColName);
60232       goto exit_create_index;
60233     }
60234     /* TODO:  Add a test to make sure that the same column is not named
60235     ** more than once within the same index.  Only the first instance of
60236     ** the column will ever be used by the optimizer.  Note that using the
60237     ** same column more than once cannot be an error because that would 
60238     ** break backwards compatibility - it needs to be a warning.
60239     */
60240     pIndex->aiColumn[i] = j;
60241     if( pListItem->pExpr && pListItem->pExpr->pColl ){
60242       assert( pListItem->pExpr->pColl );
60243       zColl = zExtra;
60244       sqlite3_snprintf(nExtra, zExtra, "%s", pListItem->pExpr->pColl->zName);
60245       zExtra += (strlen(zColl) + 1);
60246     }else{
60247       zColl = pTab->aCol[j].zColl;
60248       if( !zColl ){
60249         zColl = db->pDfltColl->zName;
60250       }
60251     }
60252     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl, -1) ){
60253       goto exit_create_index;
60254     }
60255     pIndex->azColl[i] = zColl;
60256     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
60257     pIndex->aSortOrder[i] = requestedSortOrder;
60258   }
60259   sqlite3DefaultRowEst(pIndex);
60260
60261   if( pTab==pParse->pNewTable ){
60262     /* This routine has been called to create an automatic index as a
60263     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
60264     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
60265     ** i.e. one of:
60266     **
60267     ** CREATE TABLE t(x PRIMARY KEY, y);
60268     ** CREATE TABLE t(x, y, UNIQUE(x, y));
60269     **
60270     ** Either way, check to see if the table already has such an index. If
60271     ** so, don't bother creating this one. This only applies to
60272     ** automatically created indices. Users can do as they wish with
60273     ** explicit indices.
60274     */
60275     Index *pIdx;
60276     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
60277       int k;
60278       assert( pIdx->onError!=OE_None );
60279       assert( pIdx->autoIndex );
60280       assert( pIndex->onError!=OE_None );
60281
60282       if( pIdx->nColumn!=pIndex->nColumn ) continue;
60283       for(k=0; k<pIdx->nColumn; k++){
60284         const char *z1 = pIdx->azColl[k];
60285         const char *z2 = pIndex->azColl[k];
60286         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
60287         if( pIdx->aSortOrder[k]!=pIndex->aSortOrder[k] ) break;
60288         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
60289       }
60290       if( k==pIdx->nColumn ){
60291         if( pIdx->onError!=pIndex->onError ){
60292           /* This constraint creates the same index as a previous
60293           ** constraint specified somewhere in the CREATE TABLE statement.
60294           ** However the ON CONFLICT clauses are different. If both this 
60295           ** constraint and the previous equivalent constraint have explicit
60296           ** ON CONFLICT clauses this is an error. Otherwise, use the
60297           ** explicitly specified behaviour for the index.
60298           */
60299           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
60300             sqlite3ErrorMsg(pParse, 
60301                 "conflicting ON CONFLICT clauses specified", 0);
60302           }
60303           if( pIdx->onError==OE_Default ){
60304             pIdx->onError = pIndex->onError;
60305           }
60306         }
60307         goto exit_create_index;
60308       }
60309     }
60310   }
60311
60312   /* Link the new Index structure to its table and to the other
60313   ** in-memory database structures. 
60314   */
60315   if( db->init.busy ){
60316     Index *p;
60317     p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
60318                          pIndex->zName, strlen(pIndex->zName)+1, pIndex);
60319     if( p ){
60320       assert( p==pIndex );  /* Malloc must have failed */
60321       db->mallocFailed = 1;
60322       goto exit_create_index;
60323     }
60324     db->flags |= SQLITE_InternChanges;
60325     if( pTblName!=0 ){
60326       pIndex->tnum = db->init.newTnum;
60327     }
60328   }
60329
60330   /* If the db->init.busy is 0 then create the index on disk.  This
60331   ** involves writing the index into the master table and filling in the
60332   ** index with the current table contents.
60333   **
60334   ** The db->init.busy is 0 when the user first enters a CREATE INDEX 
60335   ** command.  db->init.busy is 1 when a database is opened and 
60336   ** CREATE INDEX statements are read out of the master table.  In
60337   ** the latter case the index already exists on disk, which is why
60338   ** we don't want to recreate it.
60339   **
60340   ** If pTblName==0 it means this index is generated as a primary key
60341   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
60342   ** has just been created, it contains no data and the index initialization
60343   ** step can be skipped.
60344   */
60345   else if( db->init.busy==0 ){
60346     Vdbe *v;
60347     char *zStmt;
60348     int iMem = ++pParse->nMem;
60349
60350     v = sqlite3GetVdbe(pParse);
60351     if( v==0 ) goto exit_create_index;
60352
60353
60354     /* Create the rootpage for the index
60355     */
60356     sqlite3BeginWriteOperation(pParse, 1, iDb);
60357     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
60358
60359     /* Gather the complete text of the CREATE INDEX statement into
60360     ** the zStmt variable
60361     */
60362     if( pStart && pEnd ){
60363       /* A named index with an explicit CREATE INDEX statement */
60364       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
60365         onError==OE_None ? "" : " UNIQUE",
60366         pEnd->z - pName->z + 1,
60367         pName->z);
60368     }else{
60369       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
60370       /* zStmt = sqlite3MPrintf(""); */
60371       zStmt = 0;
60372     }
60373
60374     /* Add an entry in sqlite_master for this index
60375     */
60376     sqlite3NestedParse(pParse, 
60377         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
60378         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
60379         pIndex->zName,
60380         pTab->zName,
60381         iMem,
60382         zStmt
60383     );
60384     sqlite3DbFree(db, zStmt);
60385
60386     /* Fill the index with data and reparse the schema. Code an OP_Expire
60387     ** to invalidate all pre-compiled statements.
60388     */
60389     if( pTblName ){
60390       sqlite3RefillIndex(pParse, pIndex, iMem);
60391       sqlite3ChangeCookie(pParse, iDb);
60392       sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
60393          sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
60394       sqlite3VdbeAddOp1(v, OP_Expire, 0);
60395     }
60396   }
60397
60398   /* When adding an index to the list of indices for a table, make
60399   ** sure all indices labeled OE_Replace come after all those labeled
60400   ** OE_Ignore.  This is necessary for the correct operation of UPDATE
60401   ** and INSERT.
60402   */
60403   if( db->init.busy || pTblName==0 ){
60404     if( onError!=OE_Replace || pTab->pIndex==0
60405          || pTab->pIndex->onError==OE_Replace){
60406       pIndex->pNext = pTab->pIndex;
60407       pTab->pIndex = pIndex;
60408     }else{
60409       Index *pOther = pTab->pIndex;
60410       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
60411         pOther = pOther->pNext;
60412       }
60413       pIndex->pNext = pOther->pNext;
60414       pOther->pNext = pIndex;
60415     }
60416     pIndex = 0;
60417   }
60418
60419   /* Clean up before exiting */
60420 exit_create_index:
60421   if( pIndex ){
60422     freeIndex(pIndex);
60423   }
60424   sqlite3ExprListDelete(db, pList);
60425   sqlite3SrcListDelete(db, pTblName);
60426   sqlite3DbFree(db, zName);
60427   return;
60428 }
60429
60430 /*
60431 ** Generate code to make sure the file format number is at least minFormat.
60432 ** The generated code will increase the file format number if necessary.
60433 */
60434 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
60435   Vdbe *v;
60436   v = sqlite3GetVdbe(pParse);
60437   if( v ){
60438     int r1 = sqlite3GetTempReg(pParse);
60439     int r2 = sqlite3GetTempReg(pParse);
60440     int j1;
60441     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, 1);
60442     sqlite3VdbeUsesBtree(v, iDb);
60443     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
60444     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
60445     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, r2);
60446     sqlite3VdbeJumpHere(v, j1);
60447     sqlite3ReleaseTempReg(pParse, r1);
60448     sqlite3ReleaseTempReg(pParse, r2);
60449   }
60450 }
60451
60452 /*
60453 ** Fill the Index.aiRowEst[] array with default information - information
60454 ** to be used when we have not run the ANALYZE command.
60455 **
60456 ** aiRowEst[0] is suppose to contain the number of elements in the index.
60457 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
60458 ** number of rows in the table that match any particular value of the
60459 ** first column of the index.  aiRowEst[2] is an estimate of the number
60460 ** of rows that match any particular combiniation of the first 2 columns
60461 ** of the index.  And so forth.  It must always be the case that
60462 *
60463 **           aiRowEst[N]<=aiRowEst[N-1]
60464 **           aiRowEst[N]>=1
60465 **
60466 ** Apart from that, we have little to go on besides intuition as to
60467 ** how aiRowEst[] should be initialized.  The numbers generated here
60468 ** are based on typical values found in actual indices.
60469 */
60470 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
60471   unsigned *a = pIdx->aiRowEst;
60472   int i;
60473   assert( a!=0 );
60474   a[0] = 1000000;
60475   for(i=pIdx->nColumn; i>=5; i--){
60476     a[i] = 5;
60477   }
60478   while( i>=1 ){
60479     a[i] = 11 - i;
60480     i--;
60481   }
60482   if( pIdx->onError!=OE_None ){
60483     a[pIdx->nColumn] = 1;
60484   }
60485 }
60486
60487 /*
60488 ** This routine will drop an existing named index.  This routine
60489 ** implements the DROP INDEX statement.
60490 */
60491 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
60492   Index *pIndex;
60493   Vdbe *v;
60494   sqlite3 *db = pParse->db;
60495   int iDb;
60496
60497   if( pParse->nErr || db->mallocFailed ){
60498     goto exit_drop_index;
60499   }
60500   assert( pName->nSrc==1 );
60501   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
60502     goto exit_drop_index;
60503   }
60504   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
60505   if( pIndex==0 ){
60506     if( !ifExists ){
60507       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
60508     }
60509     pParse->checkSchema = 1;
60510     goto exit_drop_index;
60511   }
60512   if( pIndex->autoIndex ){
60513     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
60514       "or PRIMARY KEY constraint cannot be dropped", 0);
60515     goto exit_drop_index;
60516   }
60517   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
60518 #ifndef SQLITE_OMIT_AUTHORIZATION
60519   {
60520     int code = SQLITE_DROP_INDEX;
60521     Table *pTab = pIndex->pTable;
60522     const char *zDb = db->aDb[iDb].zName;
60523     const char *zTab = SCHEMA_TABLE(iDb);
60524     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
60525       goto exit_drop_index;
60526     }
60527     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
60528     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
60529       goto exit_drop_index;
60530     }
60531   }
60532 #endif
60533
60534   /* Generate code to remove the index and from the master table */
60535   v = sqlite3GetVdbe(pParse);
60536   if( v ){
60537     sqlite3BeginWriteOperation(pParse, 1, iDb);
60538     sqlite3NestedParse(pParse,
60539        "DELETE FROM %Q.%s WHERE name=%Q",
60540        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
60541        pIndex->zName
60542     );
60543     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
60544       sqlite3NestedParse(pParse,
60545         "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
60546         db->aDb[iDb].zName, pIndex->zName
60547       );
60548     }
60549     sqlite3ChangeCookie(pParse, iDb);
60550     destroyRootPage(pParse, pIndex->tnum, iDb);
60551     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
60552   }
60553
60554 exit_drop_index:
60555   sqlite3SrcListDelete(db, pName);
60556 }
60557
60558 /*
60559 ** pArray is a pointer to an array of objects.  Each object in the
60560 ** array is szEntry bytes in size.  This routine allocates a new
60561 ** object on the end of the array.
60562 **
60563 ** *pnEntry is the number of entries already in use.  *pnAlloc is
60564 ** the previously allocated size of the array.  initSize is the
60565 ** suggested initial array size allocation.
60566 **
60567 ** The index of the new entry is returned in *pIdx.
60568 **
60569 ** This routine returns a pointer to the array of objects.  This
60570 ** might be the same as the pArray parameter or it might be a different
60571 ** pointer if the array was resized.
60572 */
60573 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
60574   sqlite3 *db,      /* Connection to notify of malloc failures */
60575   void *pArray,     /* Array of objects.  Might be reallocated */
60576   int szEntry,      /* Size of each object in the array */
60577   int initSize,     /* Suggested initial allocation, in elements */
60578   int *pnEntry,     /* Number of objects currently in use */
60579   int *pnAlloc,     /* Current size of the allocation, in elements */
60580   int *pIdx         /* Write the index of a new slot here */
60581 ){
60582   char *z;
60583   if( *pnEntry >= *pnAlloc ){
60584     void *pNew;
60585     int newSize;
60586     newSize = (*pnAlloc)*2 + initSize;
60587     pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
60588     if( pNew==0 ){
60589       *pIdx = -1;
60590       return pArray;
60591     }
60592     *pnAlloc = newSize;
60593     pArray = pNew;
60594   }
60595   z = (char*)pArray;
60596   memset(&z[*pnEntry * szEntry], 0, szEntry);
60597   *pIdx = *pnEntry;
60598   ++*pnEntry;
60599   return pArray;
60600 }
60601
60602 /*
60603 ** Append a new element to the given IdList.  Create a new IdList if
60604 ** need be.
60605 **
60606 ** A new IdList is returned, or NULL if malloc() fails.
60607 */
60608 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
60609   int i;
60610   if( pList==0 ){
60611     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
60612     if( pList==0 ) return 0;
60613     pList->nAlloc = 0;
60614   }
60615   pList->a = sqlite3ArrayAllocate(
60616       db,
60617       pList->a,
60618       sizeof(pList->a[0]),
60619       5,
60620       &pList->nId,
60621       &pList->nAlloc,
60622       &i
60623   );
60624   if( i<0 ){
60625     sqlite3IdListDelete(db, pList);
60626     return 0;
60627   }
60628   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
60629   return pList;
60630 }
60631
60632 /*
60633 ** Delete an IdList.
60634 */
60635 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
60636   int i;
60637   if( pList==0 ) return;
60638   for(i=0; i<pList->nId; i++){
60639     sqlite3DbFree(db, pList->a[i].zName);
60640   }
60641   sqlite3DbFree(db, pList->a);
60642   sqlite3DbFree(db, pList);
60643 }
60644
60645 /*
60646 ** Return the index in pList of the identifier named zId.  Return -1
60647 ** if not found.
60648 */
60649 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
60650   int i;
60651   if( pList==0 ) return -1;
60652   for(i=0; i<pList->nId; i++){
60653     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
60654   }
60655   return -1;
60656 }
60657
60658 /*
60659 ** Append a new table name to the given SrcList.  Create a new SrcList if
60660 ** need be.  A new entry is created in the SrcList even if pToken is NULL.
60661 **
60662 ** A new SrcList is returned, or NULL if malloc() fails.
60663 **
60664 ** If pDatabase is not null, it means that the table has an optional
60665 ** database name prefix.  Like this:  "database.table".  The pDatabase
60666 ** points to the table name and the pTable points to the database name.
60667 ** The SrcList.a[].zName field is filled with the table name which might
60668 ** come from pTable (if pDatabase is NULL) or from pDatabase.  
60669 ** SrcList.a[].zDatabase is filled with the database name from pTable,
60670 ** or with NULL if no database is specified.
60671 **
60672 ** In other words, if call like this:
60673 **
60674 **         sqlite3SrcListAppend(D,A,B,0);
60675 **
60676 ** Then B is a table name and the database name is unspecified.  If called
60677 ** like this:
60678 **
60679 **         sqlite3SrcListAppend(D,A,B,C);
60680 **
60681 ** Then C is the table name and B is the database name.
60682 */
60683 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
60684   sqlite3 *db,        /* Connection to notify of malloc failures */
60685   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
60686   Token *pTable,      /* Table to append */
60687   Token *pDatabase    /* Database of the table */
60688 ){
60689   struct SrcList_item *pItem;
60690   if( pList==0 ){
60691     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
60692     if( pList==0 ) return 0;
60693     pList->nAlloc = 1;
60694   }
60695   if( pList->nSrc>=pList->nAlloc ){
60696     SrcList *pNew;
60697     pList->nAlloc *= 2;
60698     pNew = sqlite3DbRealloc(db, pList,
60699                sizeof(*pList) + (pList->nAlloc-1)*sizeof(pList->a[0]) );
60700     if( pNew==0 ){
60701       sqlite3SrcListDelete(db, pList);
60702       return 0;
60703     }
60704     pList = pNew;
60705   }
60706   pItem = &pList->a[pList->nSrc];
60707   memset(pItem, 0, sizeof(pList->a[0]));
60708   if( pDatabase && pDatabase->z==0 ){
60709     pDatabase = 0;
60710   }
60711   if( pDatabase && pTable ){
60712     Token *pTemp = pDatabase;
60713     pDatabase = pTable;
60714     pTable = pTemp;
60715   }
60716   pItem->zName = sqlite3NameFromToken(db, pTable);
60717   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
60718   pItem->iCursor = -1;
60719   pItem->isPopulated = 0;
60720   pList->nSrc++;
60721   return pList;
60722 }
60723
60724 /*
60725 ** Assign cursors to all tables in a SrcList
60726 */
60727 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
60728   int i;
60729   struct SrcList_item *pItem;
60730   assert(pList || pParse->db->mallocFailed );
60731   if( pList ){
60732     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
60733       if( pItem->iCursor>=0 ) break;
60734       pItem->iCursor = pParse->nTab++;
60735       if( pItem->pSelect ){
60736         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
60737       }
60738     }
60739   }
60740 }
60741
60742 /*
60743 ** Delete an entire SrcList including all its substructure.
60744 */
60745 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
60746   int i;
60747   struct SrcList_item *pItem;
60748   if( pList==0 ) return;
60749   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
60750     sqlite3DbFree(db, pItem->zDatabase);
60751     sqlite3DbFree(db, pItem->zName);
60752     sqlite3DbFree(db, pItem->zAlias);
60753     sqlite3DeleteTable(pItem->pTab);
60754     sqlite3SelectDelete(db, pItem->pSelect);
60755     sqlite3ExprDelete(db, pItem->pOn);
60756     sqlite3IdListDelete(db, pItem->pUsing);
60757   }
60758   sqlite3DbFree(db, pList);
60759 }
60760
60761 /*
60762 ** This routine is called by the parser to add a new term to the
60763 ** end of a growing FROM clause.  The "p" parameter is the part of
60764 ** the FROM clause that has already been constructed.  "p" is NULL
60765 ** if this is the first term of the FROM clause.  pTable and pDatabase
60766 ** are the name of the table and database named in the FROM clause term.
60767 ** pDatabase is NULL if the database name qualifier is missing - the
60768 ** usual case.  If the term has a alias, then pAlias points to the
60769 ** alias token.  If the term is a subquery, then pSubquery is the
60770 ** SELECT statement that the subquery encodes.  The pTable and
60771 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
60772 ** parameters are the content of the ON and USING clauses.
60773 **
60774 ** Return a new SrcList which encodes is the FROM with the new
60775 ** term added.
60776 */
60777 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
60778   Parse *pParse,          /* Parsing context */
60779   SrcList *p,             /* The left part of the FROM clause already seen */
60780   Token *pTable,          /* Name of the table to add to the FROM clause */
60781   Token *pDatabase,       /* Name of the database containing pTable */
60782   Token *pAlias,          /* The right-hand side of the AS subexpression */
60783   Select *pSubquery,      /* A subquery used in place of a table name */
60784   Expr *pOn,              /* The ON clause of a join */
60785   IdList *pUsing          /* The USING clause of a join */
60786 ){
60787   struct SrcList_item *pItem;
60788   sqlite3 *db = pParse->db;
60789   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
60790   if( p==0 || p->nSrc==0 ){
60791     sqlite3ExprDelete(db, pOn);
60792     sqlite3IdListDelete(db, pUsing);
60793     sqlite3SelectDelete(db, pSubquery);
60794     return p;
60795   }
60796   pItem = &p->a[p->nSrc-1];
60797   if( pAlias && pAlias->n ){
60798     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
60799   }
60800   pItem->pSelect = pSubquery;
60801   pItem->pOn = pOn;
60802   pItem->pUsing = pUsing;
60803   return p;
60804 }
60805
60806 /*
60807 ** When building up a FROM clause in the parser, the join operator
60808 ** is initially attached to the left operand.  But the code generator
60809 ** expects the join operator to be on the right operand.  This routine
60810 ** Shifts all join operators from left to right for an entire FROM
60811 ** clause.
60812 **
60813 ** Example: Suppose the join is like this:
60814 **
60815 **           A natural cross join B
60816 **
60817 ** The operator is "natural cross join".  The A and B operands are stored
60818 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
60819 ** operator with A.  This routine shifts that operator over to B.
60820 */
60821 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
60822   if( p && p->a ){
60823     int i;
60824     for(i=p->nSrc-1; i>0; i--){
60825       p->a[i].jointype = p->a[i-1].jointype;
60826     }
60827     p->a[0].jointype = 0;
60828   }
60829 }
60830
60831 /*
60832 ** Begin a transaction
60833 */
60834 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
60835   sqlite3 *db;
60836   Vdbe *v;
60837   int i;
60838
60839   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
60840   if( pParse->nErr || db->mallocFailed ) return;
60841   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
60842
60843   v = sqlite3GetVdbe(pParse);
60844   if( !v ) return;
60845   if( type!=TK_DEFERRED ){
60846     for(i=0; i<db->nDb; i++){
60847       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
60848       sqlite3VdbeUsesBtree(v, i);
60849     }
60850   }
60851   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
60852 }
60853
60854 /*
60855 ** Commit a transaction
60856 */
60857 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
60858   sqlite3 *db;
60859   Vdbe *v;
60860
60861   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
60862   if( pParse->nErr || db->mallocFailed ) return;
60863   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
60864
60865   v = sqlite3GetVdbe(pParse);
60866   if( v ){
60867     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
60868   }
60869 }
60870
60871 /*
60872 ** Rollback a transaction
60873 */
60874 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
60875   sqlite3 *db;
60876   Vdbe *v;
60877
60878   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
60879   if( pParse->nErr || db->mallocFailed ) return;
60880   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
60881
60882   v = sqlite3GetVdbe(pParse);
60883   if( v ){
60884     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
60885   }
60886 }
60887
60888 /*
60889 ** Make sure the TEMP database is open and available for use.  Return
60890 ** the number of errors.  Leave any error messages in the pParse structure.
60891 */
60892 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
60893   sqlite3 *db = pParse->db;
60894   if( db->aDb[1].pBt==0 && !pParse->explain ){
60895     int rc;
60896     static const int flags = 
60897           SQLITE_OPEN_READWRITE |
60898           SQLITE_OPEN_CREATE |
60899           SQLITE_OPEN_EXCLUSIVE |
60900           SQLITE_OPEN_DELETEONCLOSE |
60901           SQLITE_OPEN_TEMP_DB;
60902
60903     rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags,
60904                                  &db->aDb[1].pBt);
60905     if( rc!=SQLITE_OK ){
60906       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
60907         "file for storing temporary tables");
60908       pParse->rc = rc;
60909       return 1;
60910     }
60911     assert( (db->flags & SQLITE_InTrans)==0 || db->autoCommit );
60912     assert( db->aDb[1].pSchema );
60913     sqlite3PagerJournalMode(sqlite3BtreePager(db->aDb[1].pBt),
60914                             db->dfltJournalMode);
60915   }
60916   return 0;
60917 }
60918
60919 /*
60920 ** Generate VDBE code that will verify the schema cookie and start
60921 ** a read-transaction for all named database files.
60922 **
60923 ** It is important that all schema cookies be verified and all
60924 ** read transactions be started before anything else happens in
60925 ** the VDBE program.  But this routine can be called after much other
60926 ** code has been generated.  So here is what we do:
60927 **
60928 ** The first time this routine is called, we code an OP_Goto that
60929 ** will jump to a subroutine at the end of the program.  Then we
60930 ** record every database that needs its schema verified in the
60931 ** pParse->cookieMask field.  Later, after all other code has been
60932 ** generated, the subroutine that does the cookie verifications and
60933 ** starts the transactions will be coded and the OP_Goto P2 value
60934 ** will be made to point to that subroutine.  The generation of the
60935 ** cookie verification subroutine code happens in sqlite3FinishCoding().
60936 **
60937 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
60938 ** schema on any databases.  This can be used to position the OP_Goto
60939 ** early in the code, before we know if any database tables will be used.
60940 */
60941 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
60942   sqlite3 *db;
60943   Vdbe *v;
60944   int mask;
60945
60946   v = sqlite3GetVdbe(pParse);
60947   if( v==0 ) return;  /* This only happens if there was a prior error */
60948   db = pParse->db;
60949   if( pParse->cookieGoto==0 ){
60950     pParse->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
60951   }
60952   if( iDb>=0 ){
60953     assert( iDb<db->nDb );
60954     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
60955     assert( iDb<SQLITE_MAX_ATTACHED+2 );
60956     mask = 1<<iDb;
60957     if( (pParse->cookieMask & mask)==0 ){
60958       pParse->cookieMask |= mask;
60959       pParse->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
60960       if( !OMIT_TEMPDB && iDb==1 ){
60961         sqlite3OpenTempDatabase(pParse);
60962       }
60963     }
60964   }
60965 }
60966
60967 /*
60968 ** Generate VDBE code that prepares for doing an operation that
60969 ** might change the database.
60970 **
60971 ** This routine starts a new transaction if we are not already within
60972 ** a transaction.  If we are already within a transaction, then a checkpoint
60973 ** is set if the setStatement parameter is true.  A checkpoint should
60974 ** be set for operations that might fail (due to a constraint) part of
60975 ** the way through and which will need to undo some writes without having to
60976 ** rollback the whole transaction.  For operations where all constraints
60977 ** can be checked before any changes are made to the database, it is never
60978 ** necessary to undo a write and the checkpoint should not be set.
60979 **
60980 ** Only database iDb and the temp database are made writable by this call.
60981 ** If iDb==0, then the main and temp databases are made writable.   If
60982 ** iDb==1 then only the temp database is made writable.  If iDb>1 then the
60983 ** specified auxiliary database and the temp database are made writable.
60984 */
60985 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
60986   Vdbe *v = sqlite3GetVdbe(pParse);
60987   if( v==0 ) return;
60988   sqlite3CodeVerifySchema(pParse, iDb);
60989   pParse->writeMask |= 1<<iDb;
60990   if( setStatement && pParse->nested==0 ){
60991     sqlite3VdbeAddOp1(v, OP_Statement, iDb);
60992   }
60993   if( (OMIT_TEMPDB || iDb!=1) && pParse->db->aDb[1].pBt!=0 ){
60994     sqlite3BeginWriteOperation(pParse, setStatement, 1);
60995   }
60996 }
60997
60998 /*
60999 ** Check to see if pIndex uses the collating sequence pColl.  Return
61000 ** true if it does and false if it does not.
61001 */
61002 #ifndef SQLITE_OMIT_REINDEX
61003 static int collationMatch(const char *zColl, Index *pIndex){
61004   int i;
61005   for(i=0; i<pIndex->nColumn; i++){
61006     const char *z = pIndex->azColl[i];
61007     if( z==zColl || (z && zColl && 0==sqlite3StrICmp(z, zColl)) ){
61008       return 1;
61009     }
61010   }
61011   return 0;
61012 }
61013 #endif
61014
61015 /*
61016 ** Recompute all indices of pTab that use the collating sequence pColl.
61017 ** If pColl==0 then recompute all indices of pTab.
61018 */
61019 #ifndef SQLITE_OMIT_REINDEX
61020 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
61021   Index *pIndex;              /* An index associated with pTab */
61022
61023   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
61024     if( zColl==0 || collationMatch(zColl, pIndex) ){
61025       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
61026       sqlite3BeginWriteOperation(pParse, 0, iDb);
61027       sqlite3RefillIndex(pParse, pIndex, -1);
61028     }
61029   }
61030 }
61031 #endif
61032
61033 /*
61034 ** Recompute all indices of all tables in all databases where the
61035 ** indices use the collating sequence pColl.  If pColl==0 then recompute
61036 ** all indices everywhere.
61037 */
61038 #ifndef SQLITE_OMIT_REINDEX
61039 static void reindexDatabases(Parse *pParse, char const *zColl){
61040   Db *pDb;                    /* A single database */
61041   int iDb;                    /* The database index number */
61042   sqlite3 *db = pParse->db;   /* The database connection */
61043   HashElem *k;                /* For looping over tables in pDb */
61044   Table *pTab;                /* A table in the database */
61045
61046   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
61047     assert( pDb!=0 );
61048     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
61049       pTab = (Table*)sqliteHashData(k);
61050       reindexTable(pParse, pTab, zColl);
61051     }
61052   }
61053 }
61054 #endif
61055
61056 /*
61057 ** Generate code for the REINDEX command.
61058 **
61059 **        REINDEX                            -- 1
61060 **        REINDEX  <collation>               -- 2
61061 **        REINDEX  ?<database>.?<tablename>  -- 3
61062 **        REINDEX  ?<database>.?<indexname>  -- 4
61063 **
61064 ** Form 1 causes all indices in all attached databases to be rebuilt.
61065 ** Form 2 rebuilds all indices in all databases that use the named
61066 ** collating function.  Forms 3 and 4 rebuild the named index or all
61067 ** indices associated with the named table.
61068 */
61069 #ifndef SQLITE_OMIT_REINDEX
61070 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
61071   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
61072   char *z;                    /* Name of a table or index */
61073   const char *zDb;            /* Name of the database */
61074   Table *pTab;                /* A table in the database */
61075   Index *pIndex;              /* An index associated with pTab */
61076   int iDb;                    /* The database index number */
61077   sqlite3 *db = pParse->db;   /* The database connection */
61078   Token *pObjName;            /* Name of the table or index to be reindexed */
61079
61080   /* Read the database schema. If an error occurs, leave an error message
61081   ** and code in pParse and return NULL. */
61082   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
61083     return;
61084   }
61085
61086   if( pName1==0 || pName1->z==0 ){
61087     reindexDatabases(pParse, 0);
61088     return;
61089   }else if( pName2==0 || pName2->z==0 ){
61090     char *zColl;
61091     assert( pName1->z );
61092     zColl = sqlite3NameFromToken(pParse->db, pName1);
61093     if( !zColl ) return;
61094     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, -1, 0);
61095     if( pColl ){
61096       if( zColl ){
61097         reindexDatabases(pParse, zColl);
61098         sqlite3DbFree(db, zColl);
61099       }
61100       return;
61101     }
61102     sqlite3DbFree(db, zColl);
61103   }
61104   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
61105   if( iDb<0 ) return;
61106   z = sqlite3NameFromToken(db, pObjName);
61107   if( z==0 ) return;
61108   zDb = db->aDb[iDb].zName;
61109   pTab = sqlite3FindTable(db, z, zDb);
61110   if( pTab ){
61111     reindexTable(pParse, pTab, 0);
61112     sqlite3DbFree(db, z);
61113     return;
61114   }
61115   pIndex = sqlite3FindIndex(db, z, zDb);
61116   sqlite3DbFree(db, z);
61117   if( pIndex ){
61118     sqlite3BeginWriteOperation(pParse, 0, iDb);
61119     sqlite3RefillIndex(pParse, pIndex, -1);
61120     return;
61121   }
61122   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
61123 }
61124 #endif
61125
61126 /*
61127 ** Return a dynamicly allocated KeyInfo structure that can be used
61128 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
61129 **
61130 ** If successful, a pointer to the new structure is returned. In this case
61131 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned 
61132 ** pointer. If an error occurs (out of memory or missing collation 
61133 ** sequence), NULL is returned and the state of pParse updated to reflect
61134 ** the error.
61135 */
61136 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
61137   int i;
61138   int nCol = pIdx->nColumn;
61139   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
61140   sqlite3 *db = pParse->db;
61141   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
61142
61143   if( pKey ){
61144     pKey->db = pParse->db;
61145     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
61146     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
61147     for(i=0; i<nCol; i++){
61148       char *zColl = pIdx->azColl[i];
61149       assert( zColl );
61150       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl, -1);
61151       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
61152     }
61153     pKey->nField = nCol;
61154   }
61155
61156   if( pParse->nErr ){
61157     sqlite3DbFree(db, pKey);
61158     pKey = 0;
61159   }
61160   return pKey;
61161 }
61162
61163 /************** End of build.c ***********************************************/
61164 /************** Begin file callback.c ****************************************/
61165 /*
61166 ** 2005 May 23 
61167 **
61168 ** The author disclaims copyright to this source code.  In place of
61169 ** a legal notice, here is a blessing:
61170 **
61171 **    May you do good and not evil.
61172 **    May you find forgiveness for yourself and forgive others.
61173 **    May you share freely, never taking more than you give.
61174 **
61175 *************************************************************************
61176 **
61177 ** This file contains functions used to access the internal hash tables
61178 ** of user defined functions and collation sequences.
61179 **
61180 ** $Id: callback.c,v 1.31 2008/09/09 12:31:34 drh Exp $
61181 */
61182
61183
61184 /*
61185 ** Invoke the 'collation needed' callback to request a collation sequence
61186 ** in the database text encoding of name zName, length nName.
61187 ** If the collation sequence
61188 */
61189 static void callCollNeeded(sqlite3 *db, const char *zName, int nName){
61190   assert( !db->xCollNeeded || !db->xCollNeeded16 );
61191   if( nName<0 ) nName = sqlite3Strlen(db, zName);
61192   if( db->xCollNeeded ){
61193     char *zExternal = sqlite3DbStrNDup(db, zName, nName);
61194     if( !zExternal ) return;
61195     db->xCollNeeded(db->pCollNeededArg, db, (int)ENC(db), zExternal);
61196     sqlite3DbFree(db, zExternal);
61197   }
61198 #ifndef SQLITE_OMIT_UTF16
61199   if( db->xCollNeeded16 ){
61200     char const *zExternal;
61201     sqlite3_value *pTmp = sqlite3ValueNew(db);
61202     sqlite3ValueSetStr(pTmp, nName, zName, SQLITE_UTF8, SQLITE_STATIC);
61203     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
61204     if( zExternal ){
61205       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
61206     }
61207     sqlite3ValueFree(pTmp);
61208   }
61209 #endif
61210 }
61211
61212 /*
61213 ** This routine is called if the collation factory fails to deliver a
61214 ** collation function in the best encoding but there may be other versions
61215 ** of this collation function (for other text encodings) available. Use one
61216 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
61217 ** possible.
61218 */
61219 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
61220   CollSeq *pColl2;
61221   char *z = pColl->zName;
61222   int n = strlen(z);
61223   int i;
61224   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
61225   for(i=0; i<3; i++){
61226     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, n, 0);
61227     if( pColl2->xCmp!=0 ){
61228       memcpy(pColl, pColl2, sizeof(CollSeq));
61229       pColl->xDel = 0;         /* Do not copy the destructor */
61230       return SQLITE_OK;
61231     }
61232   }
61233   return SQLITE_ERROR;
61234 }
61235
61236 /*
61237 ** This function is responsible for invoking the collation factory callback
61238 ** or substituting a collation sequence of a different encoding when the
61239 ** requested collation sequence is not available in the database native
61240 ** encoding.
61241 ** 
61242 ** If it is not NULL, then pColl must point to the database native encoding 
61243 ** collation sequence with name zName, length nName.
61244 **
61245 ** The return value is either the collation sequence to be used in database
61246 ** db for collation type name zName, length nName, or NULL, if no collation
61247 ** sequence can be found.
61248 */
61249 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
61250   sqlite3* db, 
61251   CollSeq *pColl, 
61252   const char *zName, 
61253   int nName
61254 ){
61255   CollSeq *p;
61256
61257   p = pColl;
61258   if( !p ){
61259     p = sqlite3FindCollSeq(db, ENC(db), zName, nName, 0);
61260   }
61261   if( !p || !p->xCmp ){
61262     /* No collation sequence of this type for this encoding is registered.
61263     ** Call the collation factory to see if it can supply us with one.
61264     */
61265     callCollNeeded(db, zName, nName);
61266     p = sqlite3FindCollSeq(db, ENC(db), zName, nName, 0);
61267   }
61268   if( p && !p->xCmp && synthCollSeq(db, p) ){
61269     p = 0;
61270   }
61271   assert( !p || p->xCmp );
61272   return p;
61273 }
61274
61275 /*
61276 ** This routine is called on a collation sequence before it is used to
61277 ** check that it is defined. An undefined collation sequence exists when
61278 ** a database is loaded that contains references to collation sequences
61279 ** that have not been defined by sqlite3_create_collation() etc.
61280 **
61281 ** If required, this routine calls the 'collation needed' callback to
61282 ** request a definition of the collating sequence. If this doesn't work, 
61283 ** an equivalent collating sequence that uses a text encoding different
61284 ** from the main database is substituted, if one is available.
61285 */
61286 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
61287   if( pColl ){
61288     const char *zName = pColl->zName;
61289     CollSeq *p = sqlite3GetCollSeq(pParse->db, pColl, zName, -1);
61290     if( !p ){
61291       if( pParse->nErr==0 ){
61292         sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
61293       }
61294       pParse->nErr++;
61295       return SQLITE_ERROR;
61296     }
61297     assert( p==pColl );
61298   }
61299   return SQLITE_OK;
61300 }
61301
61302
61303
61304 /*
61305 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
61306 ** specified by zName and nName is not found and parameter 'create' is
61307 ** true, then create a new entry. Otherwise return NULL.
61308 **
61309 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
61310 ** array of three CollSeq structures. The first is the collation sequence
61311 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
61312 **
61313 ** Stored immediately after the three collation sequences is a copy of
61314 ** the collation sequence name. A pointer to this string is stored in
61315 ** each collation sequence structure.
61316 */
61317 static CollSeq *findCollSeqEntry(
61318   sqlite3 *db,
61319   const char *zName,
61320   int nName,
61321   int create
61322 ){
61323   CollSeq *pColl;
61324   if( nName<0 ) nName = sqlite3Strlen(db, zName);
61325   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
61326
61327   if( 0==pColl && create ){
61328     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
61329     if( pColl ){
61330       CollSeq *pDel = 0;
61331       pColl[0].zName = (char*)&pColl[3];
61332       pColl[0].enc = SQLITE_UTF8;
61333       pColl[1].zName = (char*)&pColl[3];
61334       pColl[1].enc = SQLITE_UTF16LE;
61335       pColl[2].zName = (char*)&pColl[3];
61336       pColl[2].enc = SQLITE_UTF16BE;
61337       memcpy(pColl[0].zName, zName, nName);
61338       pColl[0].zName[nName] = 0;
61339       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
61340
61341       /* If a malloc() failure occured in sqlite3HashInsert(), it will 
61342       ** return the pColl pointer to be deleted (because it wasn't added
61343       ** to the hash table).
61344       */
61345       assert( pDel==0 || pDel==pColl );
61346       if( pDel!=0 ){
61347         db->mallocFailed = 1;
61348         sqlite3DbFree(db, pDel);
61349         pColl = 0;
61350       }
61351     }
61352   }
61353   return pColl;
61354 }
61355
61356 /*
61357 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
61358 ** Return the CollSeq* pointer for the collation sequence named zName
61359 ** for the encoding 'enc' from the database 'db'.
61360 **
61361 ** If the entry specified is not found and 'create' is true, then create a
61362 ** new entry.  Otherwise return NULL.
61363 **
61364 ** A separate function sqlite3LocateCollSeq() is a wrapper around
61365 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
61366 ** if necessary and generates an error message if the collating sequence
61367 ** cannot be found.
61368 */
61369 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
61370   sqlite3 *db,
61371   u8 enc,
61372   const char *zName,
61373   int nName,
61374   int create
61375 ){
61376   CollSeq *pColl;
61377   if( zName ){
61378     pColl = findCollSeqEntry(db, zName, nName, create);
61379   }else{
61380     pColl = db->pDfltColl;
61381   }
61382   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
61383   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
61384   if( pColl ) pColl += enc-1;
61385   return pColl;
61386 }
61387
61388 /* During the search for the best function definition, this procedure
61389 ** is called to test how well the function passed as the first argument
61390 ** matches the request for a function with nArg arguments in a system
61391 ** that uses encoding enc. The value returned indicates how well the
61392 ** request is matched. A higher value indicates a better match.
61393 **
61394 ** The returned value is always between 1 and 6, as follows:
61395 **
61396 ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
61397 **    encoding is requested, or vice versa.
61398 ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
61399 **    requested, or vice versa.
61400 ** 3: A variable arguments function using the same text encoding.
61401 ** 4: A function with the exact number of arguments requested that
61402 **    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
61403 ** 5: A function with the exact number of arguments requested that
61404 **    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
61405 ** 6: An exact match.
61406 **
61407 */
61408 static int matchQuality(FuncDef *p, int nArg, u8 enc){
61409   int match = 0;
61410   if( p->nArg==-1 || p->nArg==nArg || nArg==-1 ){
61411     match = 1;
61412     if( p->nArg==nArg || nArg==-1 ){
61413       match = 4;
61414     }
61415     if( enc==p->iPrefEnc ){
61416       match += 2;
61417     }
61418     else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
61419              (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
61420       match += 1;
61421     }
61422   }
61423   return match;
61424 }
61425
61426 /*
61427 ** Search a FuncDefHash for a function with the given name.  Return
61428 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
61429 */
61430 static FuncDef *functionSearch(
61431   FuncDefHash *pHash,  /* Hash table to search */
61432   int h,               /* Hash of the name */
61433   const char *zFunc,   /* Name of function */
61434   int nFunc            /* Number of bytes in zFunc */
61435 ){
61436   FuncDef *p;
61437   for(p=pHash->a[h]; p; p=p->pHash){
61438     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
61439       return p;
61440     }
61441   }
61442   return 0;
61443 }
61444
61445 /*
61446 ** Insert a new FuncDef into a FuncDefHash hash table.
61447 */
61448 SQLITE_PRIVATE void sqlite3FuncDefInsert(
61449   FuncDefHash *pHash,  /* The hash table into which to insert */
61450   FuncDef *pDef        /* The function definition to insert */
61451 ){
61452   FuncDef *pOther;
61453   int nName = strlen(pDef->zName);
61454   u8 c1 = (u8)pDef->zName[0];
61455   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
61456   pOther = functionSearch(pHash, h, pDef->zName, nName);
61457   if( pOther ){
61458     pDef->pNext = pOther->pNext;
61459     pOther->pNext = pDef;
61460   }else{
61461     pDef->pNext = 0;
61462     pDef->pHash = pHash->a[h];
61463     pHash->a[h] = pDef;
61464   }
61465 }
61466   
61467   
61468
61469 /*
61470 ** Locate a user function given a name, a number of arguments and a flag
61471 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
61472 ** pointer to the FuncDef structure that defines that function, or return
61473 ** NULL if the function does not exist.
61474 **
61475 ** If the createFlag argument is true, then a new (blank) FuncDef
61476 ** structure is created and liked into the "db" structure if a
61477 ** no matching function previously existed.  When createFlag is true
61478 ** and the nArg parameter is -1, then only a function that accepts
61479 ** any number of arguments will be returned.
61480 **
61481 ** If createFlag is false and nArg is -1, then the first valid
61482 ** function found is returned.  A function is valid if either xFunc
61483 ** or xStep is non-zero.
61484 **
61485 ** If createFlag is false, then a function with the required name and
61486 ** number of arguments may be returned even if the eTextRep flag does not
61487 ** match that requested.
61488 */
61489 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
61490   sqlite3 *db,       /* An open database */
61491   const char *zName, /* Name of the function.  Not null-terminated */
61492   int nName,         /* Number of characters in the name */
61493   int nArg,          /* Number of arguments.  -1 means any number */
61494   u8 enc,            /* Preferred text encoding */
61495   int createFlag     /* Create new entry if true and does not otherwise exist */
61496 ){
61497   FuncDef *p;         /* Iterator variable */
61498   FuncDef *pBest = 0; /* Best match found so far */
61499   int bestScore = 0;  /* Score of best match */
61500   int h;              /* Hash value */
61501
61502
61503   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
61504   if( nArg<-1 ) nArg = -1;
61505   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
61506
61507   /* First search for a match amongst the application-defined functions.
61508   */
61509   p = functionSearch(&db->aFunc, h, zName, nName);
61510   while( p ){
61511     int score = matchQuality(p, nArg, enc);
61512     if( score>bestScore ){
61513       pBest = p;
61514       bestScore = score;
61515     }
61516     p = p->pNext;
61517   }
61518
61519   /* If no match is found, search the built-in functions.
61520   **
61521   ** Except, if createFlag is true, that means that we are trying to
61522   ** install a new function.  Whatever FuncDef structure is returned will
61523   ** have fields overwritten with new information appropriate for the
61524   ** new function.  But the FuncDefs for built-in functions are read-only.
61525   ** So we must not search for built-ins when creating a new function.
61526   */ 
61527   if( !createFlag && !pBest ){
61528     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
61529     p = functionSearch(pHash, h, zName, nName);
61530     while( p ){
61531       int score = matchQuality(p, nArg, enc);
61532       if( score>bestScore ){
61533         pBest = p;
61534         bestScore = score;
61535       }
61536       p = p->pNext;
61537     }
61538   }
61539
61540   /* If the createFlag parameter is true and the search did not reveal an
61541   ** exact match for the name, number of arguments and encoding, then add a
61542   ** new entry to the hash table and return it.
61543   */
61544   if( createFlag && (bestScore<6 || pBest->nArg!=nArg) && 
61545       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
61546     pBest->zName = (char *)&pBest[1];
61547     pBest->nArg = nArg;
61548     pBest->iPrefEnc = enc;
61549     memcpy(pBest->zName, zName, nName);
61550     pBest->zName[nName] = 0;
61551     sqlite3FuncDefInsert(&db->aFunc, pBest);
61552   }
61553
61554   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
61555     return pBest;
61556   }
61557   return 0;
61558 }
61559
61560 /*
61561 ** Free all resources held by the schema structure. The void* argument points
61562 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the 
61563 ** pointer itself, it just cleans up subsiduary resources (i.e. the contents
61564 ** of the schema hash tables).
61565 **
61566 ** The Schema.cache_size variable is not cleared.
61567 */
61568 SQLITE_PRIVATE void sqlite3SchemaFree(void *p){
61569   Hash temp1;
61570   Hash temp2;
61571   HashElem *pElem;
61572   Schema *pSchema = (Schema *)p;
61573
61574   temp1 = pSchema->tblHash;
61575   temp2 = pSchema->trigHash;
61576   sqlite3HashInit(&pSchema->trigHash, SQLITE_HASH_STRING, 0);
61577   sqlite3HashClear(&pSchema->aFKey);
61578   sqlite3HashClear(&pSchema->idxHash);
61579   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
61580     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
61581   }
61582   sqlite3HashClear(&temp2);
61583   sqlite3HashInit(&pSchema->tblHash, SQLITE_HASH_STRING, 0);
61584   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
61585     Table *pTab = sqliteHashData(pElem);
61586     sqlite3DeleteTable(pTab);
61587   }
61588   sqlite3HashClear(&temp1);
61589   pSchema->pSeqTab = 0;
61590   pSchema->flags &= ~DB_SchemaLoaded;
61591 }
61592
61593 /*
61594 ** Find and return the schema associated with a BTree.  Create
61595 ** a new one if necessary.
61596 */
61597 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
61598   Schema * p;
61599   if( pBt ){
61600     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaFree);
61601   }else{
61602     p = (Schema *)sqlite3MallocZero(sizeof(Schema));
61603   }
61604   if( !p ){
61605     db->mallocFailed = 1;
61606   }else if ( 0==p->file_format ){
61607     sqlite3HashInit(&p->tblHash, SQLITE_HASH_STRING, 0);
61608     sqlite3HashInit(&p->idxHash, SQLITE_HASH_STRING, 0);
61609     sqlite3HashInit(&p->trigHash, SQLITE_HASH_STRING, 0);
61610     sqlite3HashInit(&p->aFKey, SQLITE_HASH_STRING, 1);
61611     p->enc = SQLITE_UTF8;
61612   }
61613   return p;
61614 }
61615
61616 /************** End of callback.c ********************************************/
61617 /************** Begin file delete.c ******************************************/
61618 /*
61619 ** 2001 September 15
61620 **
61621 ** The author disclaims copyright to this source code.  In place of
61622 ** a legal notice, here is a blessing:
61623 **
61624 **    May you do good and not evil.
61625 **    May you find forgiveness for yourself and forgive others.
61626 **    May you share freely, never taking more than you give.
61627 **
61628 *************************************************************************
61629 ** This file contains C code routines that are called by the parser
61630 ** in order to generate code for DELETE FROM statements.
61631 **
61632 ** $Id: delete.c,v 1.175 2008/09/01 21:59:43 shane Exp $
61633 */
61634
61635 /*
61636 ** Look up every table that is named in pSrc.  If any table is not found,
61637 ** add an error message to pParse->zErrMsg and return NULL.  If all tables
61638 ** are found, return a pointer to the last table.
61639 */
61640 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
61641   Table *pTab = 0;
61642   int i;
61643   struct SrcList_item *pItem;
61644   for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){
61645     pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
61646     sqlite3DeleteTable(pItem->pTab);
61647     pItem->pTab = pTab;
61648     if( pTab ){
61649       pTab->nRef++;
61650     }
61651   }
61652   return pTab;
61653 }
61654
61655 /*
61656 ** Check to make sure the given table is writable.  If it is not
61657 ** writable, generate an error message and return 1.  If it is
61658 ** writable return 0;
61659 */
61660 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
61661   if( ((pTab->tabFlags & TF_Readonly)!=0
61662         && (pParse->db->flags & SQLITE_WriteSchema)==0
61663         && pParse->nested==0) 
61664 #ifndef SQLITE_OMIT_VIRTUALTABLE
61665       || (pTab->pMod && pTab->pMod->pModule->xUpdate==0)
61666 #endif
61667   ){
61668     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
61669     return 1;
61670   }
61671 #ifndef SQLITE_OMIT_VIEW
61672   if( !viewOk && pTab->pSelect ){
61673     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
61674     return 1;
61675   }
61676 #endif
61677   return 0;
61678 }
61679
61680 /*
61681 ** Generate code that will open a table for reading.
61682 */
61683 SQLITE_PRIVATE void sqlite3OpenTable(
61684   Parse *p,       /* Generate code into this VDBE */
61685   int iCur,       /* The cursor number of the table */
61686   int iDb,        /* The database index in sqlite3.aDb[] */
61687   Table *pTab,    /* The table to be opened */
61688   int opcode      /* OP_OpenRead or OP_OpenWrite */
61689 ){
61690   Vdbe *v;
61691   if( IsVirtual(pTab) ) return;
61692   v = sqlite3GetVdbe(p);
61693   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
61694   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite), pTab->zName);
61695   sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
61696   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
61697   VdbeComment((v, "%s", pTab->zName));
61698 }
61699
61700
61701 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
61702 /*
61703 ** Evaluate a view and store its result in an ephemeral table.  The
61704 ** pWhere argument is an optional WHERE clause that restricts the
61705 ** set of rows in the view that are to be added to the ephemeral table.
61706 */
61707 SQLITE_PRIVATE void sqlite3MaterializeView(
61708   Parse *pParse,       /* Parsing context */
61709   Table *pView,        /* View definition */
61710   Expr *pWhere,        /* Optional WHERE clause to be added */
61711   int iCur             /* Cursor number for ephemerial table */
61712 ){
61713   SelectDest dest;
61714   Select *pDup;
61715   sqlite3 *db = pParse->db;
61716
61717   pDup = sqlite3SelectDup(db, pView->pSelect);
61718   if( pWhere ){
61719     SrcList *pFrom;
61720     Token viewName;
61721     
61722     pWhere = sqlite3ExprDup(db, pWhere);
61723     viewName.z = (u8*)pView->zName;
61724     viewName.n = (unsigned int)strlen((const char*)viewName.z);
61725     pFrom = sqlite3SrcListAppendFromTerm(pParse, 0, 0, 0, &viewName, pDup, 0,0);
61726     pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
61727   }
61728   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
61729   sqlite3Select(pParse, pDup, &dest);
61730   sqlite3SelectDelete(db, pDup);
61731 }
61732 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
61733
61734
61735 /*
61736 ** Generate code for a DELETE FROM statement.
61737 **
61738 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
61739 **                 \________/       \________________/
61740 **                  pTabList              pWhere
61741 */
61742 SQLITE_PRIVATE void sqlite3DeleteFrom(
61743   Parse *pParse,         /* The parser context */
61744   SrcList *pTabList,     /* The table from which we should delete things */
61745   Expr *pWhere           /* The WHERE clause.  May be null */
61746 ){
61747   Vdbe *v;               /* The virtual database engine */
61748   Table *pTab;           /* The table from which records will be deleted */
61749   const char *zDb;       /* Name of database holding pTab */
61750   int end, addr = 0;     /* A couple addresses of generated code */
61751   int i;                 /* Loop counter */
61752   WhereInfo *pWInfo;     /* Information about the WHERE clause */
61753   Index *pIdx;           /* For looping over indices of the table */
61754   int iCur;              /* VDBE Cursor number for pTab */
61755   sqlite3 *db;           /* Main database structure */
61756   AuthContext sContext;  /* Authorization context */
61757   int oldIdx = -1;       /* Cursor for the OLD table of AFTER triggers */
61758   NameContext sNC;       /* Name context to resolve expressions in */
61759   int iDb;               /* Database number */
61760   int memCnt = 0;        /* Memory cell used for change counting */
61761
61762 #ifndef SQLITE_OMIT_TRIGGER
61763   int isView;                  /* True if attempting to delete from a view */
61764   int triggers_exist = 0;      /* True if any triggers exist */
61765 #endif
61766   int iBeginAfterTrigger;      /* Address of after trigger program */
61767   int iEndAfterTrigger;        /* Exit of after trigger program */
61768   int iBeginBeforeTrigger;     /* Address of before trigger program */
61769   int iEndBeforeTrigger;       /* Exit of before trigger program */
61770   u32 old_col_mask = 0;        /* Mask of OLD.* columns in use */
61771
61772   sContext.pParse = 0;
61773   db = pParse->db;
61774   if( pParse->nErr || db->mallocFailed ){
61775     goto delete_from_cleanup;
61776   }
61777   assert( pTabList->nSrc==1 );
61778
61779   /* Locate the table which we want to delete.  This table has to be
61780   ** put in an SrcList structure because some of the subroutines we
61781   ** will be calling are designed to work with multiple tables and expect
61782   ** an SrcList* parameter instead of just a Table* parameter.
61783   */
61784   pTab = sqlite3SrcListLookup(pParse, pTabList);
61785   if( pTab==0 )  goto delete_from_cleanup;
61786
61787   /* Figure out if we have any triggers and if the table being
61788   ** deleted from is a view
61789   */
61790 #ifndef SQLITE_OMIT_TRIGGER
61791   triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0);
61792   isView = pTab->pSelect!=0;
61793 #else
61794 # define triggers_exist 0
61795 # define isView 0
61796 #endif
61797 #ifdef SQLITE_OMIT_VIEW
61798 # undef isView
61799 # define isView 0
61800 #endif
61801
61802   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
61803     goto delete_from_cleanup;
61804   }
61805   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
61806   assert( iDb<db->nDb );
61807   zDb = db->aDb[iDb].zName;
61808   if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
61809     goto delete_from_cleanup;
61810   }
61811
61812   /* If pTab is really a view, make sure it has been initialized.
61813   */
61814   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
61815     goto delete_from_cleanup;
61816   }
61817
61818   /* Allocate a cursor used to store the old.* data for a trigger.
61819   */
61820   if( triggers_exist ){ 
61821     oldIdx = pParse->nTab++;
61822   }
61823
61824   /* Assign  cursor number to the table and all its indices.
61825   */
61826   assert( pTabList->nSrc==1 );
61827   iCur = pTabList->a[0].iCursor = pParse->nTab++;
61828   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
61829     pParse->nTab++;
61830   }
61831
61832   /* Start the view context
61833   */
61834   if( isView ){
61835     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
61836   }
61837
61838   /* Begin generating code.
61839   */
61840   v = sqlite3GetVdbe(pParse);
61841   if( v==0 ){
61842     goto delete_from_cleanup;
61843   }
61844   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
61845   sqlite3BeginWriteOperation(pParse, triggers_exist, iDb);
61846
61847   if( triggers_exist ){
61848     int orconf = ((pParse->trigStack)?pParse->trigStack->orconf:OE_Default);
61849     int iGoto = sqlite3VdbeAddOp0(v, OP_Goto);
61850     addr = sqlite3VdbeMakeLabel(v);
61851
61852     iBeginBeforeTrigger = sqlite3VdbeCurrentAddr(v);
61853     (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_BEFORE, pTab,
61854         -1, oldIdx, orconf, addr, &old_col_mask, 0);
61855     iEndBeforeTrigger = sqlite3VdbeAddOp0(v, OP_Goto);
61856
61857     iBeginAfterTrigger = sqlite3VdbeCurrentAddr(v);
61858     (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_AFTER, pTab, -1,
61859         oldIdx, orconf, addr, &old_col_mask, 0);
61860     iEndAfterTrigger = sqlite3VdbeAddOp0(v, OP_Goto);
61861
61862     sqlite3VdbeJumpHere(v, iGoto);
61863   }
61864
61865   /* If we are trying to delete from a view, realize that view into
61866   ** a ephemeral table.
61867   */
61868 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
61869   if( isView ){
61870     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
61871   }
61872 #endif
61873
61874   /* Resolve the column names in the WHERE clause.
61875   */
61876   memset(&sNC, 0, sizeof(sNC));
61877   sNC.pParse = pParse;
61878   sNC.pSrcList = pTabList;
61879   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
61880     goto delete_from_cleanup;
61881   }
61882
61883   /* Initialize the counter of the number of rows deleted, if
61884   ** we are counting rows.
61885   */
61886   if( db->flags & SQLITE_CountRows ){
61887     memCnt = ++pParse->nMem;
61888     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
61889   }
61890
61891   /* Special case: A DELETE without a WHERE clause deletes everything.
61892   ** It is easier just to erase the whole table.  Note, however, that
61893   ** this means that the row change count will be incorrect.
61894   */
61895   if( pWhere==0 && !triggers_exist && !IsVirtual(pTab) ){
61896     if( db->flags & SQLITE_CountRows ){
61897       /* If counting rows deleted, just count the total number of
61898       ** entries in the table. */
61899       int addr2;
61900       if( !isView ){
61901         sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
61902       }
61903       sqlite3VdbeAddOp2(v, OP_Rewind, iCur, sqlite3VdbeCurrentAddr(v)+2);
61904       addr2 = sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
61905       sqlite3VdbeAddOp2(v, OP_Next, iCur, addr2);
61906       sqlite3VdbeAddOp1(v, OP_Close, iCur);
61907     }
61908     if( !isView ){
61909       sqlite3VdbeAddOp2(v, OP_Clear, pTab->tnum, iDb);
61910       if( !pParse->nested ){
61911         sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
61912       }
61913       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
61914         assert( pIdx->pSchema==pTab->pSchema );
61915         sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
61916       }
61917     }
61918   } 
61919   /* The usual case: There is a WHERE clause so we have to scan through
61920   ** the table and pick which records to delete.
61921   */
61922   else{
61923     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
61924
61925     /* Begin the database scan
61926     */
61927     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0);
61928     if( pWInfo==0 ) goto delete_from_cleanup;
61929
61930     /* Remember the rowid of every item to be deleted.
61931     */
61932     sqlite3VdbeAddOp2(v, IsVirtual(pTab) ? OP_VRowid : OP_Rowid, iCur, iRowid);
61933     sqlite3VdbeAddOp1(v, OP_FifoWrite, iRowid);
61934     if( db->flags & SQLITE_CountRows ){
61935       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
61936     }
61937
61938     /* End the database scan loop.
61939     */
61940     sqlite3WhereEnd(pWInfo);
61941
61942     /* Open the pseudo-table used to store OLD if there are triggers.
61943     */
61944     if( triggers_exist ){
61945       sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
61946       sqlite3VdbeAddOp1(v, OP_OpenPseudo, oldIdx);
61947     }
61948
61949     /* Delete every item whose key was written to the list during the
61950     ** database scan.  We have to delete items after the scan is complete
61951     ** because deleting an item can change the scan order.
61952     */
61953     end = sqlite3VdbeMakeLabel(v);
61954
61955     if( !isView ){
61956       /* Open cursors for the table we are deleting from and 
61957       ** all its indices.
61958       */
61959       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
61960     }
61961
61962     /* This is the beginning of the delete loop. If a trigger encounters
61963     ** an IGNORE constraint, it jumps back to here.
61964     */
61965     if( triggers_exist ){
61966       sqlite3VdbeResolveLabel(v, addr);
61967     }
61968     addr = sqlite3VdbeAddOp2(v, OP_FifoRead, iRowid, end);
61969
61970     if( triggers_exist ){
61971       int iData = ++pParse->nMem;   /* For storing row data of OLD table */
61972
61973       /* If the record is no longer present in the table, jump to the
61974       ** next iteration of the loop through the contents of the fifo.
61975       */
61976       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, iRowid);
61977
61978       /* Populate the OLD.* pseudo-table */
61979       if( old_col_mask ){
61980         sqlite3VdbeAddOp2(v, OP_RowData, iCur, iData);
61981       }else{
61982         sqlite3VdbeAddOp2(v, OP_Null, 0, iData);
61983       }
61984       sqlite3VdbeAddOp3(v, OP_Insert, oldIdx, iData, iRowid);
61985
61986       /* Jump back and run the BEFORE triggers */
61987       sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginBeforeTrigger);
61988       sqlite3VdbeJumpHere(v, iEndBeforeTrigger);
61989     }
61990
61991     if( !isView ){
61992       /* Delete the row */
61993 #ifndef SQLITE_OMIT_VIRTUALTABLE
61994       if( IsVirtual(pTab) ){
61995         const char *pVtab = (const char *)pTab->pVtab;
61996         sqlite3VtabMakeWritable(pParse, pTab);
61997         sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVtab, P4_VTAB);
61998       }else
61999 #endif
62000       {
62001         sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, pParse->nested==0);
62002       }
62003     }
62004
62005     /* If there are row triggers, close all cursors then invoke
62006     ** the AFTER triggers
62007     */
62008     if( triggers_exist ){
62009       /* Jump back and run the AFTER triggers */
62010       sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginAfterTrigger);
62011       sqlite3VdbeJumpHere(v, iEndAfterTrigger);
62012     }
62013
62014     /* End of the delete loop */
62015     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
62016     sqlite3VdbeResolveLabel(v, end);
62017
62018     /* Close the cursors after the loop if there are no row triggers */
62019     if( !isView  && !IsVirtual(pTab) ){
62020       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
62021         sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
62022       }
62023       sqlite3VdbeAddOp1(v, OP_Close, iCur);
62024     }
62025   }
62026
62027   /*
62028   ** Return the number of rows that were deleted. If this routine is 
62029   ** generating code because of a call to sqlite3NestedParse(), do not
62030   ** invoke the callback function.
62031   */
62032   if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
62033     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
62034     sqlite3VdbeSetNumCols(v, 1);
62035     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", P4_STATIC);
62036   }
62037
62038 delete_from_cleanup:
62039   sqlite3AuthContextPop(&sContext);
62040   sqlite3SrcListDelete(db, pTabList);
62041   sqlite3ExprDelete(db, pWhere);
62042   return;
62043 }
62044
62045 /*
62046 ** This routine generates VDBE code that causes a single row of a
62047 ** single table to be deleted.
62048 **
62049 ** The VDBE must be in a particular state when this routine is called.
62050 ** These are the requirements:
62051 **
62052 **   1.  A read/write cursor pointing to pTab, the table containing the row
62053 **       to be deleted, must be opened as cursor number "base".
62054 **
62055 **   2.  Read/write cursors for all indices of pTab must be open as
62056 **       cursor number base+i for the i-th index.
62057 **
62058 **   3.  The record number of the row to be deleted must be stored in
62059 **       memory cell iRowid.
62060 **
62061 ** This routine pops the top of the stack to remove the record number
62062 ** and then generates code to remove both the table record and all index
62063 ** entries that point to that record.
62064 */
62065 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
62066   Parse *pParse,     /* Parsing context */
62067   Table *pTab,       /* Table containing the row to be deleted */
62068   int iCur,          /* Cursor number for the table */
62069   int iRowid,        /* Memory cell that contains the rowid to delete */
62070   int count          /* Increment the row change counter */
62071 ){
62072   int addr;
62073   Vdbe *v;
62074
62075   v = pParse->pVdbe;
62076   addr = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowid);
62077   sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
62078   sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
62079   if( count ){
62080     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
62081   }
62082   sqlite3VdbeJumpHere(v, addr);
62083 }
62084
62085 /*
62086 ** This routine generates VDBE code that causes the deletion of all
62087 ** index entries associated with a single row of a single table.
62088 **
62089 ** The VDBE must be in a particular state when this routine is called.
62090 ** These are the requirements:
62091 **
62092 **   1.  A read/write cursor pointing to pTab, the table containing the row
62093 **       to be deleted, must be opened as cursor number "iCur".
62094 **
62095 **   2.  Read/write cursors for all indices of pTab must be open as
62096 **       cursor number iCur+i for the i-th index.
62097 **
62098 **   3.  The "iCur" cursor must be pointing to the row that is to be
62099 **       deleted.
62100 */
62101 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
62102   Parse *pParse,     /* Parsing and code generating context */
62103   Table *pTab,       /* Table containing the row to be deleted */
62104   int iCur,          /* Cursor number for the table */
62105   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
62106 ){
62107   int i;
62108   Index *pIdx;
62109   int r1;
62110
62111   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
62112     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
62113     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
62114     sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
62115   }
62116 }
62117
62118 /*
62119 ** Generate code that will assemble an index key and put it in register
62120 ** regOut.  The key with be for index pIdx which is an index on pTab.
62121 ** iCur is the index of a cursor open on the pTab table and pointing to
62122 ** the entry that needs indexing.
62123 **
62124 ** Return a register number which is the first in a block of
62125 ** registers that holds the elements of the index key.  The
62126 ** block of registers has already been deallocated by the time
62127 ** this routine returns.
62128 */
62129 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
62130   Parse *pParse,     /* Parsing context */
62131   Index *pIdx,       /* The index for which to generate a key */
62132   int iCur,          /* Cursor number for the pIdx->pTable table */
62133   int regOut,        /* Write the new index key to this register */
62134   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
62135 ){
62136   Vdbe *v = pParse->pVdbe;
62137   int j;
62138   Table *pTab = pIdx->pTable;
62139   int regBase;
62140   int nCol;
62141
62142   nCol = pIdx->nColumn;
62143   regBase = sqlite3GetTempRange(pParse, nCol+1);
62144   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
62145   for(j=0; j<nCol; j++){
62146     int idx = pIdx->aiColumn[j];
62147     if( idx==pTab->iPKey ){
62148       sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
62149     }else{
62150       sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
62151       sqlite3ColumnDefault(v, pTab, idx);
62152     }
62153   }
62154   if( doMakeRec ){
62155     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
62156     sqlite3IndexAffinityStr(v, pIdx);
62157     sqlite3ExprCacheAffinityChange(pParse, regBase, nCol+1);
62158   }
62159   sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
62160   return regBase;
62161 }
62162
62163 /* Make sure "isView" gets undefined in case this file becomes part of
62164 ** the amalgamation - so that subsequent files do not see isView as a
62165 ** macro. */
62166 #undef isView
62167
62168 /************** End of delete.c **********************************************/
62169 /************** Begin file func.c ********************************************/
62170 /*
62171 ** 2002 February 23
62172 **
62173 ** The author disclaims copyright to this source code.  In place of
62174 ** a legal notice, here is a blessing:
62175 **
62176 **    May you do good and not evil.
62177 **    May you find forgiveness for yourself and forgive others.
62178 **    May you share freely, never taking more than you give.
62179 **
62180 *************************************************************************
62181 ** This file contains the C functions that implement various SQL
62182 ** functions of SQLite.  
62183 **
62184 ** There is only one exported symbol in this file - the function
62185 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
62186 ** All other code has file scope.
62187 **
62188 ** $Id: func.c,v 1.203 2008/09/03 17:11:16 drh Exp $
62189 */
62190
62191 /*
62192 ** Return the collating function associated with a function.
62193 */
62194 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
62195   return context->pColl;
62196 }
62197
62198 /*
62199 ** Implementation of the non-aggregate min() and max() functions
62200 */
62201 static void minmaxFunc(
62202   sqlite3_context *context,
62203   int argc,
62204   sqlite3_value **argv
62205 ){
62206   int i;
62207   int mask;    /* 0 for min() or 0xffffffff for max() */
62208   int iBest;
62209   CollSeq *pColl;
62210
62211   if( argc==0 ) return;
62212   mask = sqlite3_user_data(context)==0 ? 0 : -1;
62213   pColl = sqlite3GetFuncCollSeq(context);
62214   assert( pColl );
62215   assert( mask==-1 || mask==0 );
62216   iBest = 0;
62217   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
62218   for(i=1; i<argc; i++){
62219     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
62220     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
62221       iBest = i;
62222     }
62223   }
62224   sqlite3_result_value(context, argv[iBest]);
62225 }
62226
62227 /*
62228 ** Return the type of the argument.
62229 */
62230 static void typeofFunc(
62231   sqlite3_context *context,
62232   int argc,
62233   sqlite3_value **argv
62234 ){
62235   const char *z = 0;
62236   switch( sqlite3_value_type(argv[0]) ){
62237     case SQLITE_NULL:    z = "null";    break;
62238     case SQLITE_INTEGER: z = "integer"; break;
62239     case SQLITE_TEXT:    z = "text";    break;
62240     case SQLITE_FLOAT:   z = "real";    break;
62241     case SQLITE_BLOB:    z = "blob";    break;
62242   }
62243   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
62244 }
62245
62246
62247 /*
62248 ** Implementation of the length() function
62249 */
62250 static void lengthFunc(
62251   sqlite3_context *context,
62252   int argc,
62253   sqlite3_value **argv
62254 ){
62255   int len;
62256
62257   assert( argc==1 );
62258   switch( sqlite3_value_type(argv[0]) ){
62259     case SQLITE_BLOB:
62260     case SQLITE_INTEGER:
62261     case SQLITE_FLOAT: {
62262       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
62263       break;
62264     }
62265     case SQLITE_TEXT: {
62266       const unsigned char *z = sqlite3_value_text(argv[0]);
62267       if( z==0 ) return;
62268       len = 0;
62269       while( *z ){
62270         len++;
62271         SQLITE_SKIP_UTF8(z);
62272       }
62273       sqlite3_result_int(context, len);
62274       break;
62275     }
62276     default: {
62277       sqlite3_result_null(context);
62278       break;
62279     }
62280   }
62281 }
62282
62283 /*
62284 ** Implementation of the abs() function
62285 */
62286 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
62287   assert( argc==1 );
62288   switch( sqlite3_value_type(argv[0]) ){
62289     case SQLITE_INTEGER: {
62290       i64 iVal = sqlite3_value_int64(argv[0]);
62291       if( iVal<0 ){
62292         if( (iVal<<1)==0 ){
62293           sqlite3_result_error(context, "integer overflow", -1);
62294           return;
62295         }
62296         iVal = -iVal;
62297       } 
62298       sqlite3_result_int64(context, iVal);
62299       break;
62300     }
62301     case SQLITE_NULL: {
62302       sqlite3_result_null(context);
62303       break;
62304     }
62305     default: {
62306       double rVal = sqlite3_value_double(argv[0]);
62307       if( rVal<0 ) rVal = -rVal;
62308       sqlite3_result_double(context, rVal);
62309       break;
62310     }
62311   }
62312 }
62313
62314 /*
62315 ** Implementation of the substr() function.
62316 **
62317 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
62318 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
62319 ** of x.  If x is text, then we actually count UTF-8 characters.
62320 ** If x is a blob, then we count bytes.
62321 **
62322 ** If p1 is negative, then we begin abs(p1) from the end of x[].
62323 */
62324 static void substrFunc(
62325   sqlite3_context *context,
62326   int argc,
62327   sqlite3_value **argv
62328 ){
62329   const unsigned char *z;
62330   const unsigned char *z2;
62331   int len;
62332   int p0type;
62333   i64 p1, p2;
62334
62335   assert( argc==3 || argc==2 );
62336   p0type = sqlite3_value_type(argv[0]);
62337   if( p0type==SQLITE_BLOB ){
62338     len = sqlite3_value_bytes(argv[0]);
62339     z = sqlite3_value_blob(argv[0]);
62340     if( z==0 ) return;
62341     assert( len==sqlite3_value_bytes(argv[0]) );
62342   }else{
62343     z = sqlite3_value_text(argv[0]);
62344     if( z==0 ) return;
62345     len = 0;
62346     for(z2=z; *z2; len++){
62347       SQLITE_SKIP_UTF8(z2);
62348     }
62349   }
62350   p1 = sqlite3_value_int(argv[1]);
62351   if( argc==3 ){
62352     p2 = sqlite3_value_int(argv[2]);
62353   }else{
62354     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
62355   }
62356   if( p1<0 ){
62357     p1 += len;
62358     if( p1<0 ){
62359       p2 += p1;
62360       p1 = 0;
62361     }
62362   }else if( p1>0 ){
62363     p1--;
62364   }
62365   if( p1+p2>len ){
62366     p2 = len-p1;
62367   }
62368   if( p0type!=SQLITE_BLOB ){
62369     while( *z && p1 ){
62370       SQLITE_SKIP_UTF8(z);
62371       p1--;
62372     }
62373     for(z2=z; *z2 && p2; p2--){
62374       SQLITE_SKIP_UTF8(z2);
62375     }
62376     sqlite3_result_text(context, (char*)z, z2-z, SQLITE_TRANSIENT);
62377   }else{
62378     if( p2<0 ) p2 = 0;
62379     sqlite3_result_blob(context, (char*)&z[p1], p2, SQLITE_TRANSIENT);
62380   }
62381 }
62382
62383 /*
62384 ** Implementation of the round() function
62385 */
62386 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
62387   int n = 0;
62388   double r;
62389   char zBuf[500];  /* larger than the %f representation of the largest double */
62390   assert( argc==1 || argc==2 );
62391   if( argc==2 ){
62392     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
62393     n = sqlite3_value_int(argv[1]);
62394     if( n>30 ) n = 30;
62395     if( n<0 ) n = 0;
62396   }
62397   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
62398   r = sqlite3_value_double(argv[0]);
62399   sqlite3_snprintf(sizeof(zBuf),zBuf,"%.*f",n,r);
62400   sqlite3AtoF(zBuf, &r);
62401   sqlite3_result_double(context, r);
62402 }
62403
62404 /*
62405 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
62406 ** allocation fails, call sqlite3_result_error_nomem() to notify
62407 ** the database handle that malloc() has failed.
62408 */
62409 static void *contextMalloc(sqlite3_context *context, i64 nByte){
62410   char *z;
62411   if( nByte>sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH] ){
62412     sqlite3_result_error_toobig(context);
62413     z = 0;
62414   }else{
62415     z = sqlite3Malloc(nByte);
62416     if( !z && nByte>0 ){
62417       sqlite3_result_error_nomem(context);
62418     }
62419   }
62420   return z;
62421 }
62422
62423 /*
62424 ** Implementation of the upper() and lower() SQL functions.
62425 */
62426 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
62427   char *z1;
62428   const char *z2;
62429   int i, n;
62430   if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
62431   z2 = (char*)sqlite3_value_text(argv[0]);
62432   n = sqlite3_value_bytes(argv[0]);
62433   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
62434   assert( z2==(char*)sqlite3_value_text(argv[0]) );
62435   if( z2 ){
62436     z1 = contextMalloc(context, ((i64)n)+1);
62437     if( z1 ){
62438       memcpy(z1, z2, n+1);
62439       for(i=0; z1[i]; i++){
62440         z1[i] = toupper(z1[i]);
62441       }
62442       sqlite3_result_text(context, z1, -1, sqlite3_free);
62443     }
62444   }
62445 }
62446 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
62447   char *z1;
62448   const char *z2;
62449   int i, n;
62450   if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
62451   z2 = (char*)sqlite3_value_text(argv[0]);
62452   n = sqlite3_value_bytes(argv[0]);
62453   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
62454   assert( z2==(char*)sqlite3_value_text(argv[0]) );
62455   if( z2 ){
62456     z1 = contextMalloc(context, ((i64)n)+1);
62457     if( z1 ){
62458       memcpy(z1, z2, n+1);
62459       for(i=0; z1[i]; i++){
62460         z1[i] = tolower(z1[i]);
62461       }
62462       sqlite3_result_text(context, z1, -1, sqlite3_free);
62463     }
62464   }
62465 }
62466
62467 /*
62468 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  
62469 ** All three do the same thing.  They return the first non-NULL
62470 ** argument.
62471 */
62472 static void ifnullFunc(
62473   sqlite3_context *context,
62474   int argc,
62475   sqlite3_value **argv
62476 ){
62477   int i;
62478   for(i=0; i<argc; i++){
62479     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
62480       sqlite3_result_value(context, argv[i]);
62481       break;
62482     }
62483   }
62484 }
62485
62486 /*
62487 ** Implementation of random().  Return a random integer.  
62488 */
62489 static void randomFunc(
62490   sqlite3_context *context,
62491   int argc,
62492   sqlite3_value **argv
62493 ){
62494   sqlite_int64 r;
62495   sqlite3_randomness(sizeof(r), &r);
62496   if( (r<<1)==0 ) r = 0;  /* Prevent 0x8000.... as the result so that we */
62497                           /* can always do abs() of the result */
62498   sqlite3_result_int64(context, r);
62499 }
62500
62501 /*
62502 ** Implementation of randomblob(N).  Return a random blob
62503 ** that is N bytes long.
62504 */
62505 static void randomBlob(
62506   sqlite3_context *context,
62507   int argc,
62508   sqlite3_value **argv
62509 ){
62510   int n;
62511   unsigned char *p;
62512   assert( argc==1 );
62513   n = sqlite3_value_int(argv[0]);
62514   if( n<1 ){
62515     n = 1;
62516   }
62517   p = contextMalloc(context, n);
62518   if( p ){
62519     sqlite3_randomness(n, p);
62520     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
62521   }
62522 }
62523
62524 /*
62525 ** Implementation of the last_insert_rowid() SQL function.  The return
62526 ** value is the same as the sqlite3_last_insert_rowid() API function.
62527 */
62528 static void last_insert_rowid(
62529   sqlite3_context *context, 
62530   int arg, 
62531   sqlite3_value **argv
62532 ){
62533   sqlite3 *db = sqlite3_context_db_handle(context);
62534   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
62535 }
62536
62537 /*
62538 ** Implementation of the changes() SQL function.  The return value is the
62539 ** same as the sqlite3_changes() API function.
62540 */
62541 static void changes(
62542   sqlite3_context *context,
62543   int arg,
62544   sqlite3_value **argv
62545 ){
62546   sqlite3 *db = sqlite3_context_db_handle(context);
62547   sqlite3_result_int(context, sqlite3_changes(db));
62548 }
62549
62550 /*
62551 ** Implementation of the total_changes() SQL function.  The return value is
62552 ** the same as the sqlite3_total_changes() API function.
62553 */
62554 static void total_changes(
62555   sqlite3_context *context,
62556   int arg,
62557   sqlite3_value **argv
62558 ){
62559   sqlite3 *db = sqlite3_context_db_handle(context);
62560   sqlite3_result_int(context, sqlite3_total_changes(db));
62561 }
62562
62563 /*
62564 ** A structure defining how to do GLOB-style comparisons.
62565 */
62566 struct compareInfo {
62567   u8 matchAll;
62568   u8 matchOne;
62569   u8 matchSet;
62570   u8 noCase;
62571 };
62572
62573 /*
62574 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
62575 ** character is exactly one byte in size.  Also, all characters are
62576 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
62577 ** whereas only characters less than 0x80 do in ASCII.
62578 */
62579 #if defined(SQLITE_EBCDIC)
62580 # define sqlite3Utf8Read(A,B,C)  (*(A++))
62581 # define GlogUpperToLower(A)     A = sqlite3UpperToLower[A]
62582 #else
62583 # define GlogUpperToLower(A)     if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
62584 #endif
62585
62586 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
62587 /* The correct SQL-92 behavior is for the LIKE operator to ignore
62588 ** case.  Thus  'a' LIKE 'A' would be true. */
62589 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
62590 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
62591 ** is case sensitive causing 'a' LIKE 'A' to be false */
62592 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
62593
62594 /*
62595 ** Compare two UTF-8 strings for equality where the first string can
62596 ** potentially be a "glob" expression.  Return true (1) if they
62597 ** are the same and false (0) if they are different.
62598 **
62599 ** Globbing rules:
62600 **
62601 **      '*'       Matches any sequence of zero or more characters.
62602 **
62603 **      '?'       Matches exactly one character.
62604 **
62605 **     [...]      Matches one character from the enclosed list of
62606 **                characters.
62607 **
62608 **     [^...]     Matches one character not in the enclosed list.
62609 **
62610 ** With the [...] and [^...] matching, a ']' character can be included
62611 ** in the list by making it the first character after '[' or '^'.  A
62612 ** range of characters can be specified using '-'.  Example:
62613 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
62614 ** it the last character in the list.
62615 **
62616 ** This routine is usually quick, but can be N**2 in the worst case.
62617 **
62618 ** Hints: to match '*' or '?', put them in "[]".  Like this:
62619 **
62620 **         abc[*]xyz        Matches "abc*xyz" only
62621 */
62622 static int patternCompare(
62623   const u8 *zPattern,              /* The glob pattern */
62624   const u8 *zString,               /* The string to compare against the glob */
62625   const struct compareInfo *pInfo, /* Information about how to do the compare */
62626   const int esc                    /* The escape character */
62627 ){
62628   int c, c2;
62629   int invert;
62630   int seen;
62631   u8 matchOne = pInfo->matchOne;
62632   u8 matchAll = pInfo->matchAll;
62633   u8 matchSet = pInfo->matchSet;
62634   u8 noCase = pInfo->noCase; 
62635   int prevEscape = 0;     /* True if the previous character was 'escape' */
62636
62637   while( (c = sqlite3Utf8Read(zPattern,0,&zPattern))!=0 ){
62638     if( !prevEscape && c==matchAll ){
62639       while( (c=sqlite3Utf8Read(zPattern,0,&zPattern)) == matchAll
62640                || c == matchOne ){
62641         if( c==matchOne && sqlite3Utf8Read(zString, 0, &zString)==0 ){
62642           return 0;
62643         }
62644       }
62645       if( c==0 ){
62646         return 1;
62647       }else if( c==esc ){
62648         c = sqlite3Utf8Read(zPattern, 0, &zPattern);
62649         if( c==0 ){
62650           return 0;
62651         }
62652       }else if( c==matchSet ){
62653         assert( esc==0 );         /* This is GLOB, not LIKE */
62654         assert( matchSet<0x80 );  /* '[' is a single-byte character */
62655         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
62656           SQLITE_SKIP_UTF8(zString);
62657         }
62658         return *zString!=0;
62659       }
62660       while( (c2 = sqlite3Utf8Read(zString,0,&zString))!=0 ){
62661         if( noCase ){
62662           GlogUpperToLower(c2);
62663           GlogUpperToLower(c);
62664           while( c2 != 0 && c2 != c ){
62665             c2 = sqlite3Utf8Read(zString, 0, &zString);
62666             GlogUpperToLower(c2);
62667           }
62668         }else{
62669           while( c2 != 0 && c2 != c ){
62670             c2 = sqlite3Utf8Read(zString, 0, &zString);
62671           }
62672         }
62673         if( c2==0 ) return 0;
62674         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
62675       }
62676       return 0;
62677     }else if( !prevEscape && c==matchOne ){
62678       if( sqlite3Utf8Read(zString, 0, &zString)==0 ){
62679         return 0;
62680       }
62681     }else if( c==matchSet ){
62682       int prior_c = 0;
62683       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
62684       seen = 0;
62685       invert = 0;
62686       c = sqlite3Utf8Read(zString, 0, &zString);
62687       if( c==0 ) return 0;
62688       c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
62689       if( c2=='^' ){
62690         invert = 1;
62691         c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
62692       }
62693       if( c2==']' ){
62694         if( c==']' ) seen = 1;
62695         c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
62696       }
62697       while( c2 && c2!=']' ){
62698         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
62699           c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
62700           if( c>=prior_c && c<=c2 ) seen = 1;
62701           prior_c = 0;
62702         }else{
62703           if( c==c2 ){
62704             seen = 1;
62705           }
62706           prior_c = c2;
62707         }
62708         c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
62709       }
62710       if( c2==0 || (seen ^ invert)==0 ){
62711         return 0;
62712       }
62713     }else if( esc==c && !prevEscape ){
62714       prevEscape = 1;
62715     }else{
62716       c2 = sqlite3Utf8Read(zString, 0, &zString);
62717       if( noCase ){
62718         GlogUpperToLower(c);
62719         GlogUpperToLower(c2);
62720       }
62721       if( c!=c2 ){
62722         return 0;
62723       }
62724       prevEscape = 0;
62725     }
62726   }
62727   return *zString==0;
62728 }
62729
62730 /*
62731 ** Count the number of times that the LIKE operator (or GLOB which is
62732 ** just a variation of LIKE) gets called.  This is used for testing
62733 ** only.
62734 */
62735 #ifdef SQLITE_TEST
62736 SQLITE_API int sqlite3_like_count = 0;
62737 #endif
62738
62739
62740 /*
62741 ** Implementation of the like() SQL function.  This function implements
62742 ** the build-in LIKE operator.  The first argument to the function is the
62743 ** pattern and the second argument is the string.  So, the SQL statements:
62744 **
62745 **       A LIKE B
62746 **
62747 ** is implemented as like(B,A).
62748 **
62749 ** This same function (with a different compareInfo structure) computes
62750 ** the GLOB operator.
62751 */
62752 static void likeFunc(
62753   sqlite3_context *context, 
62754   int argc, 
62755   sqlite3_value **argv
62756 ){
62757   const unsigned char *zA, *zB;
62758   int escape = 0;
62759   sqlite3 *db = sqlite3_context_db_handle(context);
62760
62761   zB = sqlite3_value_text(argv[0]);
62762   zA = sqlite3_value_text(argv[1]);
62763
62764   /* Limit the length of the LIKE or GLOB pattern to avoid problems
62765   ** of deep recursion and N*N behavior in patternCompare().
62766   */
62767   if( sqlite3_value_bytes(argv[0]) >
62768         db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
62769     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
62770     return;
62771   }
62772   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
62773
62774   if( argc==3 ){
62775     /* The escape character string must consist of a single UTF-8 character.
62776     ** Otherwise, return an error.
62777     */
62778     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
62779     if( zEsc==0 ) return;
62780     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
62781       sqlite3_result_error(context, 
62782           "ESCAPE expression must be a single character", -1);
62783       return;
62784     }
62785     escape = sqlite3Utf8Read(zEsc, 0, &zEsc);
62786   }
62787   if( zA && zB ){
62788     struct compareInfo *pInfo = sqlite3_user_data(context);
62789 #ifdef SQLITE_TEST
62790     sqlite3_like_count++;
62791 #endif
62792     
62793     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
62794   }
62795 }
62796
62797 /*
62798 ** Implementation of the NULLIF(x,y) function.  The result is the first
62799 ** argument if the arguments are different.  The result is NULL if the
62800 ** arguments are equal to each other.
62801 */
62802 static void nullifFunc(
62803   sqlite3_context *context,
62804   int argc,
62805   sqlite3_value **argv
62806 ){
62807   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
62808   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
62809     sqlite3_result_value(context, argv[0]);
62810   }
62811 }
62812
62813 /*
62814 ** Implementation of the VERSION(*) function.  The result is the version
62815 ** of the SQLite library that is running.
62816 */
62817 static void versionFunc(
62818   sqlite3_context *context,
62819   int argc,
62820   sqlite3_value **argv
62821 ){
62822   sqlite3_result_text(context, sqlite3_version, -1, SQLITE_STATIC);
62823 }
62824
62825 /* Array for converting from half-bytes (nybbles) into ASCII hex
62826 ** digits. */
62827 static const char hexdigits[] = {
62828   '0', '1', '2', '3', '4', '5', '6', '7',
62829   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
62830 };
62831
62832 /*
62833 ** EXPERIMENTAL - This is not an official function.  The interface may
62834 ** change.  This function may disappear.  Do not write code that depends
62835 ** on this function.
62836 **
62837 ** Implementation of the QUOTE() function.  This function takes a single
62838 ** argument.  If the argument is numeric, the return value is the same as
62839 ** the argument.  If the argument is NULL, the return value is the string
62840 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
62841 ** single-quote escapes.
62842 */
62843 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
62844   if( argc<1 ) return;
62845   switch( sqlite3_value_type(argv[0]) ){
62846     case SQLITE_NULL: {
62847       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
62848       break;
62849     }
62850     case SQLITE_INTEGER:
62851     case SQLITE_FLOAT: {
62852       sqlite3_result_value(context, argv[0]);
62853       break;
62854     }
62855     case SQLITE_BLOB: {
62856       char *zText = 0;
62857       char const *zBlob = sqlite3_value_blob(argv[0]);
62858       int nBlob = sqlite3_value_bytes(argv[0]);
62859       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
62860       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 
62861       if( zText ){
62862         int i;
62863         for(i=0; i<nBlob; i++){
62864           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
62865           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
62866         }
62867         zText[(nBlob*2)+2] = '\'';
62868         zText[(nBlob*2)+3] = '\0';
62869         zText[0] = 'X';
62870         zText[1] = '\'';
62871         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
62872         sqlite3_free(zText);
62873       }
62874       break;
62875     }
62876     case SQLITE_TEXT: {
62877       int i,j;
62878       u64 n;
62879       const unsigned char *zArg = sqlite3_value_text(argv[0]);
62880       char *z;
62881
62882       if( zArg==0 ) return;
62883       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
62884       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
62885       if( z ){
62886         z[0] = '\'';
62887         for(i=0, j=1; zArg[i]; i++){
62888           z[j++] = zArg[i];
62889           if( zArg[i]=='\'' ){
62890             z[j++] = '\'';
62891           }
62892         }
62893         z[j++] = '\'';
62894         z[j] = 0;
62895         sqlite3_result_text(context, z, j, sqlite3_free);
62896       }
62897     }
62898   }
62899 }
62900
62901 /*
62902 ** The hex() function.  Interpret the argument as a blob.  Return
62903 ** a hexadecimal rendering as text.
62904 */
62905 static void hexFunc(
62906   sqlite3_context *context,
62907   int argc,
62908   sqlite3_value **argv
62909 ){
62910   int i, n;
62911   const unsigned char *pBlob;
62912   char *zHex, *z;
62913   assert( argc==1 );
62914   pBlob = sqlite3_value_blob(argv[0]);
62915   n = sqlite3_value_bytes(argv[0]);
62916   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
62917   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
62918   if( zHex ){
62919     for(i=0; i<n; i++, pBlob++){
62920       unsigned char c = *pBlob;
62921       *(z++) = hexdigits[(c>>4)&0xf];
62922       *(z++) = hexdigits[c&0xf];
62923     }
62924     *z = 0;
62925     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
62926   }
62927 }
62928
62929 /*
62930 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
62931 */
62932 static void zeroblobFunc(
62933   sqlite3_context *context,
62934   int argc,
62935   sqlite3_value **argv
62936 ){
62937   i64 n;
62938   assert( argc==1 );
62939   n = sqlite3_value_int64(argv[0]);
62940   if( n>SQLITE_MAX_LENGTH ){
62941     sqlite3_result_error_toobig(context);
62942   }else{
62943     sqlite3_result_zeroblob(context, n);
62944   }
62945 }
62946
62947 /*
62948 ** The replace() function.  Three arguments are all strings: call
62949 ** them A, B, and C. The result is also a string which is derived
62950 ** from A by replacing every occurance of B with C.  The match
62951 ** must be exact.  Collating sequences are not used.
62952 */
62953 static void replaceFunc(
62954   sqlite3_context *context,
62955   int argc,
62956   sqlite3_value **argv
62957 ){
62958   const unsigned char *zStr;        /* The input string A */
62959   const unsigned char *zPattern;    /* The pattern string B */
62960   const unsigned char *zRep;        /* The replacement string C */
62961   unsigned char *zOut;              /* The output */
62962   int nStr;                /* Size of zStr */
62963   int nPattern;            /* Size of zPattern */
62964   int nRep;                /* Size of zRep */
62965   i64 nOut;                /* Maximum size of zOut */
62966   int loopLimit;           /* Last zStr[] that might match zPattern[] */
62967   int i, j;                /* Loop counters */
62968
62969   assert( argc==3 );
62970   zStr = sqlite3_value_text(argv[0]);
62971   if( zStr==0 ) return;
62972   nStr = sqlite3_value_bytes(argv[0]);
62973   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
62974   zPattern = sqlite3_value_text(argv[1]);
62975   if( zPattern==0 || zPattern[0]==0 ) return;
62976   nPattern = sqlite3_value_bytes(argv[1]);
62977   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
62978   zRep = sqlite3_value_text(argv[2]);
62979   if( zRep==0 ) return;
62980   nRep = sqlite3_value_bytes(argv[2]);
62981   assert( zRep==sqlite3_value_text(argv[2]) );
62982   nOut = nStr + 1;
62983   assert( nOut<SQLITE_MAX_LENGTH );
62984   zOut = contextMalloc(context, (i64)nOut);
62985   if( zOut==0 ){
62986     return;
62987   }
62988   loopLimit = nStr - nPattern;  
62989   for(i=j=0; i<=loopLimit; i++){
62990     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
62991       zOut[j++] = zStr[i];
62992     }else{
62993       u8 *zOld;
62994       sqlite3 *db = sqlite3_context_db_handle(context);
62995       nOut += nRep - nPattern;
62996       if( nOut>=db->aLimit[SQLITE_LIMIT_LENGTH] ){
62997         sqlite3_result_error_toobig(context);
62998         sqlite3DbFree(db, zOut);
62999         return;
63000       }
63001       zOld = zOut;
63002       zOut = sqlite3_realloc(zOut, (int)nOut);
63003       if( zOut==0 ){
63004         sqlite3_result_error_nomem(context);
63005         sqlite3DbFree(db, zOld);
63006         return;
63007       }
63008       memcpy(&zOut[j], zRep, nRep);
63009       j += nRep;
63010       i += nPattern-1;
63011     }
63012   }
63013   assert( j+nStr-i+1==nOut );
63014   memcpy(&zOut[j], &zStr[i], nStr-i);
63015   j += nStr - i;
63016   assert( j<=nOut );
63017   zOut[j] = 0;
63018   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
63019 }
63020
63021 /*
63022 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
63023 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
63024 */
63025 static void trimFunc(
63026   sqlite3_context *context,
63027   int argc,
63028   sqlite3_value **argv
63029 ){
63030   const unsigned char *zIn;         /* Input string */
63031   const unsigned char *zCharSet;    /* Set of characters to trim */
63032   int nIn;                          /* Number of bytes in input */
63033   int flags;                        /* 1: trimleft  2: trimright  3: trim */
63034   int i;                            /* Loop counter */
63035   unsigned char *aLen;              /* Length of each character in zCharSet */
63036   unsigned char **azChar;           /* Individual characters in zCharSet */
63037   int nChar;                        /* Number of characters in zCharSet */
63038
63039   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
63040     return;
63041   }
63042   zIn = sqlite3_value_text(argv[0]);
63043   if( zIn==0 ) return;
63044   nIn = sqlite3_value_bytes(argv[0]);
63045   assert( zIn==sqlite3_value_text(argv[0]) );
63046   if( argc==1 ){
63047     static const unsigned char lenOne[] = { 1 };
63048     static unsigned char * const azOne[] = { (u8*)" " };
63049     nChar = 1;
63050     aLen = (u8*)lenOne;
63051     azChar = (unsigned char **)azOne;
63052     zCharSet = 0;
63053   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
63054     return;
63055   }else{
63056     const unsigned char *z;
63057     for(z=zCharSet, nChar=0; *z; nChar++){
63058       SQLITE_SKIP_UTF8(z);
63059     }
63060     if( nChar>0 ){
63061       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
63062       if( azChar==0 ){
63063         return;
63064       }
63065       aLen = (unsigned char*)&azChar[nChar];
63066       for(z=zCharSet, nChar=0; *z; nChar++){
63067         azChar[nChar] = (unsigned char *)z;
63068         SQLITE_SKIP_UTF8(z);
63069         aLen[nChar] = z - azChar[nChar];
63070       }
63071     }
63072   }
63073   if( nChar>0 ){
63074     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
63075     if( flags & 1 ){
63076       while( nIn>0 ){
63077         int len;
63078         for(i=0; i<nChar; i++){
63079           len = aLen[i];
63080           if( memcmp(zIn, azChar[i], len)==0 ) break;
63081         }
63082         if( i>=nChar ) break;
63083         zIn += len;
63084         nIn -= len;
63085       }
63086     }
63087     if( flags & 2 ){
63088       while( nIn>0 ){
63089         int len;
63090         for(i=0; i<nChar; i++){
63091           len = aLen[i];
63092           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
63093         }
63094         if( i>=nChar ) break;
63095         nIn -= len;
63096       }
63097     }
63098     if( zCharSet ){
63099       sqlite3_free(azChar);
63100     }
63101   }
63102   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
63103 }
63104
63105
63106 #ifdef SQLITE_SOUNDEX
63107 /*
63108 ** Compute the soundex encoding of a word.
63109 */
63110 static void soundexFunc(
63111   sqlite3_context *context,
63112   int argc,
63113   sqlite3_value **argv
63114 ){
63115   char zResult[8];
63116   const u8 *zIn;
63117   int i, j;
63118   static const unsigned char iCode[] = {
63119     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
63120     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
63121     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
63122     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
63123     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
63124     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
63125     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
63126     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
63127   };
63128   assert( argc==1 );
63129   zIn = (u8*)sqlite3_value_text(argv[0]);
63130   if( zIn==0 ) zIn = (u8*)"";
63131   for(i=0; zIn[i] && !isalpha(zIn[i]); i++){}
63132   if( zIn[i] ){
63133     u8 prevcode = iCode[zIn[i]&0x7f];
63134     zResult[0] = toupper(zIn[i]);
63135     for(j=1; j<4 && zIn[i]; i++){
63136       int code = iCode[zIn[i]&0x7f];
63137       if( code>0 ){
63138         if( code!=prevcode ){
63139           prevcode = code;
63140           zResult[j++] = code + '0';
63141         }
63142       }else{
63143         prevcode = 0;
63144       }
63145     }
63146     while( j<4 ){
63147       zResult[j++] = '0';
63148     }
63149     zResult[j] = 0;
63150     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
63151   }else{
63152     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
63153   }
63154 }
63155 #endif
63156
63157 #ifndef SQLITE_OMIT_LOAD_EXTENSION
63158 /*
63159 ** A function that loads a shared-library extension then returns NULL.
63160 */
63161 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
63162   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
63163   const char *zProc;
63164   sqlite3 *db = sqlite3_context_db_handle(context);
63165   char *zErrMsg = 0;
63166
63167   if( argc==2 ){
63168     zProc = (const char *)sqlite3_value_text(argv[1]);
63169   }else{
63170     zProc = 0;
63171   }
63172   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
63173     sqlite3_result_error(context, zErrMsg, -1);
63174     sqlite3_free(zErrMsg);
63175   }
63176 }
63177 #endif
63178
63179
63180 /*
63181 ** An instance of the following structure holds the context of a
63182 ** sum() or avg() aggregate computation.
63183 */
63184 typedef struct SumCtx SumCtx;
63185 struct SumCtx {
63186   double rSum;      /* Floating point sum */
63187   i64 iSum;         /* Integer sum */   
63188   i64 cnt;          /* Number of elements summed */
63189   u8 overflow;      /* True if integer overflow seen */
63190   u8 approx;        /* True if non-integer value was input to the sum */
63191 };
63192
63193 /*
63194 ** Routines used to compute the sum, average, and total.
63195 **
63196 ** The SUM() function follows the (broken) SQL standard which means
63197 ** that it returns NULL if it sums over no inputs.  TOTAL returns
63198 ** 0.0 in that case.  In addition, TOTAL always returns a float where
63199 ** SUM might return an integer if it never encounters a floating point
63200 ** value.  TOTAL never fails, but SUM might through an exception if
63201 ** it overflows an integer.
63202 */
63203 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
63204   SumCtx *p;
63205   int type;
63206   assert( argc==1 );
63207   p = sqlite3_aggregate_context(context, sizeof(*p));
63208   type = sqlite3_value_numeric_type(argv[0]);
63209   if( p && type!=SQLITE_NULL ){
63210     p->cnt++;
63211     if( type==SQLITE_INTEGER ){
63212       i64 v = sqlite3_value_int64(argv[0]);
63213       p->rSum += v;
63214       if( (p->approx|p->overflow)==0 ){
63215         i64 iNewSum = p->iSum + v;
63216         int s1 = p->iSum >> (sizeof(i64)*8-1);
63217         int s2 = v       >> (sizeof(i64)*8-1);
63218         int s3 = iNewSum >> (sizeof(i64)*8-1);
63219         p->overflow = (s1&s2&~s3) | (~s1&~s2&s3);
63220         p->iSum = iNewSum;
63221       }
63222     }else{
63223       p->rSum += sqlite3_value_double(argv[0]);
63224       p->approx = 1;
63225     }
63226   }
63227 }
63228 static void sumFinalize(sqlite3_context *context){
63229   SumCtx *p;
63230   p = sqlite3_aggregate_context(context, 0);
63231   if( p && p->cnt>0 ){
63232     if( p->overflow ){
63233       sqlite3_result_error(context,"integer overflow",-1);
63234     }else if( p->approx ){
63235       sqlite3_result_double(context, p->rSum);
63236     }else{
63237       sqlite3_result_int64(context, p->iSum);
63238     }
63239   }
63240 }
63241 static void avgFinalize(sqlite3_context *context){
63242   SumCtx *p;
63243   p = sqlite3_aggregate_context(context, 0);
63244   if( p && p->cnt>0 ){
63245     sqlite3_result_double(context, p->rSum/(double)p->cnt);
63246   }
63247 }
63248 static void totalFinalize(sqlite3_context *context){
63249   SumCtx *p;
63250   p = sqlite3_aggregate_context(context, 0);
63251   sqlite3_result_double(context, p ? p->rSum : 0.0);
63252 }
63253
63254 /*
63255 ** The following structure keeps track of state information for the
63256 ** count() aggregate function.
63257 */
63258 typedef struct CountCtx CountCtx;
63259 struct CountCtx {
63260   i64 n;
63261 };
63262
63263 /*
63264 ** Routines to implement the count() aggregate function.
63265 */
63266 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
63267   CountCtx *p;
63268   p = sqlite3_aggregate_context(context, sizeof(*p));
63269   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
63270     p->n++;
63271   }
63272 }   
63273 static void countFinalize(sqlite3_context *context){
63274   CountCtx *p;
63275   p = sqlite3_aggregate_context(context, 0);
63276   sqlite3_result_int64(context, p ? p->n : 0);
63277 }
63278
63279 /*
63280 ** Routines to implement min() and max() aggregate functions.
63281 */
63282 static void minmaxStep(sqlite3_context *context, int argc, sqlite3_value **argv){
63283   Mem *pArg  = (Mem *)argv[0];
63284   Mem *pBest;
63285
63286   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
63287   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
63288   if( !pBest ) return;
63289
63290   if( pBest->flags ){
63291     int max;
63292     int cmp;
63293     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
63294     /* This step function is used for both the min() and max() aggregates,
63295     ** the only difference between the two being that the sense of the
63296     ** comparison is inverted. For the max() aggregate, the
63297     ** sqlite3_user_data() function returns (void *)-1. For min() it
63298     ** returns (void *)db, where db is the sqlite3* database pointer.
63299     ** Therefore the next statement sets variable 'max' to 1 for the max()
63300     ** aggregate, or 0 for min().
63301     */
63302     max = sqlite3_user_data(context)!=0;
63303     cmp = sqlite3MemCompare(pBest, pArg, pColl);
63304     if( (max && cmp<0) || (!max && cmp>0) ){
63305       sqlite3VdbeMemCopy(pBest, pArg);
63306     }
63307   }else{
63308     sqlite3VdbeMemCopy(pBest, pArg);
63309   }
63310 }
63311 static void minMaxFinalize(sqlite3_context *context){
63312   sqlite3_value *pRes;
63313   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
63314   if( pRes ){
63315     if( pRes->flags ){
63316       sqlite3_result_value(context, pRes);
63317     }
63318     sqlite3VdbeMemRelease(pRes);
63319   }
63320 }
63321
63322 /*
63323 ** group_concat(EXPR, ?SEPARATOR?)
63324 */
63325 static void groupConcatStep(
63326   sqlite3_context *context,
63327   int argc,
63328   sqlite3_value **argv
63329 ){
63330   const char *zVal;
63331   StrAccum *pAccum;
63332   const char *zSep;
63333   int nVal, nSep, i;
63334   if( argc==0 || sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
63335   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
63336
63337   if( pAccum ){
63338     sqlite3 *db = sqlite3_context_db_handle(context);
63339     pAccum->useMalloc = 1;
63340     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
63341     if( pAccum->nChar ){
63342       if( argc>1 ){
63343         zSep = (char*)sqlite3_value_text(argv[argc-1]);
63344         nSep = sqlite3_value_bytes(argv[argc-1]);
63345       }else{
63346         zSep = ",";
63347         nSep = 1;
63348       }
63349       sqlite3StrAccumAppend(pAccum, zSep, nSep);
63350     }
63351     i = 0;
63352     do{
63353       zVal = (char*)sqlite3_value_text(argv[i]);
63354       nVal = sqlite3_value_bytes(argv[i]);
63355       sqlite3StrAccumAppend(pAccum, zVal, nVal);
63356       i++;
63357     }while( i<argc-1 );
63358   }
63359 }
63360 static void groupConcatFinalize(sqlite3_context *context){
63361   StrAccum *pAccum;
63362   pAccum = sqlite3_aggregate_context(context, 0);
63363   if( pAccum ){
63364     if( pAccum->tooBig ){
63365       sqlite3_result_error_toobig(context);
63366     }else if( pAccum->mallocFailed ){
63367       sqlite3_result_error_nomem(context);
63368     }else{    
63369       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
63370                           sqlite3_free);
63371     }
63372   }
63373 }
63374
63375 /*
63376 ** This function registered all of the above C functions as SQL
63377 ** functions.  This should be the only routine in this file with
63378 ** external linkage.
63379 */
63380 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
63381 #ifndef SQLITE_OMIT_ALTERTABLE
63382   sqlite3AlterFunctions(db);
63383 #endif
63384 #ifndef SQLITE_OMIT_PARSER
63385   sqlite3AttachFunctions(db);
63386 #endif
63387   if( !db->mallocFailed ){
63388     int rc = sqlite3_overload_function(db, "MATCH", 2);
63389     assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
63390     if( rc==SQLITE_NOMEM ){
63391       db->mallocFailed = 1;
63392     }
63393   }
63394 #ifdef SQLITE_SSE
63395   (void)sqlite3SseFunctions(db);
63396 #endif
63397 }
63398
63399 /*
63400 ** Set the LIKEOPT flag on the 2-argument function with the given name.
63401 */
63402 static void setLikeOptFlag(sqlite3 *db, const char *zName, int flagVal){
63403   FuncDef *pDef;
63404   pDef = sqlite3FindFunction(db, zName, strlen(zName), 2, SQLITE_UTF8, 0);
63405   if( pDef ){
63406     pDef->flags = flagVal;
63407   }
63408 }
63409
63410 /*
63411 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
63412 ** parameter determines whether or not the LIKE operator is case
63413 ** sensitive.  GLOB is always case sensitive.
63414 */
63415 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
63416   struct compareInfo *pInfo;
63417   if( caseSensitive ){
63418     pInfo = (struct compareInfo*)&likeInfoAlt;
63419   }else{
63420     pInfo = (struct compareInfo*)&likeInfoNorm;
63421   }
63422   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
63423   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
63424   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8, 
63425       (struct compareInfo*)&globInfo, likeFunc, 0,0);
63426   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
63427   setLikeOptFlag(db, "like", 
63428       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
63429 }
63430
63431 /*
63432 ** pExpr points to an expression which implements a function.  If
63433 ** it is appropriate to apply the LIKE optimization to that function
63434 ** then set aWc[0] through aWc[2] to the wildcard characters and
63435 ** return TRUE.  If the function is not a LIKE-style function then
63436 ** return FALSE.
63437 */
63438 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
63439   FuncDef *pDef;
63440   if( pExpr->op!=TK_FUNCTION || !pExpr->pList ){
63441     return 0;
63442   }
63443   if( pExpr->pList->nExpr!=2 ){
63444     return 0;
63445   }
63446   pDef = sqlite3FindFunction(db, (char*)pExpr->token.z, pExpr->token.n, 2,
63447                              SQLITE_UTF8, 0);
63448   if( pDef==0 || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
63449     return 0;
63450   }
63451
63452   /* The memcpy() statement assumes that the wildcard characters are
63453   ** the first three statements in the compareInfo structure.  The
63454   ** asserts() that follow verify that assumption
63455   */
63456   memcpy(aWc, pDef->pUserData, 3);
63457   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
63458   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
63459   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
63460   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
63461   return 1;
63462 }
63463
63464 /*
63465 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
63466 ** to the global function hash table.  This occurs at start-time (as
63467 ** a consequence of calling sqlite3_initialize()).
63468 **
63469 ** After this routine runs
63470 */
63471 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
63472   /*
63473   ** The following array holds FuncDef structures for all of the functions
63474   ** defined in this file.
63475   **
63476   ** The array cannot be constant since changes are made to the
63477   ** FuncDef.pHash elements at start-time.  The elements of this array
63478   ** are read-only after initialization is complete.
63479   */
63480   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
63481     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
63482     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
63483     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
63484     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
63485     FUNCTION(trim,               1, 3, 0, trimFunc         ),
63486     FUNCTION(trim,               2, 3, 0, trimFunc         ),
63487     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
63488     FUNCTION(min,                0, 0, 1, 0                ),
63489     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
63490     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
63491     FUNCTION(max,                0, 1, 1, 0                ),
63492     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
63493     FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
63494     FUNCTION(length,             1, 0, 0, lengthFunc       ),
63495     FUNCTION(substr,             2, 0, 0, substrFunc       ),
63496     FUNCTION(substr,             3, 0, 0, substrFunc       ),
63497     FUNCTION(abs,                1, 0, 0, absFunc          ),
63498     FUNCTION(round,              1, 0, 0, roundFunc        ),
63499     FUNCTION(round,              2, 0, 0, roundFunc        ),
63500     FUNCTION(upper,              1, 0, 0, upperFunc        ),
63501     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
63502     FUNCTION(coalesce,           1, 0, 0, 0                ),
63503     FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ),
63504     FUNCTION(coalesce,           0, 0, 0, 0                ),
63505     FUNCTION(hex,                1, 0, 0, hexFunc          ),
63506     FUNCTION(ifnull,             2, 0, 1, ifnullFunc       ),
63507     FUNCTION(random,            -1, 0, 0, randomFunc       ),
63508     FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
63509     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
63510     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
63511     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
63512     FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
63513     FUNCTION(changes,            0, 0, 0, changes          ),
63514     FUNCTION(total_changes,      0, 0, 0, total_changes    ),
63515     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
63516     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
63517   #ifdef SQLITE_SOUNDEX
63518     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
63519   #endif
63520   #ifndef SQLITE_OMIT_LOAD_EXTENSION
63521     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
63522     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
63523   #endif
63524     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
63525     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
63526     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
63527     AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ),
63528     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
63529     AGGREGATE(group_concat,     -1, 0, 0, groupConcatStep, groupConcatFinalize),
63530   
63531     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
63532   #ifdef SQLITE_CASE_SENSITIVE_LIKE
63533     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
63534     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
63535   #else
63536     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
63537     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
63538   #endif
63539   };
63540
63541   int i;
63542   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
63543   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
63544
63545   for(i=0; i<ArraySize(aBuiltinFunc); i++){
63546     sqlite3FuncDefInsert(pHash, &aFunc[i]);
63547   }
63548   sqlite3RegisterDateTimeFunctions();
63549 }
63550
63551 /************** End of func.c ************************************************/
63552 /************** Begin file insert.c ******************************************/
63553 /*
63554 ** 2001 September 15
63555 **
63556 ** The author disclaims copyright to this source code.  In place of
63557 ** a legal notice, here is a blessing:
63558 **
63559 **    May you do good and not evil.
63560 **    May you find forgiveness for yourself and forgive others.
63561 **    May you share freely, never taking more than you give.
63562 **
63563 *************************************************************************
63564 ** This file contains C code routines that are called by the parser
63565 ** to handle INSERT statements in SQLite.
63566 **
63567 ** $Id: insert.c,v 1.249 2008/08/20 16:35:10 drh Exp $
63568 */
63569
63570 /*
63571 ** Set P4 of the most recently inserted opcode to a column affinity
63572 ** string for index pIdx. A column affinity string has one character
63573 ** for each column in the table, according to the affinity of the column:
63574 **
63575 **  Character      Column affinity
63576 **  ------------------------------
63577 **  'a'            TEXT
63578 **  'b'            NONE
63579 **  'c'            NUMERIC
63580 **  'd'            INTEGER
63581 **  'e'            REAL
63582 **
63583 ** An extra 'b' is appended to the end of the string to cover the
63584 ** rowid that appears as the last column in every index.
63585 */
63586 SQLITE_PRIVATE void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
63587   if( !pIdx->zColAff ){
63588     /* The first time a column affinity string for a particular index is
63589     ** required, it is allocated and populated here. It is then stored as
63590     ** a member of the Index structure for subsequent use.
63591     **
63592     ** The column affinity string will eventually be deleted by
63593     ** sqliteDeleteIndex() when the Index structure itself is cleaned
63594     ** up.
63595     */
63596     int n;
63597     Table *pTab = pIdx->pTable;
63598     sqlite3 *db = sqlite3VdbeDb(v);
63599     pIdx->zColAff = (char *)sqlite3Malloc(pIdx->nColumn+2);
63600     if( !pIdx->zColAff ){
63601       db->mallocFailed = 1;
63602       return;
63603     }
63604     for(n=0; n<pIdx->nColumn; n++){
63605       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
63606     }
63607     pIdx->zColAff[n++] = SQLITE_AFF_NONE;
63608     pIdx->zColAff[n] = 0;
63609   }
63610  
63611   sqlite3VdbeChangeP4(v, -1, pIdx->zColAff, 0);
63612 }
63613
63614 /*
63615 ** Set P4 of the most recently inserted opcode to a column affinity
63616 ** string for table pTab. A column affinity string has one character
63617 ** for each column indexed by the index, according to the affinity of the
63618 ** column:
63619 **
63620 **  Character      Column affinity
63621 **  ------------------------------
63622 **  'a'            TEXT
63623 **  'b'            NONE
63624 **  'c'            NUMERIC
63625 **  'd'            INTEGER
63626 **  'e'            REAL
63627 */
63628 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
63629   /* The first time a column affinity string for a particular table
63630   ** is required, it is allocated and populated here. It is then 
63631   ** stored as a member of the Table structure for subsequent use.
63632   **
63633   ** The column affinity string will eventually be deleted by
63634   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
63635   */
63636   if( !pTab->zColAff ){
63637     char *zColAff;
63638     int i;
63639     sqlite3 *db = sqlite3VdbeDb(v);
63640
63641     zColAff = (char *)sqlite3Malloc(pTab->nCol+1);
63642     if( !zColAff ){
63643       db->mallocFailed = 1;
63644       return;
63645     }
63646
63647     for(i=0; i<pTab->nCol; i++){
63648       zColAff[i] = pTab->aCol[i].affinity;
63649     }
63650     zColAff[pTab->nCol] = '\0';
63651
63652     pTab->zColAff = zColAff;
63653   }
63654
63655   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
63656 }
63657
63658 /*
63659 ** Return non-zero if the table pTab in database iDb or any of its indices
63660 ** have been opened at any point in the VDBE program beginning at location
63661 ** iStartAddr throught the end of the program.  This is used to see if 
63662 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
63663 ** run without using temporary table for the results of the SELECT. 
63664 */
63665 static int readsTable(Vdbe *v, int iStartAddr, int iDb, Table *pTab){
63666   int i;
63667   int iEnd = sqlite3VdbeCurrentAddr(v);
63668   for(i=iStartAddr; i<iEnd; i++){
63669     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
63670     assert( pOp!=0 );
63671     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
63672       Index *pIndex;
63673       int tnum = pOp->p2;
63674       if( tnum==pTab->tnum ){
63675         return 1;
63676       }
63677       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
63678         if( tnum==pIndex->tnum ){
63679           return 1;
63680         }
63681       }
63682     }
63683 #ifndef SQLITE_OMIT_VIRTUALTABLE
63684     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pTab->pVtab ){
63685       assert( pOp->p4.pVtab!=0 );
63686       assert( pOp->p4type==P4_VTAB );
63687       return 1;
63688     }
63689 #endif
63690   }
63691   return 0;
63692 }
63693
63694 #ifndef SQLITE_OMIT_AUTOINCREMENT
63695 /*
63696 ** Write out code to initialize the autoincrement logic.  This code
63697 ** looks up the current autoincrement value in the sqlite_sequence
63698 ** table and stores that value in a register.  Code generated by
63699 ** autoIncStep() will keep that register holding the largest
63700 ** rowid value.  Code generated by autoIncEnd() will write the new
63701 ** largest value of the counter back into the sqlite_sequence table.
63702 **
63703 ** This routine returns the index of the mem[] cell that contains
63704 ** the maximum rowid counter.
63705 **
63706 ** Three consecutive registers are allocated by this routine.  The
63707 ** first two hold the name of the target table and the maximum rowid 
63708 ** inserted into the target table, respectively.
63709 ** The third holds the rowid in sqlite_sequence where we will
63710 ** write back the revised maximum rowid.  This routine returns the
63711 ** index of the second of these three registers.
63712 */
63713 static int autoIncBegin(
63714   Parse *pParse,      /* Parsing context */
63715   int iDb,            /* Index of the database holding pTab */
63716   Table *pTab         /* The table we are writing to */
63717 ){
63718   int memId = 0;      /* Register holding maximum rowid */
63719   if( pTab->tabFlags & TF_Autoincrement ){
63720     Vdbe *v = pParse->pVdbe;
63721     Db *pDb = &pParse->db->aDb[iDb];
63722     int iCur = pParse->nTab;
63723     int addr;               /* Address of the top of the loop */
63724     assert( v );
63725     pParse->nMem++;         /* Holds name of table */
63726     memId = ++pParse->nMem;
63727     pParse->nMem++;
63728     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
63729     addr = sqlite3VdbeCurrentAddr(v);
63730     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, pTab->zName, 0);
63731     sqlite3VdbeAddOp2(v, OP_Rewind, iCur, addr+9);
63732     sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, memId);
63733     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
63734     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
63735     sqlite3VdbeAddOp2(v, OP_Rowid, iCur, memId+1);
63736     sqlite3VdbeAddOp3(v, OP_Column, iCur, 1, memId);
63737     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
63738     sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+2);
63739     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
63740     sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
63741   }
63742   return memId;
63743 }
63744
63745 /*
63746 ** Update the maximum rowid for an autoincrement calculation.
63747 **
63748 ** This routine should be called when the top of the stack holds a
63749 ** new rowid that is about to be inserted.  If that new rowid is
63750 ** larger than the maximum rowid in the memId memory cell, then the
63751 ** memory cell is updated.  The stack is unchanged.
63752 */
63753 static void autoIncStep(Parse *pParse, int memId, int regRowid){
63754   if( memId>0 ){
63755     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
63756   }
63757 }
63758
63759 /*
63760 ** After doing one or more inserts, the maximum rowid is stored
63761 ** in reg[memId].  Generate code to write this value back into the
63762 ** the sqlite_sequence table.
63763 */
63764 static void autoIncEnd(
63765   Parse *pParse,     /* The parsing context */
63766   int iDb,           /* Index of the database holding pTab */
63767   Table *pTab,       /* Table we are inserting into */
63768   int memId          /* Memory cell holding the maximum rowid */
63769 ){
63770   if( pTab->tabFlags & TF_Autoincrement ){
63771     int iCur = pParse->nTab;
63772     Vdbe *v = pParse->pVdbe;
63773     Db *pDb = &pParse->db->aDb[iDb];
63774     int j1;
63775     int iRec = ++pParse->nMem;    /* Memory cell used for record */
63776
63777     assert( v );
63778     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
63779     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
63780     sqlite3VdbeAddOp2(v, OP_NewRowid, iCur, memId+1);
63781     sqlite3VdbeJumpHere(v, j1);
63782     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
63783     sqlite3VdbeAddOp3(v, OP_Insert, iCur, iRec, memId+1);
63784     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
63785     sqlite3VdbeAddOp1(v, OP_Close, iCur);
63786   }
63787 }
63788 #else
63789 /*
63790 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
63791 ** above are all no-ops
63792 */
63793 # define autoIncBegin(A,B,C) (0)
63794 # define autoIncStep(A,B,C)
63795 # define autoIncEnd(A,B,C,D)
63796 #endif /* SQLITE_OMIT_AUTOINCREMENT */
63797
63798
63799 /* Forward declaration */
63800 static int xferOptimization(
63801   Parse *pParse,        /* Parser context */
63802   Table *pDest,         /* The table we are inserting into */
63803   Select *pSelect,      /* A SELECT statement to use as the data source */
63804   int onError,          /* How to handle constraint errors */
63805   int iDbDest           /* The database of pDest */
63806 );
63807
63808 /*
63809 ** This routine is call to handle SQL of the following forms:
63810 **
63811 **    insert into TABLE (IDLIST) values(EXPRLIST)
63812 **    insert into TABLE (IDLIST) select
63813 **
63814 ** The IDLIST following the table name is always optional.  If omitted,
63815 ** then a list of all columns for the table is substituted.  The IDLIST
63816 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
63817 **
63818 ** The pList parameter holds EXPRLIST in the first form of the INSERT
63819 ** statement above, and pSelect is NULL.  For the second form, pList is
63820 ** NULL and pSelect is a pointer to the select statement used to generate
63821 ** data for the insert.
63822 **
63823 ** The code generated follows one of four templates.  For a simple
63824 ** select with data coming from a VALUES clause, the code executes
63825 ** once straight down through.  Pseudo-code follows (we call this
63826 ** the "1st template"):
63827 **
63828 **         open write cursor to <table> and its indices
63829 **         puts VALUES clause expressions onto the stack
63830 **         write the resulting record into <table>
63831 **         cleanup
63832 **
63833 ** The three remaining templates assume the statement is of the form
63834 **
63835 **   INSERT INTO <table> SELECT ...
63836 **
63837 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
63838 ** in other words if the SELECT pulls all columns from a single table
63839 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
63840 ** if <table2> and <table1> are distinct tables but have identical
63841 ** schemas, including all the same indices, then a special optimization
63842 ** is invoked that copies raw records from <table2> over to <table1>.
63843 ** See the xferOptimization() function for the implementation of this
63844 ** template.  This is the 2nd template.
63845 **
63846 **         open a write cursor to <table>
63847 **         open read cursor on <table2>
63848 **         transfer all records in <table2> over to <table>
63849 **         close cursors
63850 **         foreach index on <table>
63851 **           open a write cursor on the <table> index
63852 **           open a read cursor on the corresponding <table2> index
63853 **           transfer all records from the read to the write cursors
63854 **           close cursors
63855 **         end foreach
63856 **
63857 ** The 3rd template is for when the second template does not apply
63858 ** and the SELECT clause does not read from <table> at any time.
63859 ** The generated code follows this template:
63860 **
63861 **         EOF <- 0
63862 **         X <- A
63863 **         goto B
63864 **      A: setup for the SELECT
63865 **         loop over the rows in the SELECT
63866 **           load values into registers R..R+n
63867 **           yield X
63868 **         end loop
63869 **         cleanup after the SELECT
63870 **         EOF <- 1
63871 **         yield X
63872 **         goto A
63873 **      B: open write cursor to <table> and its indices
63874 **      C: yield X
63875 **         if EOF goto D
63876 **         insert the select result into <table> from R..R+n
63877 **         goto C
63878 **      D: cleanup
63879 **
63880 ** The 4th template is used if the insert statement takes its
63881 ** values from a SELECT but the data is being inserted into a table
63882 ** that is also read as part of the SELECT.  In the third form,
63883 ** we have to use a intermediate table to store the results of
63884 ** the select.  The template is like this:
63885 **
63886 **         EOF <- 0
63887 **         X <- A
63888 **         goto B
63889 **      A: setup for the SELECT
63890 **         loop over the tables in the SELECT
63891 **           load value into register R..R+n
63892 **           yield X
63893 **         end loop
63894 **         cleanup after the SELECT
63895 **         EOF <- 1
63896 **         yield X
63897 **         halt-error
63898 **      B: open temp table
63899 **      L: yield X
63900 **         if EOF goto M
63901 **         insert row from R..R+n into temp table
63902 **         goto L
63903 **      M: open write cursor to <table> and its indices
63904 **         rewind temp table
63905 **      C: loop over rows of intermediate table
63906 **           transfer values form intermediate table into <table>
63907 **         end loop
63908 **      D: cleanup
63909 */
63910 SQLITE_PRIVATE void sqlite3Insert(
63911   Parse *pParse,        /* Parser context */
63912   SrcList *pTabList,    /* Name of table into which we are inserting */
63913   ExprList *pList,      /* List of values to be inserted */
63914   Select *pSelect,      /* A SELECT statement to use as the data source */
63915   IdList *pColumn,      /* Column names corresponding to IDLIST. */
63916   int onError           /* How to handle constraint errors */
63917 ){
63918   sqlite3 *db;          /* The main database structure */
63919   Table *pTab;          /* The table to insert into.  aka TABLE */
63920   char *zTab;           /* Name of the table into which we are inserting */
63921   const char *zDb;      /* Name of the database holding this table */
63922   int i, j, idx;        /* Loop counters */
63923   Vdbe *v;              /* Generate code into this virtual machine */
63924   Index *pIdx;          /* For looping over indices of the table */
63925   int nColumn;          /* Number of columns in the data */
63926   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
63927   int baseCur = 0;      /* VDBE Cursor number for pTab */
63928   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
63929   int endOfLoop;        /* Label for the end of the insertion loop */
63930   int useTempTable = 0; /* Store SELECT results in intermediate table */
63931   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
63932   int addrInsTop = 0;   /* Jump to label "D" */
63933   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
63934   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
63935   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
63936   int newIdx = -1;      /* Cursor for the NEW pseudo-table */
63937   int iDb;              /* Index of database holding TABLE */
63938   Db *pDb;              /* The database containing table being inserted into */
63939   int appendFlag = 0;   /* True if the insert is likely to be an append */
63940
63941   /* Register allocations */
63942   int regFromSelect;    /* Base register for data coming from SELECT */
63943   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
63944   int regRowCount = 0;  /* Memory cell used for the row counter */
63945   int regIns;           /* Block of regs holding rowid+data being inserted */
63946   int regRowid;         /* registers holding insert rowid */
63947   int regData;          /* register holding first column to insert */
63948   int regRecord;        /* Holds the assemblied row record */
63949   int regEof;           /* Register recording end of SELECT data */
63950   int *aRegIdx = 0;     /* One register allocated to each index */
63951
63952
63953 #ifndef SQLITE_OMIT_TRIGGER
63954   int isView;                 /* True if attempting to insert into a view */
63955   int triggers_exist = 0;     /* True if there are FOR EACH ROW triggers */
63956 #endif
63957
63958   db = pParse->db;
63959   if( pParse->nErr || db->mallocFailed ){
63960     goto insert_cleanup;
63961   }
63962
63963   /* Locate the table into which we will be inserting new information.
63964   */
63965   assert( pTabList->nSrc==1 );
63966   zTab = pTabList->a[0].zName;
63967   if( zTab==0 ) goto insert_cleanup;
63968   pTab = sqlite3SrcListLookup(pParse, pTabList);
63969   if( pTab==0 ){
63970     goto insert_cleanup;
63971   }
63972   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
63973   assert( iDb<db->nDb );
63974   pDb = &db->aDb[iDb];
63975   zDb = pDb->zName;
63976   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
63977     goto insert_cleanup;
63978   }
63979
63980   /* Figure out if we have any triggers and if the table being
63981   ** inserted into is a view
63982   */
63983 #ifndef SQLITE_OMIT_TRIGGER
63984   triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
63985   isView = pTab->pSelect!=0;
63986 #else
63987 # define triggers_exist 0
63988 # define isView 0
63989 #endif
63990 #ifdef SQLITE_OMIT_VIEW
63991 # undef isView
63992 # define isView 0
63993 #endif
63994
63995   /* Ensure that:
63996   *  (a) the table is not read-only, 
63997   *  (b) that if it is a view then ON INSERT triggers exist
63998   */
63999   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
64000     goto insert_cleanup;
64001   }
64002   assert( pTab!=0 );
64003
64004   /* If pTab is really a view, make sure it has been initialized.
64005   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 
64006   ** module table).
64007   */
64008   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
64009     goto insert_cleanup;
64010   }
64011
64012   /* Allocate a VDBE
64013   */
64014   v = sqlite3GetVdbe(pParse);
64015   if( v==0 ) goto insert_cleanup;
64016   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
64017   sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
64018
64019   /* if there are row triggers, allocate a temp table for new.* references. */
64020   if( triggers_exist ){
64021     newIdx = pParse->nTab++;
64022   }
64023
64024 #ifndef SQLITE_OMIT_XFER_OPT
64025   /* If the statement is of the form
64026   **
64027   **       INSERT INTO <table1> SELECT * FROM <table2>;
64028   **
64029   ** Then special optimizations can be applied that make the transfer
64030   ** very fast and which reduce fragmentation of indices.
64031   **
64032   ** This is the 2nd template.
64033   */
64034   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
64035     assert( !triggers_exist );
64036     assert( pList==0 );
64037     goto insert_cleanup;
64038   }
64039 #endif /* SQLITE_OMIT_XFER_OPT */
64040
64041   /* If this is an AUTOINCREMENT table, look up the sequence number in the
64042   ** sqlite_sequence table and store it in memory cell regAutoinc.
64043   */
64044   regAutoinc = autoIncBegin(pParse, iDb, pTab);
64045
64046   /* Figure out how many columns of data are supplied.  If the data
64047   ** is coming from a SELECT statement, then generate a co-routine that
64048   ** produces a single row of the SELECT on each invocation.  The
64049   ** co-routine is the common header to the 3rd and 4th templates.
64050   */
64051   if( pSelect ){
64052     /* Data is coming from a SELECT.  Generate code to implement that SELECT
64053     ** as a co-routine.  The code is common to both the 3rd and 4th
64054     ** templates:
64055     **
64056     **         EOF <- 0
64057     **         X <- A
64058     **         goto B
64059     **      A: setup for the SELECT
64060     **         loop over the tables in the SELECT
64061     **           load value into register R..R+n
64062     **           yield X
64063     **         end loop
64064     **         cleanup after the SELECT
64065     **         EOF <- 1
64066     **         yield X
64067     **         halt-error
64068     **
64069     ** On each invocation of the co-routine, it puts a single row of the
64070     ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
64071     ** (These output registers are allocated by sqlite3Select().)  When
64072     ** the SELECT completes, it sets the EOF flag stored in regEof.
64073     */
64074     int rc, j1;
64075
64076     regEof = ++pParse->nMem;
64077     sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
64078     VdbeComment((v, "SELECT eof flag"));
64079     sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
64080     addrSelect = sqlite3VdbeCurrentAddr(v)+2;
64081     sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
64082     j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
64083     VdbeComment((v, "Jump over SELECT coroutine"));
64084
64085     /* Resolve the expressions in the SELECT statement and execute it. */
64086     rc = sqlite3Select(pParse, pSelect, &dest);
64087     if( rc || pParse->nErr || db->mallocFailed ){
64088       goto insert_cleanup;
64089     }
64090     sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
64091     sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
64092     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
64093     VdbeComment((v, "End of SELECT coroutine"));
64094     sqlite3VdbeJumpHere(v, j1);                          /* label B: */
64095
64096     regFromSelect = dest.iMem;
64097     assert( pSelect->pEList );
64098     nColumn = pSelect->pEList->nExpr;
64099     assert( dest.nMem==nColumn );
64100
64101     /* Set useTempTable to TRUE if the result of the SELECT statement
64102     ** should be written into a temporary table (template 4).  Set to
64103     ** FALSE if each* row of the SELECT can be written directly into
64104     ** the destination table (template 3).
64105     **
64106     ** A temp table must be used if the table being updated is also one
64107     ** of the tables being read by the SELECT statement.  Also use a 
64108     ** temp table in the case of row triggers.
64109     */
64110     if( triggers_exist || readsTable(v, addrSelect, iDb, pTab) ){
64111       useTempTable = 1;
64112     }
64113
64114     if( useTempTable ){
64115       /* Invoke the coroutine to extract information from the SELECT
64116       ** and add it to a transient table srcTab.  The code generated
64117       ** here is from the 4th template:
64118       **
64119       **      B: open temp table
64120       **      L: yield X
64121       **         if EOF goto M
64122       **         insert row from R..R+n into temp table
64123       **         goto L
64124       **      M: ...
64125       */
64126       int regRec;      /* Register to hold packed record */
64127       int regRowid;    /* Register to hold temp table ROWID */
64128       int addrTop;     /* Label "L" */
64129       int addrIf;      /* Address of jump to M */
64130
64131       srcTab = pParse->nTab++;
64132       regRec = sqlite3GetTempReg(pParse);
64133       regRowid = sqlite3GetTempReg(pParse);
64134       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
64135       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
64136       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
64137       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
64138       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regRowid);
64139       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regRowid);
64140       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
64141       sqlite3VdbeJumpHere(v, addrIf);
64142       sqlite3ReleaseTempReg(pParse, regRec);
64143       sqlite3ReleaseTempReg(pParse, regRowid);
64144     }
64145   }else{
64146     /* This is the case if the data for the INSERT is coming from a VALUES
64147     ** clause
64148     */
64149     NameContext sNC;
64150     memset(&sNC, 0, sizeof(sNC));
64151     sNC.pParse = pParse;
64152     srcTab = -1;
64153     assert( useTempTable==0 );
64154     nColumn = pList ? pList->nExpr : 0;
64155     for(i=0; i<nColumn; i++){
64156       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
64157         goto insert_cleanup;
64158       }
64159     }
64160   }
64161
64162   /* Make sure the number of columns in the source data matches the number
64163   ** of columns to be inserted into the table.
64164   */
64165   if( IsVirtual(pTab) ){
64166     for(i=0; i<pTab->nCol; i++){
64167       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
64168     }
64169   }
64170   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
64171     sqlite3ErrorMsg(pParse, 
64172        "table %S has %d columns but %d values were supplied",
64173        pTabList, 0, pTab->nCol, nColumn);
64174     goto insert_cleanup;
64175   }
64176   if( pColumn!=0 && nColumn!=pColumn->nId ){
64177     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
64178     goto insert_cleanup;
64179   }
64180
64181   /* If the INSERT statement included an IDLIST term, then make sure
64182   ** all elements of the IDLIST really are columns of the table and 
64183   ** remember the column indices.
64184   **
64185   ** If the table has an INTEGER PRIMARY KEY column and that column
64186   ** is named in the IDLIST, then record in the keyColumn variable
64187   ** the index into IDLIST of the primary key column.  keyColumn is
64188   ** the index of the primary key as it appears in IDLIST, not as
64189   ** is appears in the original table.  (The index of the primary
64190   ** key in the original table is pTab->iPKey.)
64191   */
64192   if( pColumn ){
64193     for(i=0; i<pColumn->nId; i++){
64194       pColumn->a[i].idx = -1;
64195     }
64196     for(i=0; i<pColumn->nId; i++){
64197       for(j=0; j<pTab->nCol; j++){
64198         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
64199           pColumn->a[i].idx = j;
64200           if( j==pTab->iPKey ){
64201             keyColumn = i;
64202           }
64203           break;
64204         }
64205       }
64206       if( j>=pTab->nCol ){
64207         if( sqlite3IsRowid(pColumn->a[i].zName) ){
64208           keyColumn = i;
64209         }else{
64210           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
64211               pTabList, 0, pColumn->a[i].zName);
64212           pParse->nErr++;
64213           goto insert_cleanup;
64214         }
64215       }
64216     }
64217   }
64218
64219   /* If there is no IDLIST term but the table has an integer primary
64220   ** key, the set the keyColumn variable to the primary key column index
64221   ** in the original table definition.
64222   */
64223   if( pColumn==0 && nColumn>0 ){
64224     keyColumn = pTab->iPKey;
64225   }
64226
64227   /* Open the temp table for FOR EACH ROW triggers
64228   */
64229   if( triggers_exist ){
64230     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
64231     sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0);
64232   }
64233     
64234   /* Initialize the count of rows to be inserted
64235   */
64236   if( db->flags & SQLITE_CountRows ){
64237     regRowCount = ++pParse->nMem;
64238     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
64239   }
64240
64241   /* If this is not a view, open the table and and all indices */
64242   if( !isView ){
64243     int nIdx;
64244     int i;
64245
64246     baseCur = pParse->nTab;
64247     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
64248     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
64249     if( aRegIdx==0 ){
64250       goto insert_cleanup;
64251     }
64252     for(i=0; i<nIdx; i++){
64253       aRegIdx[i] = ++pParse->nMem;
64254     }
64255   }
64256
64257   /* This is the top of the main insertion loop */
64258   if( useTempTable ){
64259     /* This block codes the top of loop only.  The complete loop is the
64260     ** following pseudocode (template 4):
64261     **
64262     **         rewind temp table
64263     **      C: loop over rows of intermediate table
64264     **           transfer values form intermediate table into <table>
64265     **         end loop
64266     **      D: ...
64267     */
64268     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
64269     addrCont = sqlite3VdbeCurrentAddr(v);
64270   }else if( pSelect ){
64271     /* This block codes the top of loop only.  The complete loop is the
64272     ** following pseudocode (template 3):
64273     **
64274     **      C: yield X
64275     **         if EOF goto D
64276     **         insert the select result into <table> from R..R+n
64277     **         goto C
64278     **      D: ...
64279     */
64280     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
64281     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
64282   }
64283
64284   /* Allocate registers for holding the rowid of the new row,
64285   ** the content of the new row, and the assemblied row record.
64286   */
64287   regRecord = ++pParse->nMem;
64288   regRowid = regIns = pParse->nMem+1;
64289   pParse->nMem += pTab->nCol + 1;
64290   if( IsVirtual(pTab) ){
64291     regRowid++;
64292     pParse->nMem++;
64293   }
64294   regData = regRowid+1;
64295
64296   /* Run the BEFORE and INSTEAD OF triggers, if there are any
64297   */
64298   endOfLoop = sqlite3VdbeMakeLabel(v);
64299   if( triggers_exist & TRIGGER_BEFORE ){
64300     int regRowid;
64301     int regCols;
64302     int regRec;
64303
64304     /* build the NEW.* reference row.  Note that if there is an INTEGER
64305     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
64306     ** translated into a unique ID for the row.  But on a BEFORE trigger,
64307     ** we do not know what the unique ID will be (because the insert has
64308     ** not happened yet) so we substitute a rowid of -1
64309     */
64310     regRowid = sqlite3GetTempReg(pParse);
64311     if( keyColumn<0 ){
64312       sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
64313     }else if( useTempTable ){
64314       sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
64315     }else{
64316       int j1;
64317       assert( pSelect==0 );  /* Otherwise useTempTable is true */
64318       sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
64319       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
64320       sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
64321       sqlite3VdbeJumpHere(v, j1);
64322       sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
64323     }
64324
64325     /* Cannot have triggers on a virtual table. If it were possible,
64326     ** this block would have to account for hidden column.
64327     */
64328     assert(!IsVirtual(pTab));
64329
64330     /* Create the new column data
64331     */
64332     regCols = sqlite3GetTempRange(pParse, pTab->nCol);
64333     for(i=0; i<pTab->nCol; i++){
64334       if( pColumn==0 ){
64335         j = i;
64336       }else{
64337         for(j=0; j<pColumn->nId; j++){
64338           if( pColumn->a[j].idx==i ) break;
64339         }
64340       }
64341       if( pColumn && j>=pColumn->nId ){
64342         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i);
64343       }else if( useTempTable ){
64344         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i); 
64345       }else{
64346         assert( pSelect==0 ); /* Otherwise useTempTable is true */
64347         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i);
64348       }
64349     }
64350     regRec = sqlite3GetTempReg(pParse);
64351     sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRec);
64352
64353     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
64354     ** do not attempt any conversions before assembling the record.
64355     ** If this is a real table, attempt conversions as required by the
64356     ** table column affinities.
64357     */
64358     if( !isView ){
64359       sqlite3TableAffinityStr(v, pTab);
64360     }
64361     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid);
64362     sqlite3ReleaseTempReg(pParse, regRec);
64363     sqlite3ReleaseTempReg(pParse, regRowid);
64364     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol);
64365
64366     /* Fire BEFORE or INSTEAD OF triggers */
64367     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab, 
64368         newIdx, -1, onError, endOfLoop, 0, 0) ){
64369       goto insert_cleanup;
64370     }
64371   }
64372
64373   /* Push the record number for the new entry onto the stack.  The
64374   ** record number is a randomly generate integer created by NewRowid
64375   ** except when the table has an INTEGER PRIMARY KEY column, in which
64376   ** case the record number is the same as that column. 
64377   */
64378   if( !isView ){
64379     if( IsVirtual(pTab) ){
64380       /* The row that the VUpdate opcode will delete: none */
64381       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
64382     }
64383     if( keyColumn>=0 ){
64384       if( useTempTable ){
64385         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
64386       }else if( pSelect ){
64387         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
64388       }else{
64389         VdbeOp *pOp;
64390         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
64391         pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
64392         if( pOp && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
64393           appendFlag = 1;
64394           pOp->opcode = OP_NewRowid;
64395           pOp->p1 = baseCur;
64396           pOp->p2 = regRowid;
64397           pOp->p3 = regAutoinc;
64398         }
64399       }
64400       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
64401       ** to generate a unique primary key value.
64402       */
64403       if( !appendFlag ){
64404         int j1;
64405         if( !IsVirtual(pTab) ){
64406           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
64407           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
64408           sqlite3VdbeJumpHere(v, j1);
64409         }else{
64410           j1 = sqlite3VdbeCurrentAddr(v);
64411           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
64412         }
64413         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
64414       }
64415     }else if( IsVirtual(pTab) ){
64416       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
64417     }else{
64418       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
64419       appendFlag = 1;
64420     }
64421     autoIncStep(pParse, regAutoinc, regRowid);
64422
64423     /* Push onto the stack, data for all columns of the new entry, beginning
64424     ** with the first column.
64425     */
64426     nHidden = 0;
64427     for(i=0; i<pTab->nCol; i++){
64428       int iRegStore = regRowid+1+i;
64429       if( i==pTab->iPKey ){
64430         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
64431         ** Whenever this column is read, the record number will be substituted
64432         ** in its place.  So will fill this column with a NULL to avoid
64433         ** taking up data space with information that will never be used. */
64434         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
64435         continue;
64436       }
64437       if( pColumn==0 ){
64438         if( IsHiddenColumn(&pTab->aCol[i]) ){
64439           assert( IsVirtual(pTab) );
64440           j = -1;
64441           nHidden++;
64442         }else{
64443           j = i - nHidden;
64444         }
64445       }else{
64446         for(j=0; j<pColumn->nId; j++){
64447           if( pColumn->a[j].idx==i ) break;
64448         }
64449       }
64450       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
64451         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
64452       }else if( useTempTable ){
64453         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
64454       }else if( pSelect ){
64455         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
64456       }else{
64457         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
64458       }
64459     }
64460
64461     /* Generate code to check constraints and generate index keys and
64462     ** do the insertion.
64463     */
64464 #ifndef SQLITE_OMIT_VIRTUALTABLE
64465     if( IsVirtual(pTab) ){
64466       sqlite3VtabMakeWritable(pParse, pTab);
64467       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns,
64468                      (const char*)pTab->pVtab, P4_VTAB);
64469     }else
64470 #endif
64471     {
64472       sqlite3GenerateConstraintChecks(
64473           pParse,
64474           pTab,
64475           baseCur,
64476           regIns,
64477           aRegIdx,
64478           keyColumn>=0,
64479           0,
64480           onError,
64481           endOfLoop
64482       );
64483       sqlite3CompleteInsertion(
64484           pParse,
64485           pTab,
64486           baseCur,
64487           regIns,
64488           aRegIdx,
64489           0,
64490           0,
64491           (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
64492           appendFlag
64493        );
64494     }
64495   }
64496
64497   /* Update the count of rows that are inserted
64498   */
64499   if( (db->flags & SQLITE_CountRows)!=0 ){
64500     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
64501   }
64502
64503   if( triggers_exist ){
64504     /* Code AFTER triggers */
64505     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
64506           newIdx, -1, onError, endOfLoop, 0, 0) ){
64507       goto insert_cleanup;
64508     }
64509   }
64510
64511   /* The bottom of the main insertion loop, if the data source
64512   ** is a SELECT statement.
64513   */
64514   sqlite3VdbeResolveLabel(v, endOfLoop);
64515   if( useTempTable ){
64516     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
64517     sqlite3VdbeJumpHere(v, addrInsTop);
64518     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
64519   }else if( pSelect ){
64520     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
64521     sqlite3VdbeJumpHere(v, addrInsTop);
64522   }
64523
64524   if( !IsVirtual(pTab) && !isView ){
64525     /* Close all tables opened */
64526     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
64527     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
64528       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
64529     }
64530   }
64531
64532   /* Update the sqlite_sequence table by storing the content of the
64533   ** counter value in memory regAutoinc back into the sqlite_sequence
64534   ** table.
64535   */
64536   autoIncEnd(pParse, iDb, pTab, regAutoinc);
64537
64538   /*
64539   ** Return the number of rows inserted. If this routine is 
64540   ** generating code because of a call to sqlite3NestedParse(), do not
64541   ** invoke the callback function.
64542   */
64543   if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
64544     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
64545     sqlite3VdbeSetNumCols(v, 1);
64546     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P4_STATIC);
64547   }
64548
64549 insert_cleanup:
64550   sqlite3SrcListDelete(db, pTabList);
64551   sqlite3ExprListDelete(db, pList);
64552   sqlite3SelectDelete(db, pSelect);
64553   sqlite3IdListDelete(db, pColumn);
64554   sqlite3DbFree(db, aRegIdx);
64555 }
64556
64557 /*
64558 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
64559 **
64560 ** The input is a range of consecutive registers as follows:
64561 **
64562 **    1.  The rowid of the row to be updated before the update.  This
64563 **        value is omitted unless we are doing an UPDATE that involves a
64564 **        change to the record number or writing to a virtual table.
64565 **
64566 **    2.  The rowid of the row after the update.
64567 **
64568 **    3.  The data in the first column of the entry after the update.
64569 **
64570 **    i.  Data from middle columns...
64571 **
64572 **    N.  The data in the last column of the entry after the update.
64573 **
64574 ** The regRowid parameter is the index of the register containing (2).
64575 **
64576 ** The old rowid shown as entry (1) above is omitted unless both isUpdate
64577 ** and rowidChng are 1.  isUpdate is true for UPDATEs and false for
64578 ** INSERTs.  RowidChng means that the new rowid is explicitly specified by
64579 ** the update or insert statement.  If rowidChng is false, it means that
64580 ** the rowid is computed automatically in an insert or that the rowid value
64581 ** is not modified by the update.
64582 **
64583 ** The code generated by this routine store new index entries into
64584 ** registers identified by aRegIdx[].  No index entry is created for
64585 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
64586 ** the same as the order of indices on the linked list of indices
64587 ** attached to the table.
64588 **
64589 ** This routine also generates code to check constraints.  NOT NULL,
64590 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
64591 ** then the appropriate action is performed.  There are five possible
64592 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
64593 **
64594 **  Constraint type  Action       What Happens
64595 **  ---------------  ----------   ----------------------------------------
64596 **  any              ROLLBACK     The current transaction is rolled back and
64597 **                                sqlite3_exec() returns immediately with a
64598 **                                return code of SQLITE_CONSTRAINT.
64599 **
64600 **  any              ABORT        Back out changes from the current command
64601 **                                only (do not do a complete rollback) then
64602 **                                cause sqlite3_exec() to return immediately
64603 **                                with SQLITE_CONSTRAINT.
64604 **
64605 **  any              FAIL         Sqlite_exec() returns immediately with a
64606 **                                return code of SQLITE_CONSTRAINT.  The
64607 **                                transaction is not rolled back and any
64608 **                                prior changes are retained.
64609 **
64610 **  any              IGNORE       The record number and data is popped from
64611 **                                the stack and there is an immediate jump
64612 **                                to label ignoreDest.
64613 **
64614 **  NOT NULL         REPLACE      The NULL value is replace by the default
64615 **                                value for that column.  If the default value
64616 **                                is NULL, the action is the same as ABORT.
64617 **
64618 **  UNIQUE           REPLACE      The other row that conflicts with the row
64619 **                                being inserted is removed.
64620 **
64621 **  CHECK            REPLACE      Illegal.  The results in an exception.
64622 **
64623 ** Which action to take is determined by the overrideError parameter.
64624 ** Or if overrideError==OE_Default, then the pParse->onError parameter
64625 ** is used.  Or if pParse->onError==OE_Default then the onError value
64626 ** for the constraint is used.
64627 **
64628 ** The calling routine must open a read/write cursor for pTab with
64629 ** cursor number "baseCur".  All indices of pTab must also have open
64630 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
64631 ** Except, if there is no possibility of a REPLACE action then
64632 ** cursors do not need to be open for indices where aRegIdx[i]==0.
64633 */
64634 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
64635   Parse *pParse,      /* The parser context */
64636   Table *pTab,        /* the table into which we are inserting */
64637   int baseCur,        /* Index of a read/write cursor pointing at pTab */
64638   int regRowid,       /* Index of the range of input registers */
64639   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
64640   int rowidChng,      /* True if the rowid might collide with existing entry */
64641   int isUpdate,       /* True for UPDATE, False for INSERT */
64642   int overrideError,  /* Override onError to this if not OE_Default */
64643   int ignoreDest      /* Jump to this label on an OE_Ignore resolution */
64644 ){
64645   int i;
64646   Vdbe *v;
64647   int nCol;
64648   int onError;
64649   int j1, j2, j3;     /* Addresses of jump instructions */
64650   int regData;        /* Register containing first data column */
64651   int iCur;
64652   Index *pIdx;
64653   int seenReplace = 0;
64654   int hasTwoRowids = (isUpdate && rowidChng);
64655
64656   v = sqlite3GetVdbe(pParse);
64657   assert( v!=0 );
64658   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
64659   nCol = pTab->nCol;
64660   regData = regRowid + 1;
64661
64662
64663   /* Test all NOT NULL constraints.
64664   */
64665   for(i=0; i<nCol; i++){
64666     if( i==pTab->iPKey ){
64667       continue;
64668     }
64669     onError = pTab->aCol[i].notNull;
64670     if( onError==OE_None ) continue;
64671     if( overrideError!=OE_Default ){
64672       onError = overrideError;
64673     }else if( onError==OE_Default ){
64674       onError = OE_Abort;
64675     }
64676     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
64677       onError = OE_Abort;
64678     }
64679     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
64680     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
64681         || onError==OE_Ignore || onError==OE_Replace );
64682     switch( onError ){
64683       case OE_Rollback:
64684       case OE_Abort:
64685       case OE_Fail: {
64686         char *zMsg;
64687         sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
64688         zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
64689                               pTab->zName, pTab->aCol[i].zName);
64690         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
64691         break;
64692       }
64693       case OE_Ignore: {
64694         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
64695         break;
64696       }
64697       case OE_Replace: {
64698         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
64699         break;
64700       }
64701     }
64702     sqlite3VdbeJumpHere(v, j1);
64703   }
64704
64705   /* Test all CHECK constraints
64706   */
64707 #ifndef SQLITE_OMIT_CHECK
64708   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
64709     int allOk = sqlite3VdbeMakeLabel(v);
64710     pParse->ckBase = regData;
64711     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
64712     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
64713     if( onError==OE_Ignore ){
64714       sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
64715     }else{
64716       sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
64717     }
64718     sqlite3VdbeResolveLabel(v, allOk);
64719   }
64720 #endif /* !defined(SQLITE_OMIT_CHECK) */
64721
64722   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
64723   ** of the new record does not previously exist.  Except, if this
64724   ** is an UPDATE and the primary key is not changing, that is OK.
64725   */
64726   if( rowidChng ){
64727     onError = pTab->keyConf;
64728     if( overrideError!=OE_Default ){
64729       onError = overrideError;
64730     }else if( onError==OE_Default ){
64731       onError = OE_Abort;
64732     }
64733     
64734     if( onError!=OE_Replace || pTab->pIndex ){
64735       if( isUpdate ){
64736         j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, regRowid-1);
64737       }
64738       j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
64739       switch( onError ){
64740         default: {
64741           onError = OE_Abort;
64742           /* Fall thru into the next case */
64743         }
64744         case OE_Rollback:
64745         case OE_Abort:
64746         case OE_Fail: {
64747           sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
64748                            "PRIMARY KEY must be unique", P4_STATIC);
64749           break;
64750         }
64751         case OE_Replace: {
64752           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
64753           seenReplace = 1;
64754           break;
64755         }
64756         case OE_Ignore: {
64757           assert( seenReplace==0 );
64758           sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
64759           break;
64760         }
64761       }
64762       sqlite3VdbeJumpHere(v, j3);
64763       if( isUpdate ){
64764         sqlite3VdbeJumpHere(v, j2);
64765       }
64766     }
64767   }
64768
64769   /* Test all UNIQUE constraints by creating entries for each UNIQUE
64770   ** index and making sure that duplicate entries do not already exist.
64771   ** Add the new records to the indices as we go.
64772   */
64773   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
64774     int regIdx;
64775     int regR;
64776
64777     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
64778
64779     /* Create a key for accessing the index entry */
64780     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
64781     for(i=0; i<pIdx->nColumn; i++){
64782       int idx = pIdx->aiColumn[i];
64783       if( idx==pTab->iPKey ){
64784         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
64785       }else{
64786         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
64787       }
64788     }
64789     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
64790     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
64791     sqlite3IndexAffinityStr(v, pIdx);
64792     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
64793     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
64794
64795     /* Find out what action to take in case there is an indexing conflict */
64796     onError = pIdx->onError;
64797     if( onError==OE_None ) continue;  /* pIdx is not a UNIQUE index */
64798     if( overrideError!=OE_Default ){
64799       onError = overrideError;
64800     }else if( onError==OE_Default ){
64801       onError = OE_Abort;
64802     }
64803     if( seenReplace ){
64804       if( onError==OE_Ignore ) onError = OE_Replace;
64805       else if( onError==OE_Fail ) onError = OE_Abort;
64806     }
64807     
64808
64809     /* Check to see if the new index entry will be unique */
64810     j2 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdx, 0, pIdx->nColumn);
64811     regR = sqlite3GetTempReg(pParse);
64812     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid-hasTwoRowids, regR);
64813     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
64814                            regR, SQLITE_INT_TO_PTR(aRegIdx[iCur]),
64815                            P4_INT32);
64816
64817     /* Generate code that executes if the new index entry is not unique */
64818     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
64819         || onError==OE_Ignore || onError==OE_Replace );
64820     switch( onError ){
64821       case OE_Rollback:
64822       case OE_Abort:
64823       case OE_Fail: {
64824         int j, n1, n2;
64825         char zErrMsg[200];
64826         sqlite3_snprintf(sizeof(zErrMsg), zErrMsg,
64827                          pIdx->nColumn>1 ? "columns " : "column ");
64828         n1 = strlen(zErrMsg);
64829         for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
64830           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
64831           n2 = strlen(zCol);
64832           if( j>0 ){
64833             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", ");
64834             n1 += 2;
64835           }
64836           if( n1+n2>sizeof(zErrMsg)-30 ){
64837             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "...");
64838             n1 += 3;
64839             break;
64840           }else{
64841             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
64842             n1 += n2;
64843           }
64844         }
64845         sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], 
64846             pIdx->nColumn>1 ? " are not unique" : " is not unique");
64847         sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErrMsg,0);
64848         break;
64849       }
64850       case OE_Ignore: {
64851         assert( seenReplace==0 );
64852         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
64853         break;
64854       }
64855       case OE_Replace: {
64856         sqlite3GenerateRowDelete(pParse, pTab, baseCur, regR, 0);
64857         seenReplace = 1;
64858         break;
64859       }
64860     }
64861     sqlite3VdbeJumpHere(v, j2);
64862     sqlite3VdbeJumpHere(v, j3);
64863     sqlite3ReleaseTempReg(pParse, regR);
64864   }
64865 }
64866
64867 /*
64868 ** This routine generates code to finish the INSERT or UPDATE operation
64869 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
64870 ** A consecutive range of registers starting at regRowid contains the
64871 ** rowid and the content to be inserted.
64872 **
64873 ** The arguments to this routine should be the same as the first six
64874 ** arguments to sqlite3GenerateConstraintChecks.
64875 */
64876 SQLITE_PRIVATE void sqlite3CompleteInsertion(
64877   Parse *pParse,      /* The parser context */
64878   Table *pTab,        /* the table into which we are inserting */
64879   int baseCur,        /* Index of a read/write cursor pointing at pTab */
64880   int regRowid,       /* Range of content */
64881   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
64882   int rowidChng,      /* True if the record number will change */
64883   int isUpdate,       /* True for UPDATE, False for INSERT */
64884   int newIdx,         /* Index of NEW table for triggers.  -1 if none */
64885   int appendBias      /* True if this is likely to be an append */
64886 ){
64887   int i;
64888   Vdbe *v;
64889   int nIdx;
64890   Index *pIdx;
64891   int pik_flags;
64892   int regData;
64893   int regRec;
64894
64895   v = sqlite3GetVdbe(pParse);
64896   assert( v!=0 );
64897   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
64898   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
64899   for(i=nIdx-1; i>=0; i--){
64900     if( aRegIdx[i]==0 ) continue;
64901     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
64902   }
64903   regData = regRowid + 1;
64904   regRec = sqlite3GetTempReg(pParse);
64905   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
64906   sqlite3TableAffinityStr(v, pTab);
64907   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
64908 #ifndef SQLITE_OMIT_TRIGGER
64909   if( newIdx>=0 ){
64910     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid);
64911   }
64912 #endif
64913   if( pParse->nested ){
64914     pik_flags = 0;
64915   }else{
64916     pik_flags = OPFLAG_NCHANGE;
64917     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
64918   }
64919   if( appendBias ){
64920     pik_flags |= OPFLAG_APPEND;
64921   }
64922   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
64923   if( !pParse->nested ){
64924     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
64925   }
64926   sqlite3VdbeChangeP5(v, pik_flags);
64927 }
64928
64929 /*
64930 ** Generate code that will open cursors for a table and for all
64931 ** indices of that table.  The "baseCur" parameter is the cursor number used
64932 ** for the table.  Indices are opened on subsequent cursors.
64933 **
64934 ** Return the number of indices on the table.
64935 */
64936 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
64937   Parse *pParse,   /* Parsing context */
64938   Table *pTab,     /* Table to be opened */
64939   int baseCur,        /* Cursor number assigned to the table */
64940   int op           /* OP_OpenRead or OP_OpenWrite */
64941 ){
64942   int i;
64943   int iDb;
64944   Index *pIdx;
64945   Vdbe *v;
64946
64947   if( IsVirtual(pTab) ) return 0;
64948   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
64949   v = sqlite3GetVdbe(pParse);
64950   assert( v!=0 );
64951   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
64952   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
64953     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
64954     assert( pIdx->pSchema==pTab->pSchema );
64955     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
64956                       (char*)pKey, P4_KEYINFO_HANDOFF);
64957     VdbeComment((v, "%s", pIdx->zName));
64958   }
64959   if( pParse->nTab<=baseCur+i ){
64960     pParse->nTab = baseCur+i;
64961   }
64962   return i-1;
64963 }
64964
64965
64966 #ifdef SQLITE_TEST
64967 /*
64968 ** The following global variable is incremented whenever the
64969 ** transfer optimization is used.  This is used for testing
64970 ** purposes only - to make sure the transfer optimization really
64971 ** is happening when it is suppose to.
64972 */
64973 SQLITE_API int sqlite3_xferopt_count;
64974 #endif /* SQLITE_TEST */
64975
64976
64977 #ifndef SQLITE_OMIT_XFER_OPT
64978 /*
64979 ** Check to collation names to see if they are compatible.
64980 */
64981 static int xferCompatibleCollation(const char *z1, const char *z2){
64982   if( z1==0 ){
64983     return z2==0;
64984   }
64985   if( z2==0 ){
64986     return 0;
64987   }
64988   return sqlite3StrICmp(z1, z2)==0;
64989 }
64990
64991
64992 /*
64993 ** Check to see if index pSrc is compatible as a source of data
64994 ** for index pDest in an insert transfer optimization.  The rules
64995 ** for a compatible index:
64996 **
64997 **    *   The index is over the same set of columns
64998 **    *   The same DESC and ASC markings occurs on all columns
64999 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
65000 **    *   The same collating sequence on each column
65001 */
65002 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
65003   int i;
65004   assert( pDest && pSrc );
65005   assert( pDest->pTable!=pSrc->pTable );
65006   if( pDest->nColumn!=pSrc->nColumn ){
65007     return 0;   /* Different number of columns */
65008   }
65009   if( pDest->onError!=pSrc->onError ){
65010     return 0;   /* Different conflict resolution strategies */
65011   }
65012   for(i=0; i<pSrc->nColumn; i++){
65013     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
65014       return 0;   /* Different columns indexed */
65015     }
65016     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
65017       return 0;   /* Different sort orders */
65018     }
65019     if( pSrc->azColl[i]!=pDest->azColl[i] ){
65020       return 0;   /* Different collating sequences */
65021     }
65022   }
65023
65024   /* If no test above fails then the indices must be compatible */
65025   return 1;
65026 }
65027
65028 /*
65029 ** Attempt the transfer optimization on INSERTs of the form
65030 **
65031 **     INSERT INTO tab1 SELECT * FROM tab2;
65032 **
65033 ** This optimization is only attempted if
65034 **
65035 **    (1)  tab1 and tab2 have identical schemas including all the
65036 **         same indices and constraints
65037 **
65038 **    (2)  tab1 and tab2 are different tables
65039 **
65040 **    (3)  There must be no triggers on tab1
65041 **
65042 **    (4)  The result set of the SELECT statement is "*"
65043 **
65044 **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
65045 **         or LIMIT clause.
65046 **
65047 **    (6)  The SELECT statement is a simple (not a compound) select that
65048 **         contains only tab2 in its FROM clause
65049 **
65050 ** This method for implementing the INSERT transfers raw records from
65051 ** tab2 over to tab1.  The columns are not decoded.  Raw records from
65052 ** the indices of tab2 are transfered to tab1 as well.  In so doing,
65053 ** the resulting tab1 has much less fragmentation.
65054 **
65055 ** This routine returns TRUE if the optimization is attempted.  If any
65056 ** of the conditions above fail so that the optimization should not
65057 ** be attempted, then this routine returns FALSE.
65058 */
65059 static int xferOptimization(
65060   Parse *pParse,        /* Parser context */
65061   Table *pDest,         /* The table we are inserting into */
65062   Select *pSelect,      /* A SELECT statement to use as the data source */
65063   int onError,          /* How to handle constraint errors */
65064   int iDbDest           /* The database of pDest */
65065 ){
65066   ExprList *pEList;                /* The result set of the SELECT */
65067   Table *pSrc;                     /* The table in the FROM clause of SELECT */
65068   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
65069   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
65070   int i;                           /* Loop counter */
65071   int iDbSrc;                      /* The database of pSrc */
65072   int iSrc, iDest;                 /* Cursors from source and destination */
65073   int addr1, addr2;                /* Loop addresses */
65074   int emptyDestTest;               /* Address of test for empty pDest */
65075   int emptySrcTest;                /* Address of test for empty pSrc */
65076   Vdbe *v;                         /* The VDBE we are building */
65077   KeyInfo *pKey;                   /* Key information for an index */
65078   int regAutoinc;                  /* Memory register used by AUTOINC */
65079   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
65080   int regData, regRowid;           /* Registers holding data and rowid */
65081
65082   if( pSelect==0 ){
65083     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
65084   }
65085   if( pDest->pTrigger ){
65086     return 0;   /* tab1 must not have triggers */
65087   }
65088 #ifndef SQLITE_OMIT_VIRTUALTABLE
65089   if( pDest->tabFlags & TF_Virtual ){
65090     return 0;   /* tab1 must not be a virtual table */
65091   }
65092 #endif
65093   if( onError==OE_Default ){
65094     onError = OE_Abort;
65095   }
65096   if( onError!=OE_Abort && onError!=OE_Rollback ){
65097     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
65098   }
65099   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
65100   if( pSelect->pSrc->nSrc!=1 ){
65101     return 0;   /* FROM clause must have exactly one term */
65102   }
65103   if( pSelect->pSrc->a[0].pSelect ){
65104     return 0;   /* FROM clause cannot contain a subquery */
65105   }
65106   if( pSelect->pWhere ){
65107     return 0;   /* SELECT may not have a WHERE clause */
65108   }
65109   if( pSelect->pOrderBy ){
65110     return 0;   /* SELECT may not have an ORDER BY clause */
65111   }
65112   /* Do not need to test for a HAVING clause.  If HAVING is present but
65113   ** there is no ORDER BY, we will get an error. */
65114   if( pSelect->pGroupBy ){
65115     return 0;   /* SELECT may not have a GROUP BY clause */
65116   }
65117   if( pSelect->pLimit ){
65118     return 0;   /* SELECT may not have a LIMIT clause */
65119   }
65120   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
65121   if( pSelect->pPrior ){
65122     return 0;   /* SELECT may not be a compound query */
65123   }
65124   if( pSelect->selFlags & SF_Distinct ){
65125     return 0;   /* SELECT may not be DISTINCT */
65126   }
65127   pEList = pSelect->pEList;
65128   assert( pEList!=0 );
65129   if( pEList->nExpr!=1 ){
65130     return 0;   /* The result set must have exactly one column */
65131   }
65132   assert( pEList->a[0].pExpr );
65133   if( pEList->a[0].pExpr->op!=TK_ALL ){
65134     return 0;   /* The result set must be the special operator "*" */
65135   }
65136
65137   /* At this point we have established that the statement is of the
65138   ** correct syntactic form to participate in this optimization.  Now
65139   ** we have to check the semantics.
65140   */
65141   pItem = pSelect->pSrc->a;
65142   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
65143   if( pSrc==0 ){
65144     return 0;   /* FROM clause does not contain a real table */
65145   }
65146   if( pSrc==pDest ){
65147     return 0;   /* tab1 and tab2 may not be the same table */
65148   }
65149 #ifndef SQLITE_OMIT_VIRTUALTABLE
65150   if( pSrc->tabFlags & TF_Virtual ){
65151     return 0;   /* tab2 must not be a virtual table */
65152   }
65153 #endif
65154   if( pSrc->pSelect ){
65155     return 0;   /* tab2 may not be a view */
65156   }
65157   if( pDest->nCol!=pSrc->nCol ){
65158     return 0;   /* Number of columns must be the same in tab1 and tab2 */
65159   }
65160   if( pDest->iPKey!=pSrc->iPKey ){
65161     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
65162   }
65163   for(i=0; i<pDest->nCol; i++){
65164     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
65165       return 0;    /* Affinity must be the same on all columns */
65166     }
65167     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
65168       return 0;    /* Collating sequence must be the same on all columns */
65169     }
65170     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
65171       return 0;    /* tab2 must be NOT NULL if tab1 is */
65172     }
65173   }
65174   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
65175     if( pDestIdx->onError!=OE_None ){
65176       destHasUniqueIdx = 1;
65177     }
65178     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
65179       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
65180     }
65181     if( pSrcIdx==0 ){
65182       return 0;    /* pDestIdx has no corresponding index in pSrc */
65183     }
65184   }
65185 #ifndef SQLITE_OMIT_CHECK
65186   if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
65187     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
65188   }
65189 #endif
65190
65191   /* If we get this far, it means either:
65192   **
65193   **    *   We can always do the transfer if the table contains an
65194   **        an integer primary key
65195   **
65196   **    *   We can conditionally do the transfer if the destination
65197   **        table is empty.
65198   */
65199 #ifdef SQLITE_TEST
65200   sqlite3_xferopt_count++;
65201 #endif
65202   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
65203   v = sqlite3GetVdbe(pParse);
65204   sqlite3CodeVerifySchema(pParse, iDbSrc);
65205   iSrc = pParse->nTab++;
65206   iDest = pParse->nTab++;
65207   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
65208   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
65209   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
65210     /* If tables do not have an INTEGER PRIMARY KEY and there
65211     ** are indices to be copied and the destination is not empty,
65212     ** we have to disallow the transfer optimization because the
65213     ** the rowids might change which will mess up indexing.
65214     **
65215     ** Or if the destination has a UNIQUE index and is not empty,
65216     ** we also disallow the transfer optimization because we cannot
65217     ** insure that all entries in the union of DEST and SRC will be
65218     ** unique.
65219     */
65220     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
65221     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
65222     sqlite3VdbeJumpHere(v, addr1);
65223   }else{
65224     emptyDestTest = 0;
65225   }
65226   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
65227   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
65228   regData = sqlite3GetTempReg(pParse);
65229   regRowid = sqlite3GetTempReg(pParse);
65230   if( pDest->iPKey>=0 ){
65231     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
65232     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
65233     sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
65234                       "PRIMARY KEY must be unique", P4_STATIC);
65235     sqlite3VdbeJumpHere(v, addr2);
65236     autoIncStep(pParse, regAutoinc, regRowid);
65237   }else if( pDest->pIndex==0 ){
65238     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
65239   }else{
65240     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
65241     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
65242   }
65243   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
65244   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
65245   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
65246   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
65247   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
65248   autoIncEnd(pParse, iDbDest, pDest, regAutoinc);
65249   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
65250     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
65251       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
65252     }
65253     assert( pSrcIdx );
65254     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
65255     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
65256     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
65257     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
65258                       (char*)pKey, P4_KEYINFO_HANDOFF);
65259     VdbeComment((v, "%s", pSrcIdx->zName));
65260     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
65261     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
65262                       (char*)pKey, P4_KEYINFO_HANDOFF);
65263     VdbeComment((v, "%s", pDestIdx->zName));
65264     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
65265     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
65266     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
65267     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
65268     sqlite3VdbeJumpHere(v, addr1);
65269   }
65270   sqlite3VdbeJumpHere(v, emptySrcTest);
65271   sqlite3ReleaseTempReg(pParse, regRowid);
65272   sqlite3ReleaseTempReg(pParse, regData);
65273   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
65274   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
65275   if( emptyDestTest ){
65276     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
65277     sqlite3VdbeJumpHere(v, emptyDestTest);
65278     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
65279     return 0;
65280   }else{
65281     return 1;
65282   }
65283 }
65284 #endif /* SQLITE_OMIT_XFER_OPT */
65285
65286 /* Make sure "isView" gets undefined in case this file becomes part of
65287 ** the amalgamation - so that subsequent files do not see isView as a
65288 ** macro. */
65289 #undef isView
65290
65291 /************** End of insert.c **********************************************/
65292 /************** Begin file legacy.c ******************************************/
65293 /*
65294 ** 2001 September 15
65295 **
65296 ** The author disclaims copyright to this source code.  In place of
65297 ** a legal notice, here is a blessing:
65298 **
65299 **    May you do good and not evil.
65300 **    May you find forgiveness for yourself and forgive others.
65301 **    May you share freely, never taking more than you give.
65302 **
65303 *************************************************************************
65304 ** Main file for the SQLite library.  The routines in this file
65305 ** implement the programmer interface to the library.  Routines in
65306 ** other files are for internal use by SQLite and should not be
65307 ** accessed by users of the library.
65308 **
65309 ** $Id: legacy.c,v 1.29 2008/08/02 03:50:39 drh Exp $
65310 */
65311
65312
65313 /*
65314 ** Execute SQL code.  Return one of the SQLITE_ success/failure
65315 ** codes.  Also write an error message into memory obtained from
65316 ** malloc() and make *pzErrMsg point to that message.
65317 **
65318 ** If the SQL is a query, then for each row in the query result
65319 ** the xCallback() function is called.  pArg becomes the first
65320 ** argument to xCallback().  If xCallback=NULL then no callback
65321 ** is invoked, even for queries.
65322 */
65323 SQLITE_API int sqlite3_exec(
65324   sqlite3 *db,                /* The database on which the SQL executes */
65325   const char *zSql,           /* The SQL to be executed */
65326   sqlite3_callback xCallback, /* Invoke this callback routine */
65327   void *pArg,                 /* First argument to xCallback() */
65328   char **pzErrMsg             /* Write error messages here */
65329 ){
65330   int rc = SQLITE_OK;
65331   const char *zLeftover;
65332   sqlite3_stmt *pStmt = 0;
65333   char **azCols = 0;
65334
65335   int nRetry = 0;
65336   int nCallback;
65337
65338   if( zSql==0 ) zSql = "";
65339
65340   sqlite3_mutex_enter(db->mutex);
65341   sqlite3Error(db, SQLITE_OK, 0);
65342   while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
65343     int nCol;
65344     char **azVals = 0;
65345
65346     pStmt = 0;
65347     rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
65348     assert( rc==SQLITE_OK || pStmt==0 );
65349     if( rc!=SQLITE_OK ){
65350       continue;
65351     }
65352     if( !pStmt ){
65353       /* this happens for a comment or white-space */
65354       zSql = zLeftover;
65355       continue;
65356     }
65357
65358     nCallback = 0;
65359     nCol = sqlite3_column_count(pStmt);
65360
65361     while( 1 ){
65362       int i;
65363       rc = sqlite3_step(pStmt);
65364
65365       /* Invoke the callback function if required */
65366       if( xCallback && (SQLITE_ROW==rc || 
65367           (SQLITE_DONE==rc && !nCallback && db->flags&SQLITE_NullCallback)) ){
65368         if( 0==nCallback ){
65369           if( azCols==0 ){
65370             azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
65371             if( azCols==0 ){
65372               goto exec_out;
65373             }
65374           }
65375           for(i=0; i<nCol; i++){
65376             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
65377             /* sqlite3VdbeSetColName() installs column names as UTF8
65378             ** strings so there is no way for sqlite3_column_name() to fail. */
65379             assert( azCols[i]!=0 );
65380           }
65381           nCallback++;
65382         }
65383         if( rc==SQLITE_ROW ){
65384           azVals = &azCols[nCol];
65385           for(i=0; i<nCol; i++){
65386             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
65387             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
65388               db->mallocFailed = 1;
65389               goto exec_out;
65390             }
65391           }
65392         }
65393         if( xCallback(pArg, nCol, azVals, azCols) ){
65394           rc = SQLITE_ABORT;
65395           sqlite3_finalize(pStmt);
65396           pStmt = 0;
65397           sqlite3Error(db, SQLITE_ABORT, 0);
65398           goto exec_out;
65399         }
65400       }
65401
65402       if( rc!=SQLITE_ROW ){
65403         rc = sqlite3_finalize(pStmt);
65404         pStmt = 0;
65405         if( rc!=SQLITE_SCHEMA ){
65406           nRetry = 0;
65407           zSql = zLeftover;
65408           while( isspace((unsigned char)zSql[0]) ) zSql++;
65409         }
65410         break;
65411       }
65412     }
65413
65414     sqlite3DbFree(db, azCols);
65415     azCols = 0;
65416   }
65417
65418 exec_out:
65419   if( pStmt ) sqlite3_finalize(pStmt);
65420   sqlite3DbFree(db, azCols);
65421
65422   rc = sqlite3ApiExit(db, rc);
65423   if( rc!=SQLITE_OK && rc==sqlite3_errcode(db) && pzErrMsg ){
65424     int nErrMsg = 1 + strlen(sqlite3_errmsg(db));
65425     *pzErrMsg = sqlite3Malloc(nErrMsg);
65426     if( *pzErrMsg ){
65427       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
65428     }
65429   }else if( pzErrMsg ){
65430     *pzErrMsg = 0;
65431   }
65432
65433   assert( (rc&db->errMask)==rc );
65434   sqlite3_mutex_leave(db->mutex);
65435   return rc;
65436 }
65437
65438 /************** End of legacy.c **********************************************/
65439 /************** Begin file loadext.c *****************************************/
65440 /*
65441 ** 2006 June 7
65442 **
65443 ** The author disclaims copyright to this source code.  In place of
65444 ** a legal notice, here is a blessing:
65445 **
65446 **    May you do good and not evil.
65447 **    May you find forgiveness for yourself and forgive others.
65448 **    May you share freely, never taking more than you give.
65449 **
65450 *************************************************************************
65451 ** This file contains code used to dynamically load extensions into
65452 ** the SQLite library.
65453 **
65454 ** $Id: loadext.c,v 1.54 2008/09/02 00:52:52 drh Exp $
65455 */
65456
65457 #ifndef SQLITE_CORE
65458   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
65459 #endif
65460 /************** Include sqlite3ext.h in the middle of loadext.c **************/
65461 /************** Begin file sqlite3ext.h **************************************/
65462 /*
65463 ** 2006 June 7
65464 **
65465 ** The author disclaims copyright to this source code.  In place of
65466 ** a legal notice, here is a blessing:
65467 **
65468 **    May you do good and not evil.
65469 **    May you find forgiveness for yourself and forgive others.
65470 **    May you share freely, never taking more than you give.
65471 **
65472 *************************************************************************
65473 ** This header file defines the SQLite interface for use by
65474 ** shared libraries that want to be imported as extensions into
65475 ** an SQLite instance.  Shared libraries that intend to be loaded
65476 ** as extensions by SQLite should #include this file instead of 
65477 ** sqlite3.h.
65478 **
65479 ** @(#) $Id: sqlite3ext.h,v 1.24 2008/06/30 15:09:29 danielk1977 Exp $
65480 */
65481 #ifndef _SQLITE3EXT_H_
65482 #define _SQLITE3EXT_H_
65483
65484 typedef struct sqlite3_api_routines sqlite3_api_routines;
65485
65486 /*
65487 ** The following structure holds pointers to all of the SQLite API
65488 ** routines.
65489 **
65490 ** WARNING:  In order to maintain backwards compatibility, add new
65491 ** interfaces to the end of this structure only.  If you insert new
65492 ** interfaces in the middle of this structure, then older different
65493 ** versions of SQLite will not be able to load each others' shared
65494 ** libraries!
65495 */
65496 struct sqlite3_api_routines {
65497   void * (*aggregate_context)(sqlite3_context*,int nBytes);
65498   int  (*aggregate_count)(sqlite3_context*);
65499   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
65500   int  (*bind_double)(sqlite3_stmt*,int,double);
65501   int  (*bind_int)(sqlite3_stmt*,int,int);
65502   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
65503   int  (*bind_null)(sqlite3_stmt*,int);
65504   int  (*bind_parameter_count)(sqlite3_stmt*);
65505   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
65506   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
65507   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
65508   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
65509   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
65510   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
65511   int  (*busy_timeout)(sqlite3*,int ms);
65512   int  (*changes)(sqlite3*);
65513   int  (*close)(sqlite3*);
65514   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
65515   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
65516   const void * (*column_blob)(sqlite3_stmt*,int iCol);
65517   int  (*column_bytes)(sqlite3_stmt*,int iCol);
65518   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
65519   int  (*column_count)(sqlite3_stmt*pStmt);
65520   const char * (*column_database_name)(sqlite3_stmt*,int);
65521   const void * (*column_database_name16)(sqlite3_stmt*,int);
65522   const char * (*column_decltype)(sqlite3_stmt*,int i);
65523   const void * (*column_decltype16)(sqlite3_stmt*,int);
65524   double  (*column_double)(sqlite3_stmt*,int iCol);
65525   int  (*column_int)(sqlite3_stmt*,int iCol);
65526   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
65527   const char * (*column_name)(sqlite3_stmt*,int);
65528   const void * (*column_name16)(sqlite3_stmt*,int);
65529   const char * (*column_origin_name)(sqlite3_stmt*,int);
65530   const void * (*column_origin_name16)(sqlite3_stmt*,int);
65531   const char * (*column_table_name)(sqlite3_stmt*,int);
65532   const void * (*column_table_name16)(sqlite3_stmt*,int);
65533   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
65534   const void * (*column_text16)(sqlite3_stmt*,int iCol);
65535   int  (*column_type)(sqlite3_stmt*,int iCol);
65536   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
65537   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
65538   int  (*complete)(const char*sql);
65539   int  (*complete16)(const void*sql);
65540   int  (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
65541   int  (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*));
65542   int  (*create_function)(sqlite3*,const char*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*));
65543   int  (*create_function16)(sqlite3*,const void*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*));
65544   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
65545   int  (*data_count)(sqlite3_stmt*pStmt);
65546   sqlite3 * (*db_handle)(sqlite3_stmt*);
65547   int (*declare_vtab)(sqlite3*,const char*);
65548   int  (*enable_shared_cache)(int);
65549   int  (*errcode)(sqlite3*db);
65550   const char * (*errmsg)(sqlite3*);
65551   const void * (*errmsg16)(sqlite3*);
65552   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
65553   int  (*expired)(sqlite3_stmt*);
65554   int  (*finalize)(sqlite3_stmt*pStmt);
65555   void  (*free)(void*);
65556   void  (*free_table)(char**result);
65557   int  (*get_autocommit)(sqlite3*);
65558   void * (*get_auxdata)(sqlite3_context*,int);
65559   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
65560   int  (*global_recover)(void);
65561   void  (*interruptx)(sqlite3*);
65562   sqlite_int64  (*last_insert_rowid)(sqlite3*);
65563   const char * (*libversion)(void);
65564   int  (*libversion_number)(void);
65565   void *(*malloc)(int);
65566   char * (*mprintf)(const char*,...);
65567   int  (*open)(const char*,sqlite3**);
65568   int  (*open16)(const void*,sqlite3**);
65569   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
65570   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
65571   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
65572   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
65573   void *(*realloc)(void*,int);
65574   int  (*reset)(sqlite3_stmt*pStmt);
65575   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
65576   void  (*result_double)(sqlite3_context*,double);
65577   void  (*result_error)(sqlite3_context*,const char*,int);
65578   void  (*result_error16)(sqlite3_context*,const void*,int);
65579   void  (*result_int)(sqlite3_context*,int);
65580   void  (*result_int64)(sqlite3_context*,sqlite_int64);
65581   void  (*result_null)(sqlite3_context*);
65582   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
65583   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
65584   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
65585   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
65586   void  (*result_value)(sqlite3_context*,sqlite3_value*);
65587   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
65588   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
65589   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
65590   char * (*snprintf)(int,char*,const char*,...);
65591   int  (*step)(sqlite3_stmt*);
65592   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
65593   void  (*thread_cleanup)(void);
65594   int  (*total_changes)(sqlite3*);
65595   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
65596   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
65597   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
65598   void * (*user_data)(sqlite3_context*);
65599   const void * (*value_blob)(sqlite3_value*);
65600   int  (*value_bytes)(sqlite3_value*);
65601   int  (*value_bytes16)(sqlite3_value*);
65602   double  (*value_double)(sqlite3_value*);
65603   int  (*value_int)(sqlite3_value*);
65604   sqlite_int64  (*value_int64)(sqlite3_value*);
65605   int  (*value_numeric_type)(sqlite3_value*);
65606   const unsigned char * (*value_text)(sqlite3_value*);
65607   const void * (*value_text16)(sqlite3_value*);
65608   const void * (*value_text16be)(sqlite3_value*);
65609   const void * (*value_text16le)(sqlite3_value*);
65610   int  (*value_type)(sqlite3_value*);
65611   char *(*vmprintf)(const char*,va_list);
65612   /* Added ??? */
65613   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
65614   /* Added by 3.3.13 */
65615   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
65616   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
65617   int (*clear_bindings)(sqlite3_stmt*);
65618   /* Added by 3.4.1 */
65619   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
65620   /* Added by 3.5.0 */
65621   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
65622   int (*blob_bytes)(sqlite3_blob*);
65623   int (*blob_close)(sqlite3_blob*);
65624   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
65625   int (*blob_read)(sqlite3_blob*,void*,int,int);
65626   int (*blob_write)(sqlite3_blob*,const void*,int,int);
65627   int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
65628   int (*file_control)(sqlite3*,const char*,int,void*);
65629   sqlite3_int64 (*memory_highwater)(int);
65630   sqlite3_int64 (*memory_used)(void);
65631   sqlite3_mutex *(*mutex_alloc)(int);
65632   void (*mutex_enter)(sqlite3_mutex*);
65633   void (*mutex_free)(sqlite3_mutex*);
65634   void (*mutex_leave)(sqlite3_mutex*);
65635   int (*mutex_try)(sqlite3_mutex*);
65636   int (*open_v2)(const char*,sqlite3**,int,const char*);
65637   int (*release_memory)(int);
65638   void (*result_error_nomem)(sqlite3_context*);
65639   void (*result_error_toobig)(sqlite3_context*);
65640   int (*sleep)(int);
65641   void (*soft_heap_limit)(int);
65642   sqlite3_vfs *(*vfs_find)(const char*);
65643   int (*vfs_register)(sqlite3_vfs*,int);
65644   int (*vfs_unregister)(sqlite3_vfs*);
65645   int (*xthreadsafe)(void);
65646   void (*result_zeroblob)(sqlite3_context*,int);
65647   void (*result_error_code)(sqlite3_context*,int);
65648   int (*test_control)(int, ...);
65649   void (*randomness)(int,void*);
65650   sqlite3 *(*context_db_handle)(sqlite3_context*);
65651   int (*extended_result_codes)(sqlite3*,int);
65652   int (*limit)(sqlite3*,int,int);
65653   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
65654   const char *(*sql)(sqlite3_stmt*);
65655   int (*status)(int,int*,int*,int);
65656 };
65657
65658 /*
65659 ** The following macros redefine the API routines so that they are
65660 ** redirected throught the global sqlite3_api structure.
65661 **
65662 ** This header file is also used by the loadext.c source file
65663 ** (part of the main SQLite library - not an extension) so that
65664 ** it can get access to the sqlite3_api_routines structure
65665 ** definition.  But the main library does not want to redefine
65666 ** the API.  So the redefinition macros are only valid if the
65667 ** SQLITE_CORE macros is undefined.
65668 */
65669 #ifndef SQLITE_CORE
65670 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
65671 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
65672 #define sqlite3_bind_blob              sqlite3_api->bind_blob
65673 #define sqlite3_bind_double            sqlite3_api->bind_double
65674 #define sqlite3_bind_int               sqlite3_api->bind_int
65675 #define sqlite3_bind_int64             sqlite3_api->bind_int64
65676 #define sqlite3_bind_null              sqlite3_api->bind_null
65677 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
65678 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
65679 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
65680 #define sqlite3_bind_text              sqlite3_api->bind_text
65681 #define sqlite3_bind_text16            sqlite3_api->bind_text16
65682 #define sqlite3_bind_value             sqlite3_api->bind_value
65683 #define sqlite3_busy_handler           sqlite3_api->busy_handler
65684 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
65685 #define sqlite3_changes                sqlite3_api->changes
65686 #define sqlite3_close                  sqlite3_api->close
65687 #define sqlite3_collation_needed       sqlite3_api->collation_needed
65688 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
65689 #define sqlite3_column_blob            sqlite3_api->column_blob
65690 #define sqlite3_column_bytes           sqlite3_api->column_bytes
65691 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
65692 #define sqlite3_column_count           sqlite3_api->column_count
65693 #define sqlite3_column_database_name   sqlite3_api->column_database_name
65694 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
65695 #define sqlite3_column_decltype        sqlite3_api->column_decltype
65696 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
65697 #define sqlite3_column_double          sqlite3_api->column_double
65698 #define sqlite3_column_int             sqlite3_api->column_int
65699 #define sqlite3_column_int64           sqlite3_api->column_int64
65700 #define sqlite3_column_name            sqlite3_api->column_name
65701 #define sqlite3_column_name16          sqlite3_api->column_name16
65702 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
65703 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
65704 #define sqlite3_column_table_name      sqlite3_api->column_table_name
65705 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
65706 #define sqlite3_column_text            sqlite3_api->column_text
65707 #define sqlite3_column_text16          sqlite3_api->column_text16
65708 #define sqlite3_column_type            sqlite3_api->column_type
65709 #define sqlite3_column_value           sqlite3_api->column_value
65710 #define sqlite3_commit_hook            sqlite3_api->commit_hook
65711 #define sqlite3_complete               sqlite3_api->complete
65712 #define sqlite3_complete16             sqlite3_api->complete16
65713 #define sqlite3_create_collation       sqlite3_api->create_collation
65714 #define sqlite3_create_collation16     sqlite3_api->create_collation16
65715 #define sqlite3_create_function        sqlite3_api->create_function
65716 #define sqlite3_create_function16      sqlite3_api->create_function16
65717 #define sqlite3_create_module          sqlite3_api->create_module
65718 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
65719 #define sqlite3_data_count             sqlite3_api->data_count
65720 #define sqlite3_db_handle              sqlite3_api->db_handle
65721 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
65722 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
65723 #define sqlite3_errcode                sqlite3_api->errcode
65724 #define sqlite3_errmsg                 sqlite3_api->errmsg
65725 #define sqlite3_errmsg16               sqlite3_api->errmsg16
65726 #define sqlite3_exec                   sqlite3_api->exec
65727 #define sqlite3_expired                sqlite3_api->expired
65728 #define sqlite3_finalize               sqlite3_api->finalize
65729 #define sqlite3_free                   sqlite3_api->free
65730 #define sqlite3_free_table             sqlite3_api->free_table
65731 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
65732 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
65733 #define sqlite3_get_table              sqlite3_api->get_table
65734 #define sqlite3_global_recover         sqlite3_api->global_recover
65735 #define sqlite3_interrupt              sqlite3_api->interruptx
65736 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
65737 #define sqlite3_libversion             sqlite3_api->libversion
65738 #define sqlite3_libversion_number      sqlite3_api->libversion_number
65739 #define sqlite3_malloc                 sqlite3_api->malloc
65740 #define sqlite3_mprintf                sqlite3_api->mprintf
65741 #define sqlite3_open                   sqlite3_api->open
65742 #define sqlite3_open16                 sqlite3_api->open16
65743 #define sqlite3_prepare                sqlite3_api->prepare
65744 #define sqlite3_prepare16              sqlite3_api->prepare16
65745 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
65746 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
65747 #define sqlite3_profile                sqlite3_api->profile
65748 #define sqlite3_progress_handler       sqlite3_api->progress_handler
65749 #define sqlite3_realloc                sqlite3_api->realloc
65750 #define sqlite3_reset                  sqlite3_api->reset
65751 #define sqlite3_result_blob            sqlite3_api->result_blob
65752 #define sqlite3_result_double          sqlite3_api->result_double
65753 #define sqlite3_result_error           sqlite3_api->result_error
65754 #define sqlite3_result_error16         sqlite3_api->result_error16
65755 #define sqlite3_result_int             sqlite3_api->result_int
65756 #define sqlite3_result_int64           sqlite3_api->result_int64
65757 #define sqlite3_result_null            sqlite3_api->result_null
65758 #define sqlite3_result_text            sqlite3_api->result_text
65759 #define sqlite3_result_text16          sqlite3_api->result_text16
65760 #define sqlite3_result_text16be        sqlite3_api->result_text16be
65761 #define sqlite3_result_text16le        sqlite3_api->result_text16le
65762 #define sqlite3_result_value           sqlite3_api->result_value
65763 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
65764 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
65765 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
65766 #define sqlite3_snprintf               sqlite3_api->snprintf
65767 #define sqlite3_step                   sqlite3_api->step
65768 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
65769 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
65770 #define sqlite3_total_changes          sqlite3_api->total_changes
65771 #define sqlite3_trace                  sqlite3_api->trace
65772 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
65773 #define sqlite3_update_hook            sqlite3_api->update_hook
65774 #define sqlite3_user_data              sqlite3_api->user_data
65775 #define sqlite3_value_blob             sqlite3_api->value_blob
65776 #define sqlite3_value_bytes            sqlite3_api->value_bytes
65777 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
65778 #define sqlite3_value_double           sqlite3_api->value_double
65779 #define sqlite3_value_int              sqlite3_api->value_int
65780 #define sqlite3_value_int64            sqlite3_api->value_int64
65781 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
65782 #define sqlite3_value_text             sqlite3_api->value_text
65783 #define sqlite3_value_text16           sqlite3_api->value_text16
65784 #define sqlite3_value_text16be         sqlite3_api->value_text16be
65785 #define sqlite3_value_text16le         sqlite3_api->value_text16le
65786 #define sqlite3_value_type             sqlite3_api->value_type
65787 #define sqlite3_vmprintf               sqlite3_api->vmprintf
65788 #define sqlite3_overload_function      sqlite3_api->overload_function
65789 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
65790 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
65791 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
65792 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
65793 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
65794 #define sqlite3_blob_close             sqlite3_api->blob_close
65795 #define sqlite3_blob_open              sqlite3_api->blob_open
65796 #define sqlite3_blob_read              sqlite3_api->blob_read
65797 #define sqlite3_blob_write             sqlite3_api->blob_write
65798 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
65799 #define sqlite3_file_control           sqlite3_api->file_control
65800 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
65801 #define sqlite3_memory_used            sqlite3_api->memory_used
65802 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
65803 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
65804 #define sqlite3_mutex_free             sqlite3_api->mutex_free
65805 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
65806 #define sqlite3_mutex_try              sqlite3_api->mutex_try
65807 #define sqlite3_open_v2                sqlite3_api->open_v2
65808 #define sqlite3_release_memory         sqlite3_api->release_memory
65809 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
65810 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
65811 #define sqlite3_sleep                  sqlite3_api->sleep
65812 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
65813 #define sqlite3_vfs_find               sqlite3_api->vfs_find
65814 #define sqlite3_vfs_register           sqlite3_api->vfs_register
65815 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
65816 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
65817 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
65818 #define sqlite3_result_error_code      sqlite3_api->result_error_code
65819 #define sqlite3_test_control           sqlite3_api->test_control
65820 #define sqlite3_randomness             sqlite3_api->randomness
65821 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
65822 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
65823 #define sqlite3_limit                  sqlite3_api->limit
65824 #define sqlite3_next_stmt              sqlite3_api->next_stmt
65825 #define sqlite3_sql                    sqlite3_api->sql
65826 #define sqlite3_status                 sqlite3_api->status
65827 #endif /* SQLITE_CORE */
65828
65829 #define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
65830 #define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
65831
65832 #endif /* _SQLITE3EXT_H_ */
65833
65834 /************** End of sqlite3ext.h ******************************************/
65835 /************** Continuing where we left off in loadext.c ********************/
65836
65837 #ifndef SQLITE_OMIT_LOAD_EXTENSION
65838
65839 /*
65840 ** Some API routines are omitted when various features are
65841 ** excluded from a build of SQLite.  Substitute a NULL pointer
65842 ** for any missing APIs.
65843 */
65844 #ifndef SQLITE_ENABLE_COLUMN_METADATA
65845 # define sqlite3_column_database_name   0
65846 # define sqlite3_column_database_name16 0
65847 # define sqlite3_column_table_name      0
65848 # define sqlite3_column_table_name16    0
65849 # define sqlite3_column_origin_name     0
65850 # define sqlite3_column_origin_name16   0
65851 # define sqlite3_table_column_metadata  0
65852 #endif
65853
65854 #ifdef SQLITE_OMIT_AUTHORIZATION
65855 # define sqlite3_set_authorizer         0
65856 #endif
65857
65858 #ifdef SQLITE_OMIT_UTF16
65859 # define sqlite3_bind_text16            0
65860 # define sqlite3_collation_needed16     0
65861 # define sqlite3_column_decltype16      0
65862 # define sqlite3_column_name16          0
65863 # define sqlite3_column_text16          0
65864 # define sqlite3_complete16             0
65865 # define sqlite3_create_collation16     0
65866 # define sqlite3_create_function16      0
65867 # define sqlite3_errmsg16               0
65868 # define sqlite3_open16                 0
65869 # define sqlite3_prepare16              0
65870 # define sqlite3_prepare16_v2           0
65871 # define sqlite3_result_error16         0
65872 # define sqlite3_result_text16          0
65873 # define sqlite3_result_text16be        0
65874 # define sqlite3_result_text16le        0
65875 # define sqlite3_value_text16           0
65876 # define sqlite3_value_text16be         0
65877 # define sqlite3_value_text16le         0
65878 # define sqlite3_column_database_name16 0
65879 # define sqlite3_column_table_name16    0
65880 # define sqlite3_column_origin_name16   0
65881 #endif
65882
65883 #ifdef SQLITE_OMIT_COMPLETE
65884 # define sqlite3_complete 0
65885 # define sqlite3_complete16 0
65886 #endif
65887
65888 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
65889 # define sqlite3_progress_handler 0
65890 #endif
65891
65892 #ifdef SQLITE_OMIT_VIRTUALTABLE
65893 # define sqlite3_create_module 0
65894 # define sqlite3_create_module_v2 0
65895 # define sqlite3_declare_vtab 0
65896 #endif
65897
65898 #ifdef SQLITE_OMIT_SHARED_CACHE
65899 # define sqlite3_enable_shared_cache 0
65900 #endif
65901
65902 #ifdef SQLITE_OMIT_TRACE
65903 # define sqlite3_profile       0
65904 # define sqlite3_trace         0
65905 #endif
65906
65907 #ifdef SQLITE_OMIT_GET_TABLE
65908 # define sqlite3_free_table    0
65909 # define sqlite3_get_table     0
65910 #endif
65911
65912 #ifdef SQLITE_OMIT_INCRBLOB
65913 #define sqlite3_bind_zeroblob  0
65914 #define sqlite3_blob_bytes     0
65915 #define sqlite3_blob_close     0
65916 #define sqlite3_blob_open      0
65917 #define sqlite3_blob_read      0
65918 #define sqlite3_blob_write     0
65919 #endif
65920
65921 /*
65922 ** The following structure contains pointers to all SQLite API routines.
65923 ** A pointer to this structure is passed into extensions when they are
65924 ** loaded so that the extension can make calls back into the SQLite
65925 ** library.
65926 **
65927 ** When adding new APIs, add them to the bottom of this structure
65928 ** in order to preserve backwards compatibility.
65929 **
65930 ** Extensions that use newer APIs should first call the
65931 ** sqlite3_libversion_number() to make sure that the API they
65932 ** intend to use is supported by the library.  Extensions should
65933 ** also check to make sure that the pointer to the function is
65934 ** not NULL before calling it.
65935 */
65936 static const sqlite3_api_routines sqlite3Apis = {
65937   sqlite3_aggregate_context,
65938   sqlite3_aggregate_count,
65939   sqlite3_bind_blob,
65940   sqlite3_bind_double,
65941   sqlite3_bind_int,
65942   sqlite3_bind_int64,
65943   sqlite3_bind_null,
65944   sqlite3_bind_parameter_count,
65945   sqlite3_bind_parameter_index,
65946   sqlite3_bind_parameter_name,
65947   sqlite3_bind_text,
65948   sqlite3_bind_text16,
65949   sqlite3_bind_value,
65950   sqlite3_busy_handler,
65951   sqlite3_busy_timeout,
65952   sqlite3_changes,
65953   sqlite3_close,
65954   sqlite3_collation_needed,
65955   sqlite3_collation_needed16,
65956   sqlite3_column_blob,
65957   sqlite3_column_bytes,
65958   sqlite3_column_bytes16,
65959   sqlite3_column_count,
65960   sqlite3_column_database_name,
65961   sqlite3_column_database_name16,
65962   sqlite3_column_decltype,
65963   sqlite3_column_decltype16,
65964   sqlite3_column_double,
65965   sqlite3_column_int,
65966   sqlite3_column_int64,
65967   sqlite3_column_name,
65968   sqlite3_column_name16,
65969   sqlite3_column_origin_name,
65970   sqlite3_column_origin_name16,
65971   sqlite3_column_table_name,
65972   sqlite3_column_table_name16,
65973   sqlite3_column_text,
65974   sqlite3_column_text16,
65975   sqlite3_column_type,
65976   sqlite3_column_value,
65977   sqlite3_commit_hook,
65978   sqlite3_complete,
65979   sqlite3_complete16,
65980   sqlite3_create_collation,
65981   sqlite3_create_collation16,
65982   sqlite3_create_function,
65983   sqlite3_create_function16,
65984   sqlite3_create_module,
65985   sqlite3_data_count,
65986   sqlite3_db_handle,
65987   sqlite3_declare_vtab,
65988   sqlite3_enable_shared_cache,
65989   sqlite3_errcode,
65990   sqlite3_errmsg,
65991   sqlite3_errmsg16,
65992   sqlite3_exec,
65993   sqlite3_expired,
65994   sqlite3_finalize,
65995   sqlite3_free,
65996   sqlite3_free_table,
65997   sqlite3_get_autocommit,
65998   sqlite3_get_auxdata,
65999   sqlite3_get_table,
66000   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
66001   sqlite3_interrupt,
66002   sqlite3_last_insert_rowid,
66003   sqlite3_libversion,
66004   sqlite3_libversion_number,
66005   sqlite3_malloc,
66006   sqlite3_mprintf,
66007   sqlite3_open,
66008   sqlite3_open16,
66009   sqlite3_prepare,
66010   sqlite3_prepare16,
66011   sqlite3_profile,
66012   sqlite3_progress_handler,
66013   sqlite3_realloc,
66014   sqlite3_reset,
66015   sqlite3_result_blob,
66016   sqlite3_result_double,
66017   sqlite3_result_error,
66018   sqlite3_result_error16,
66019   sqlite3_result_int,
66020   sqlite3_result_int64,
66021   sqlite3_result_null,
66022   sqlite3_result_text,
66023   sqlite3_result_text16,
66024   sqlite3_result_text16be,
66025   sqlite3_result_text16le,
66026   sqlite3_result_value,
66027   sqlite3_rollback_hook,
66028   sqlite3_set_authorizer,
66029   sqlite3_set_auxdata,
66030   sqlite3_snprintf,
66031   sqlite3_step,
66032   sqlite3_table_column_metadata,
66033   sqlite3_thread_cleanup,
66034   sqlite3_total_changes,
66035   sqlite3_trace,
66036   sqlite3_transfer_bindings,
66037   sqlite3_update_hook,
66038   sqlite3_user_data,
66039   sqlite3_value_blob,
66040   sqlite3_value_bytes,
66041   sqlite3_value_bytes16,
66042   sqlite3_value_double,
66043   sqlite3_value_int,
66044   sqlite3_value_int64,
66045   sqlite3_value_numeric_type,
66046   sqlite3_value_text,
66047   sqlite3_value_text16,
66048   sqlite3_value_text16be,
66049   sqlite3_value_text16le,
66050   sqlite3_value_type,
66051   sqlite3_vmprintf,
66052   /*
66053   ** The original API set ends here.  All extensions can call any
66054   ** of the APIs above provided that the pointer is not NULL.  But
66055   ** before calling APIs that follow, extension should check the
66056   ** sqlite3_libversion_number() to make sure they are dealing with
66057   ** a library that is new enough to support that API.
66058   *************************************************************************
66059   */
66060   sqlite3_overload_function,
66061
66062   /*
66063   ** Added after 3.3.13
66064   */
66065   sqlite3_prepare_v2,
66066   sqlite3_prepare16_v2,
66067   sqlite3_clear_bindings,
66068
66069   /*
66070   ** Added for 3.4.1
66071   */
66072   sqlite3_create_module_v2,
66073
66074   /*
66075   ** Added for 3.5.0
66076   */
66077   sqlite3_bind_zeroblob,
66078   sqlite3_blob_bytes,
66079   sqlite3_blob_close,
66080   sqlite3_blob_open,
66081   sqlite3_blob_read,
66082   sqlite3_blob_write,
66083   sqlite3_create_collation_v2,
66084   sqlite3_file_control,
66085   sqlite3_memory_highwater,
66086   sqlite3_memory_used,
66087 #ifdef SQLITE_MUTEX_NOOP
66088   0, 
66089   0, 
66090   0,
66091   0,
66092   0,
66093 #else
66094   sqlite3_mutex_alloc,
66095   sqlite3_mutex_enter,
66096   sqlite3_mutex_free,
66097   sqlite3_mutex_leave,
66098   sqlite3_mutex_try,
66099 #endif
66100   sqlite3_open_v2,
66101   sqlite3_release_memory,
66102   sqlite3_result_error_nomem,
66103   sqlite3_result_error_toobig,
66104   sqlite3_sleep,
66105   sqlite3_soft_heap_limit,
66106   sqlite3_vfs_find,
66107   sqlite3_vfs_register,
66108   sqlite3_vfs_unregister,
66109
66110   /*
66111   ** Added for 3.5.8
66112   */
66113   sqlite3_threadsafe,
66114   sqlite3_result_zeroblob,
66115   sqlite3_result_error_code,
66116   sqlite3_test_control,
66117   sqlite3_randomness,
66118   sqlite3_context_db_handle,
66119
66120   /*
66121   ** Added for 3.6.0
66122   */
66123   sqlite3_extended_result_codes,
66124   sqlite3_limit,
66125   sqlite3_next_stmt,
66126   sqlite3_sql,
66127   sqlite3_status,
66128 };
66129
66130 /*
66131 ** Attempt to load an SQLite extension library contained in the file
66132 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
66133 ** default entry point name (sqlite3_extension_init) is used.  Use
66134 ** of the default name is recommended.
66135 **
66136 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
66137 **
66138 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
66139 ** error message text.  The calling function should free this memory
66140 ** by calling sqlite3DbFree(db, ).
66141 */
66142 static int sqlite3LoadExtension(
66143   sqlite3 *db,          /* Load the extension into this database connection */
66144   const char *zFile,    /* Name of the shared library containing extension */
66145   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
66146   char **pzErrMsg       /* Put error message here if not 0 */
66147 ){
66148   sqlite3_vfs *pVfs = db->pVfs;
66149   void *handle;
66150   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
66151   char *zErrmsg = 0;
66152   void **aHandle;
66153
66154   /* Ticket #1863.  To avoid a creating security problems for older
66155   ** applications that relink against newer versions of SQLite, the
66156   ** ability to run load_extension is turned off by default.  One
66157   ** must call sqlite3_enable_load_extension() to turn on extension
66158   ** loading.  Otherwise you get the following error.
66159   */
66160   if( (db->flags & SQLITE_LoadExtension)==0 ){
66161     if( pzErrMsg ){
66162       *pzErrMsg = sqlite3_mprintf("not authorized");
66163     }
66164     return SQLITE_ERROR;
66165   }
66166
66167   if( zProc==0 ){
66168     zProc = "sqlite3_extension_init";
66169   }
66170
66171   handle = sqlite3OsDlOpen(pVfs, zFile);
66172   if( handle==0 ){
66173     if( pzErrMsg ){
66174       char zErr[256];
66175       zErr[sizeof(zErr)-1] = '\0';
66176       sqlite3_snprintf(sizeof(zErr)-1, zErr, 
66177           "unable to open shared library [%s]", zFile);
66178       sqlite3OsDlError(pVfs, sizeof(zErr)-1, zErr);
66179       *pzErrMsg = sqlite3DbStrDup(0, zErr);
66180     }
66181     return SQLITE_ERROR;
66182   }
66183   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
66184                    sqlite3OsDlSym(pVfs, handle, zProc);
66185   if( xInit==0 ){
66186     if( pzErrMsg ){
66187       char zErr[256];
66188       zErr[sizeof(zErr)-1] = '\0';
66189       sqlite3_snprintf(sizeof(zErr)-1, zErr,
66190           "no entry point [%s] in shared library [%s]", zProc,zFile);
66191       sqlite3OsDlError(pVfs, sizeof(zErr)-1, zErr);
66192       *pzErrMsg = sqlite3DbStrDup(0, zErr);
66193       sqlite3OsDlClose(pVfs, handle);
66194     }
66195     return SQLITE_ERROR;
66196   }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
66197     if( pzErrMsg ){
66198       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
66199     }
66200     sqlite3_free(zErrmsg);
66201     sqlite3OsDlClose(pVfs, handle);
66202     return SQLITE_ERROR;
66203   }
66204
66205   /* Append the new shared library handle to the db->aExtension array. */
66206   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
66207   if( aHandle==0 ){
66208     return SQLITE_NOMEM;
66209   }
66210   if( db->nExtension>0 ){
66211     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
66212   }
66213   sqlite3DbFree(db, db->aExtension);
66214   db->aExtension = aHandle;
66215
66216   db->aExtension[db->nExtension++] = handle;
66217   return SQLITE_OK;
66218 }
66219 SQLITE_API int sqlite3_load_extension(
66220   sqlite3 *db,          /* Load the extension into this database connection */
66221   const char *zFile,    /* Name of the shared library containing extension */
66222   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
66223   char **pzErrMsg       /* Put error message here if not 0 */
66224 ){
66225   int rc;
66226   sqlite3_mutex_enter(db->mutex);
66227   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
66228   sqlite3_mutex_leave(db->mutex);
66229   return rc;
66230 }
66231
66232 /*
66233 ** Call this routine when the database connection is closing in order
66234 ** to clean up loaded extensions
66235 */
66236 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
66237   int i;
66238   assert( sqlite3_mutex_held(db->mutex) );
66239   for(i=0; i<db->nExtension; i++){
66240     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
66241   }
66242   sqlite3DbFree(db, db->aExtension);
66243 }
66244
66245 /*
66246 ** Enable or disable extension loading.  Extension loading is disabled by
66247 ** default so as not to open security holes in older applications.
66248 */
66249 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
66250   sqlite3_mutex_enter(db->mutex);
66251   if( onoff ){
66252     db->flags |= SQLITE_LoadExtension;
66253   }else{
66254     db->flags &= ~SQLITE_LoadExtension;
66255   }
66256   sqlite3_mutex_leave(db->mutex);
66257   return SQLITE_OK;
66258 }
66259
66260 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
66261
66262 /*
66263 ** The auto-extension code added regardless of whether or not extension
66264 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
66265 ** code if regular extension loading is not available.  This is that
66266 ** dummy pointer.
66267 */
66268 #ifdef SQLITE_OMIT_LOAD_EXTENSION
66269 static const sqlite3_api_routines sqlite3Apis = { 0 };
66270 #endif
66271
66272
66273 /*
66274 ** The following object holds the list of automatically loaded
66275 ** extensions.
66276 **
66277 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
66278 ** mutex must be held while accessing this list.
66279 */
66280 typedef struct sqlite3ExtType sqlite3ExtType;
66281 static SQLITE_WSD struct sqlite3ExtType {
66282   int nExt;        /* Number of entries in aExt[] */          
66283   void **aExt;     /* Pointers to the extension init functions */
66284 } sqlite3Autoext = { 0, 0 };
66285
66286 /* The "wsdAutoext" macro will resolve to the autoextension
66287 ** state vector.  If writable static data is unsupported on the target,
66288 ** we have to locate the state vector at run-time.  In the more common
66289 ** case where writable static data is supported, wsdStat can refer directly
66290 ** to the "sqlite3Autoext" state vector declared above.
66291 */
66292 #ifdef SQLITE_OMIT_WSD
66293 # define wsdAutoextInit \
66294   sqlite3ExtType *x = &GLOBAL(sqlite3ExtType,sqlite3Autoext)
66295 # define wsdAutoext x[0]
66296 #else
66297 # define wsdAutoextInit
66298 # define wsdAutoext sqlite3Autoext
66299 #endif
66300
66301
66302 /*
66303 ** Register a statically linked extension that is automatically
66304 ** loaded by every new database connection.
66305 */
66306 SQLITE_API int sqlite3_auto_extension(void *xInit){
66307   int rc = SQLITE_OK;
66308 #ifndef SQLITE_OMIT_AUTOINIT
66309   rc = sqlite3_initialize();
66310   if( rc ){
66311     return rc;
66312   }else
66313 #endif
66314   {
66315     int i;
66316 #ifndef SQLITE_MUTEX_NOOP
66317     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
66318 #endif
66319     wsdAutoextInit;
66320     sqlite3_mutex_enter(mutex);
66321     for(i=0; i<wsdAutoext.nExt; i++){
66322       if( wsdAutoext.aExt[i]==xInit ) break;
66323     }
66324     if( i==wsdAutoext.nExt ){
66325       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
66326       void **aNew;
66327       aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
66328       if( aNew==0 ){
66329         rc = SQLITE_NOMEM;
66330       }else{
66331         wsdAutoext.aExt = aNew;
66332         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
66333         wsdAutoext.nExt++;
66334       }
66335     }
66336     sqlite3_mutex_leave(mutex);
66337     assert( (rc&0xff)==rc );
66338     return rc;
66339   }
66340 }
66341
66342 /*
66343 ** Reset the automatic extension loading mechanism.
66344 */
66345 SQLITE_API void sqlite3_reset_auto_extension(void){
66346 #ifndef SQLITE_OMIT_AUTOINIT
66347   if( sqlite3_initialize()==SQLITE_OK )
66348 #endif
66349   {
66350 #ifndef SQLITE_MUTEX_NOOP
66351     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
66352 #endif
66353     wsdAutoextInit;
66354     sqlite3_mutex_enter(mutex);
66355     sqlite3_free(wsdAutoext.aExt);
66356     wsdAutoext.aExt = 0;
66357     wsdAutoext.nExt = 0;
66358     sqlite3_mutex_leave(mutex);
66359   }
66360 }
66361
66362 /*
66363 ** Load all automatic extensions.
66364 */
66365 SQLITE_PRIVATE int sqlite3AutoLoadExtensions(sqlite3 *db){
66366   int i;
66367   int go = 1;
66368   int rc = SQLITE_OK;
66369   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
66370
66371   wsdAutoextInit;
66372   if( wsdAutoext.nExt==0 ){
66373     /* Common case: early out without every having to acquire a mutex */
66374     return SQLITE_OK;
66375   }
66376   for(i=0; go; i++){
66377     char *zErrmsg = 0;
66378 #ifndef SQLITE_MUTEX_NOOP
66379     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
66380 #endif
66381     sqlite3_mutex_enter(mutex);
66382     if( i>=wsdAutoext.nExt ){
66383       xInit = 0;
66384       go = 0;
66385     }else{
66386       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
66387               wsdAutoext.aExt[i];
66388     }
66389     sqlite3_mutex_leave(mutex);
66390     if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
66391       sqlite3Error(db, SQLITE_ERROR,
66392             "automatic extension loading failed: %s", zErrmsg);
66393       go = 0;
66394       rc = SQLITE_ERROR;
66395       sqlite3_free(zErrmsg);
66396     }
66397   }
66398   return rc;
66399 }
66400
66401 /************** End of loadext.c *********************************************/
66402 /************** Begin file pragma.c ******************************************/
66403 /*
66404 ** 2003 April 6
66405 **
66406 ** The author disclaims copyright to this source code.  In place of
66407 ** a legal notice, here is a blessing:
66408 **
66409 **    May you do good and not evil.
66410 **    May you find forgiveness for yourself and forgive others.
66411 **    May you share freely, never taking more than you give.
66412 **
66413 *************************************************************************
66414 ** This file contains code used to implement the PRAGMA command.
66415 **
66416 ** $Id: pragma.c,v 1.187 2008/09/16 14:38:03 danielk1977 Exp $
66417 */
66418
66419 /* Ignore this whole file if pragmas are disabled
66420 */
66421 #if !defined(SQLITE_OMIT_PRAGMA) && !defined(SQLITE_OMIT_PARSER)
66422
66423 /*
66424 ** Interpret the given string as a safety level.  Return 0 for OFF,
66425 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or 
66426 ** unrecognized string argument.
66427 **
66428 ** Note that the values returned are one less that the values that
66429 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
66430 ** to support legacy SQL code.  The safety level used to be boolean
66431 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
66432 */
66433 static int getSafetyLevel(const char *z){
66434                              /* 123456789 123456789 */
66435   static const char zText[] = "onoffalseyestruefull";
66436   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
66437   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
66438   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
66439   int i, n;
66440   if( isdigit(*z) ){
66441     return atoi(z);
66442   }
66443   n = strlen(z);
66444   for(i=0; i<sizeof(iLength); i++){
66445     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
66446       return iValue[i];
66447     }
66448   }
66449   return 1;
66450 }
66451
66452 /*
66453 ** Interpret the given string as a boolean value.
66454 */
66455 static int getBoolean(const char *z){
66456   return getSafetyLevel(z)&1;
66457 }
66458
66459 /*
66460 ** Interpret the given string as a locking mode value.
66461 */
66462 static int getLockingMode(const char *z){
66463   if( z ){
66464     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
66465     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
66466   }
66467   return PAGER_LOCKINGMODE_QUERY;
66468 }
66469
66470 #ifndef SQLITE_OMIT_AUTOVACUUM
66471 /*
66472 ** Interpret the given string as an auto-vacuum mode value.
66473 **
66474 ** The following strings, "none", "full" and "incremental" are 
66475 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
66476 */
66477 static int getAutoVacuum(const char *z){
66478   int i;
66479   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
66480   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
66481   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
66482   i = atoi(z);
66483   return ((i>=0&&i<=2)?i:0);
66484 }
66485 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
66486
66487 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
66488 /*
66489 ** Interpret the given string as a temp db location. Return 1 for file
66490 ** backed temporary databases, 2 for the Red-Black tree in memory database
66491 ** and 0 to use the compile-time default.
66492 */
66493 static int getTempStore(const char *z){
66494   if( z[0]>='0' && z[0]<='2' ){
66495     return z[0] - '0';
66496   }else if( sqlite3StrICmp(z, "file")==0 ){
66497     return 1;
66498   }else if( sqlite3StrICmp(z, "memory")==0 ){
66499     return 2;
66500   }else{
66501     return 0;
66502   }
66503 }
66504 #endif /* SQLITE_PAGER_PRAGMAS */
66505
66506 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
66507 /*
66508 ** Invalidate temp storage, either when the temp storage is changed
66509 ** from default, or when 'file' and the temp_store_directory has changed
66510 */
66511 static int invalidateTempStorage(Parse *pParse){
66512   sqlite3 *db = pParse->db;
66513   if( db->aDb[1].pBt!=0 ){
66514     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
66515       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
66516         "from within a transaction");
66517       return SQLITE_ERROR;
66518     }
66519     sqlite3BtreeClose(db->aDb[1].pBt);
66520     db->aDb[1].pBt = 0;
66521     sqlite3ResetInternalSchema(db, 0);
66522   }
66523   return SQLITE_OK;
66524 }
66525 #endif /* SQLITE_PAGER_PRAGMAS */
66526
66527 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
66528 /*
66529 ** If the TEMP database is open, close it and mark the database schema
66530 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
66531 ** or DEFAULT_TEMP_STORE pragmas.
66532 */
66533 static int changeTempStorage(Parse *pParse, const char *zStorageType){
66534   int ts = getTempStore(zStorageType);
66535   sqlite3 *db = pParse->db;
66536   if( db->temp_store==ts ) return SQLITE_OK;
66537   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
66538     return SQLITE_ERROR;
66539   }
66540   db->temp_store = ts;
66541   return SQLITE_OK;
66542 }
66543 #endif /* SQLITE_PAGER_PRAGMAS */
66544
66545 /*
66546 ** Generate code to return a single integer value.
66547 */
66548 static void returnSingleInt(Parse *pParse, const char *zLabel, int value){
66549   Vdbe *v = sqlite3GetVdbe(pParse);
66550   int mem = ++pParse->nMem;
66551   sqlite3VdbeAddOp2(v, OP_Integer, value, mem);
66552   if( pParse->explain==0 ){
66553     sqlite3VdbeSetNumCols(v, 1);
66554     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, P4_STATIC);
66555   }
66556   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
66557 }
66558
66559 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
66560 /*
66561 ** Check to see if zRight and zLeft refer to a pragma that queries
66562 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
66563 ** Also, implement the pragma.
66564 */
66565 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
66566   static const struct sPragmaType {
66567     const char *zName;  /* Name of the pragma */
66568     int mask;           /* Mask for the db->flags value */
66569   } aPragma[] = {
66570     { "full_column_names",        SQLITE_FullColNames  },
66571     { "short_column_names",       SQLITE_ShortColNames },
66572     { "count_changes",            SQLITE_CountRows     },
66573     { "empty_result_callbacks",   SQLITE_NullCallback  },
66574     { "legacy_file_format",       SQLITE_LegacyFileFmt },
66575     { "fullfsync",                SQLITE_FullFSync     },
66576 #ifdef SQLITE_DEBUG
66577     { "sql_trace",                SQLITE_SqlTrace      },
66578     { "vdbe_listing",             SQLITE_VdbeListing   },
66579     { "vdbe_trace",               SQLITE_VdbeTrace     },
66580 #endif
66581 #ifndef SQLITE_OMIT_CHECK
66582     { "ignore_check_constraints", SQLITE_IgnoreChecks  },
66583 #endif
66584     /* The following is VERY experimental */
66585     { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
66586     { "omit_readlock",            SQLITE_NoReadlock    },
66587
66588     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
66589     ** flag if there are any active statements. */
66590     { "read_uncommitted",         SQLITE_ReadUncommitted },
66591   };
66592   int i;
66593   const struct sPragmaType *p;
66594   for(i=0, p=aPragma; i<sizeof(aPragma)/sizeof(aPragma[0]); i++, p++){
66595     if( sqlite3StrICmp(zLeft, p->zName)==0 ){
66596       sqlite3 *db = pParse->db;
66597       Vdbe *v;
66598       v = sqlite3GetVdbe(pParse);
66599       if( v ){
66600         if( zRight==0 ){
66601           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
66602         }else{
66603           if( getBoolean(zRight) ){
66604             db->flags |= p->mask;
66605           }else{
66606             db->flags &= ~p->mask;
66607           }
66608
66609           /* Many of the flag-pragmas modify the code generated by the SQL 
66610           ** compiler (eg. count_changes). So add an opcode to expire all
66611           ** compiled SQL statements after modifying a pragma value.
66612           */
66613           sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
66614         }
66615       }
66616
66617       return 1;
66618     }
66619   }
66620   return 0;
66621 }
66622 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
66623
66624 /*
66625 ** Process a pragma statement.  
66626 **
66627 ** Pragmas are of this form:
66628 **
66629 **      PRAGMA [database.]id [= value]
66630 **
66631 ** The identifier might also be a string.  The value is a string, and
66632 ** identifier, or a number.  If minusFlag is true, then the value is
66633 ** a number that was preceded by a minus sign.
66634 **
66635 ** If the left side is "database.id" then pId1 is the database name
66636 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
66637 ** id and pId2 is any empty string.
66638 */
66639 SQLITE_PRIVATE void sqlite3Pragma(
66640   Parse *pParse, 
66641   Token *pId1,        /* First part of [database.]id field */
66642   Token *pId2,        /* Second part of [database.]id field, or NULL */
66643   Token *pValue,      /* Token for <value>, or NULL */
66644   int minusFlag       /* True if a '-' sign preceded <value> */
66645 ){
66646   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
66647   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
66648   const char *zDb = 0;   /* The database name */
66649   Token *pId;            /* Pointer to <id> token */
66650   int iDb;               /* Database index for <database> */
66651   sqlite3 *db = pParse->db;
66652   Db *pDb;
66653   Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
66654   if( v==0 ) return;
66655   pParse->nMem = 2;
66656
66657   /* Interpret the [database.] part of the pragma statement. iDb is the
66658   ** index of the database this pragma is being applied to in db.aDb[]. */
66659   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
66660   if( iDb<0 ) return;
66661   pDb = &db->aDb[iDb];
66662
66663   /* If the temp database has been explicitly named as part of the 
66664   ** pragma, make sure it is open. 
66665   */
66666   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
66667     return;
66668   }
66669
66670   zLeft = sqlite3NameFromToken(db, pId);
66671   if( !zLeft ) return;
66672   if( minusFlag ){
66673     zRight = sqlite3MPrintf(db, "-%T", pValue);
66674   }else{
66675     zRight = sqlite3NameFromToken(db, pValue);
66676   }
66677
66678   zDb = ((pId2 && pId2->n>0)?pDb->zName:0);
66679   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
66680     goto pragma_out;
66681   }
66682  
66683 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
66684   /*
66685   **  PRAGMA [database.]default_cache_size
66686   **  PRAGMA [database.]default_cache_size=N
66687   **
66688   ** The first form reports the current persistent setting for the
66689   ** page cache size.  The value returned is the maximum number of
66690   ** pages in the page cache.  The second form sets both the current
66691   ** page cache size value and the persistent page cache size value
66692   ** stored in the database file.
66693   **
66694   ** The default cache size is stored in meta-value 2 of page 1 of the
66695   ** database file.  The cache size is actually the absolute value of
66696   ** this memory location.  The sign of meta-value 2 determines the
66697   ** synchronous setting.  A negative value means synchronous is off
66698   ** and a positive value means synchronous is on.
66699   */
66700   if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
66701     static const VdbeOpList getCacheSize[] = {
66702       { OP_ReadCookie,  0, 1,        2},  /* 0 */
66703       { OP_IfPos,       1, 6,        0},
66704       { OP_Integer,     0, 2,        0},
66705       { OP_Subtract,    1, 2,        1},
66706       { OP_IfPos,       1, 6,        0},
66707       { OP_Integer,     0, 1,        0},  /* 5 */
66708       { OP_ResultRow,   1, 1,        0},
66709     };
66710     int addr;
66711     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
66712     sqlite3VdbeUsesBtree(v, iDb);
66713     if( !zRight ){
66714       sqlite3VdbeSetNumCols(v, 1);
66715       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", P4_STATIC);
66716       pParse->nMem += 2;
66717       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
66718       sqlite3VdbeChangeP1(v, addr, iDb);
66719       sqlite3VdbeChangeP1(v, addr+5, SQLITE_DEFAULT_CACHE_SIZE);
66720     }else{
66721       int size = atoi(zRight);
66722       if( size<0 ) size = -size;
66723       sqlite3BeginWriteOperation(pParse, 0, iDb);
66724       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
66725       sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, 2, 2);
66726       addr = sqlite3VdbeAddOp2(v, OP_IfPos, 2, 0);
66727       sqlite3VdbeAddOp2(v, OP_Integer, -size, 1);
66728       sqlite3VdbeJumpHere(v, addr);
66729       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 2, 1);
66730       pDb->pSchema->cache_size = size;
66731       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
66732     }
66733   }else
66734
66735   /*
66736   **  PRAGMA [database.]page_size
66737   **  PRAGMA [database.]page_size=N
66738   **
66739   ** The first form reports the current setting for the
66740   ** database page size in bytes.  The second form sets the
66741   ** database page size value.  The value can only be set if
66742   ** the database has not yet been created.
66743   */
66744   if( sqlite3StrICmp(zLeft,"page_size")==0 ){
66745     Btree *pBt = pDb->pBt;
66746     if( !zRight ){
66747       int size = pBt ? sqlite3BtreeGetPageSize(pBt) : 0;
66748       returnSingleInt(pParse, "page_size", size);
66749     }else{
66750       /* Malloc may fail when setting the page-size, as there is an internal
66751       ** buffer that the pager module resizes using sqlite3_realloc().
66752       */
66753       db->nextPagesize = atoi(zRight);
66754       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1) ){
66755         db->mallocFailed = 1;
66756       }
66757     }
66758   }else
66759
66760   /*
66761   **  PRAGMA [database.]max_page_count
66762   **  PRAGMA [database.]max_page_count=N
66763   **
66764   ** The first form reports the current setting for the
66765   ** maximum number of pages in the database file.  The 
66766   ** second form attempts to change this setting.  Both
66767   ** forms return the current setting.
66768   */
66769   if( sqlite3StrICmp(zLeft,"max_page_count")==0 ){
66770     Btree *pBt = pDb->pBt;
66771     int newMax = 0;
66772     if( zRight ){
66773       newMax = atoi(zRight);
66774     }
66775     if( pBt ){
66776       newMax = sqlite3BtreeMaxPageCount(pBt, newMax);
66777     }
66778     returnSingleInt(pParse, "max_page_count", newMax);
66779   }else
66780
66781   /*
66782   **  PRAGMA [database.]page_count
66783   **
66784   ** Return the number of pages in the specified database.
66785   */
66786   if( sqlite3StrICmp(zLeft,"page_count")==0 ){
66787     Vdbe *v;
66788     int iReg;
66789     v = sqlite3GetVdbe(pParse);
66790     if( !v || sqlite3ReadSchema(pParse) ) goto pragma_out;
66791     sqlite3CodeVerifySchema(pParse, iDb);
66792     iReg = ++pParse->nMem;
66793     sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
66794     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
66795     sqlite3VdbeSetNumCols(v, 1);
66796     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "page_count", P4_STATIC);
66797   }else
66798
66799   /*
66800   **  PRAGMA [database.]locking_mode
66801   **  PRAGMA [database.]locking_mode = (normal|exclusive)
66802   */
66803   if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
66804     const char *zRet = "normal";
66805     int eMode = getLockingMode(zRight);
66806
66807     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
66808       /* Simple "PRAGMA locking_mode;" statement. This is a query for
66809       ** the current default locking mode (which may be different to
66810       ** the locking-mode of the main database).
66811       */
66812       eMode = db->dfltLockMode;
66813     }else{
66814       Pager *pPager;
66815       if( pId2->n==0 ){
66816         /* This indicates that no database name was specified as part
66817         ** of the PRAGMA command. In this case the locking-mode must be
66818         ** set on all attached databases, as well as the main db file.
66819         **
66820         ** Also, the sqlite3.dfltLockMode variable is set so that
66821         ** any subsequently attached databases also use the specified
66822         ** locking mode.
66823         */
66824         int ii;
66825         assert(pDb==&db->aDb[0]);
66826         for(ii=2; ii<db->nDb; ii++){
66827           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
66828           sqlite3PagerLockingMode(pPager, eMode);
66829         }
66830         db->dfltLockMode = eMode;
66831       }
66832       pPager = sqlite3BtreePager(pDb->pBt);
66833       eMode = sqlite3PagerLockingMode(pPager, eMode);
66834     }
66835
66836     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
66837     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
66838       zRet = "exclusive";
66839     }
66840     sqlite3VdbeSetNumCols(v, 1);
66841     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", P4_STATIC);
66842     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
66843     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
66844   }else
66845
66846   /*
66847   **  PRAGMA [database.]journal_mode
66848   **  PRAGMA [database.]journal_mode = (delete|persist|off)
66849   */
66850   if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
66851     int eMode;
66852     static char * const azModeName[] = {"delete", "persist", "off"};
66853
66854     if( zRight==0 ){
66855       eMode = PAGER_JOURNALMODE_QUERY;
66856     }else{
66857       int n = strlen(zRight);
66858       eMode = 2;
66859       while( eMode>=0 && sqlite3StrNICmp(zRight, azModeName[eMode], n)!=0 ){
66860         eMode--;
66861       }
66862     }
66863     if( pId2->n==0 && eMode==PAGER_JOURNALMODE_QUERY ){
66864       /* Simple "PRAGMA journal_mode;" statement. This is a query for
66865       ** the current default journal mode (which may be different to
66866       ** the journal-mode of the main database).
66867       */
66868       eMode = db->dfltJournalMode;
66869     }else{
66870       Pager *pPager;
66871       if( pId2->n==0 ){
66872         /* This indicates that no database name was specified as part
66873         ** of the PRAGMA command. In this case the journal-mode must be
66874         ** set on all attached databases, as well as the main db file.
66875         **
66876         ** Also, the sqlite3.dfltJournalMode variable is set so that
66877         ** any subsequently attached databases also use the specified
66878         ** journal mode.
66879         */
66880         int ii;
66881         assert(pDb==&db->aDb[0]);
66882         for(ii=1; ii<db->nDb; ii++){
66883           if( db->aDb[ii].pBt ){
66884             pPager = sqlite3BtreePager(db->aDb[ii].pBt);
66885             sqlite3PagerJournalMode(pPager, eMode);
66886           }
66887         }
66888         db->dfltJournalMode = eMode;
66889       }
66890       pPager = sqlite3BtreePager(pDb->pBt);
66891       eMode = sqlite3PagerJournalMode(pPager, eMode);
66892     }
66893     assert( eMode==PAGER_JOURNALMODE_DELETE
66894               || eMode==PAGER_JOURNALMODE_PERSIST
66895               || eMode==PAGER_JOURNALMODE_OFF );
66896     sqlite3VdbeSetNumCols(v, 1);
66897     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", P4_STATIC);
66898     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, 
66899            azModeName[eMode], P4_STATIC);
66900     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
66901   }else
66902
66903   /*
66904   **  PRAGMA [database.]journal_size_limit
66905   **  PRAGMA [database.]journal_size_limit=N
66906   **
66907   ** Get or set the (boolean) value of the database 'auto-vacuum' parameter.
66908   */
66909   if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
66910     Pager *pPager = sqlite3BtreePager(pDb->pBt);
66911     i64 iLimit = -2;
66912     if( zRight ){
66913       int iLimit32 = atoi(zRight);
66914       if( iLimit32<-1 ){
66915         iLimit32 = -1;
66916       }
66917       iLimit = iLimit32;
66918     }
66919     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
66920     returnSingleInt(pParse, "journal_size_limit", (int)iLimit);
66921   }else
66922
66923 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
66924
66925   /*
66926   **  PRAGMA [database.]auto_vacuum
66927   **  PRAGMA [database.]auto_vacuum=N
66928   **
66929   ** Get or set the (boolean) value of the database 'auto-vacuum' parameter.
66930   */
66931 #ifndef SQLITE_OMIT_AUTOVACUUM
66932   if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
66933     Btree *pBt = pDb->pBt;
66934     if( sqlite3ReadSchema(pParse) ){
66935       goto pragma_out;
66936     }
66937     if( !zRight ){
66938       int auto_vacuum = 
66939           pBt ? sqlite3BtreeGetAutoVacuum(pBt) : SQLITE_DEFAULT_AUTOVACUUM;
66940       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
66941     }else{
66942       int eAuto = getAutoVacuum(zRight);
66943       db->nextAutovac = eAuto;
66944       if( eAuto>=0 ){
66945         /* Call SetAutoVacuum() to set initialize the internal auto and
66946         ** incr-vacuum flags. This is required in case this connection
66947         ** creates the database file. It is important that it is created
66948         ** as an auto-vacuum capable db.
66949         */
66950         int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
66951         if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
66952           /* When setting the auto_vacuum mode to either "full" or 
66953           ** "incremental", write the value of meta[6] in the database
66954           ** file. Before writing to meta[6], check that meta[3] indicates
66955           ** that this really is an auto-vacuum capable database.
66956           */
66957           static const VdbeOpList setMeta6[] = {
66958             { OP_Transaction,    0,               1,        0},    /* 0 */
66959             { OP_ReadCookie,     0,               1,        3},    /* 1 */
66960             { OP_If,             1,               0,        0},    /* 2 */
66961             { OP_Halt,           SQLITE_OK,       OE_Abort, 0},    /* 3 */
66962             { OP_Integer,        0,               1,        0},    /* 4 */
66963             { OP_SetCookie,      0,               6,        1},    /* 5 */
66964           };
66965           int iAddr;
66966           iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
66967           sqlite3VdbeChangeP1(v, iAddr, iDb);
66968           sqlite3VdbeChangeP1(v, iAddr+1, iDb);
66969           sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
66970           sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
66971           sqlite3VdbeChangeP1(v, iAddr+5, iDb);
66972           sqlite3VdbeUsesBtree(v, iDb);
66973         }
66974       }
66975     }
66976   }else
66977 #endif
66978
66979   /*
66980   **  PRAGMA [database.]incremental_vacuum(N)
66981   **
66982   ** Do N steps of incremental vacuuming on a database.
66983   */
66984 #ifndef SQLITE_OMIT_AUTOVACUUM
66985   if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
66986     int iLimit, addr;
66987     if( sqlite3ReadSchema(pParse) ){
66988       goto pragma_out;
66989     }
66990     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
66991       iLimit = 0x7fffffff;
66992     }
66993     sqlite3BeginWriteOperation(pParse, 0, iDb);
66994     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
66995     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
66996     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
66997     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
66998     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
66999     sqlite3VdbeJumpHere(v, addr);
67000   }else
67001 #endif
67002
67003 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
67004   /*
67005   **  PRAGMA [database.]cache_size
67006   **  PRAGMA [database.]cache_size=N
67007   **
67008   ** The first form reports the current local setting for the
67009   ** page cache size.  The local setting can be different from
67010   ** the persistent cache size value that is stored in the database
67011   ** file itself.  The value returned is the maximum number of
67012   ** pages in the page cache.  The second form sets the local
67013   ** page cache size value.  It does not change the persistent
67014   ** cache size stored on the disk so the cache size will revert
67015   ** to its default value when the database is closed and reopened.
67016   ** N should be a positive integer.
67017   */
67018   if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
67019     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
67020     if( !zRight ){
67021       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
67022     }else{
67023       int size = atoi(zRight);
67024       if( size<0 ) size = -size;
67025       pDb->pSchema->cache_size = size;
67026       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
67027     }
67028   }else
67029
67030   /*
67031   **   PRAGMA temp_store
67032   **   PRAGMA temp_store = "default"|"memory"|"file"
67033   **
67034   ** Return or set the local value of the temp_store flag.  Changing
67035   ** the local value does not make changes to the disk file and the default
67036   ** value will be restored the next time the database is opened.
67037   **
67038   ** Note that it is possible for the library compile-time options to
67039   ** override this setting
67040   */
67041   if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
67042     if( !zRight ){
67043       returnSingleInt(pParse, "temp_store", db->temp_store);
67044     }else{
67045       changeTempStorage(pParse, zRight);
67046     }
67047   }else
67048
67049   /*
67050   **   PRAGMA temp_store_directory
67051   **   PRAGMA temp_store_directory = ""|"directory_name"
67052   **
67053   ** Return or set the local value of the temp_store_directory flag.  Changing
67054   ** the value sets a specific directory to be used for temporary files.
67055   ** Setting to a null string reverts to the default temporary directory search.
67056   ** If temporary directory is changed, then invalidateTempStorage.
67057   **
67058   */
67059   if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
67060     if( !zRight ){
67061       if( sqlite3_temp_directory ){
67062         sqlite3VdbeSetNumCols(v, 1);
67063         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
67064             "temp_store_directory", P4_STATIC);
67065         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
67066         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
67067       }
67068     }else{
67069 #ifndef SQLITE_OMIT_WSD
67070       if( zRight[0] ){
67071         int rc;
67072         int res;
67073         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
67074         if( rc!=SQLITE_OK || res==0 ){
67075           sqlite3ErrorMsg(pParse, "not a writable directory");
67076           goto pragma_out;
67077         }
67078       }
67079       if( SQLITE_TEMP_STORE==0
67080        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
67081        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
67082       ){
67083         invalidateTempStorage(pParse);
67084       }
67085       sqlite3_free(sqlite3_temp_directory);
67086       if( zRight[0] ){
67087         sqlite3_temp_directory = sqlite3DbStrDup(0, zRight);
67088       }else{
67089         sqlite3_temp_directory = 0;
67090       }
67091 #endif /* SQLITE_OMIT_WSD */
67092     }
67093   }else
67094
67095   /*
67096   **   PRAGMA [database.]synchronous
67097   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
67098   **
67099   ** Return or set the local value of the synchronous flag.  Changing
67100   ** the local value does not make changes to the disk file and the
67101   ** default value will be restored the next time the database is
67102   ** opened.
67103   */
67104   if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
67105     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
67106     if( !zRight ){
67107       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
67108     }else{
67109       if( !db->autoCommit ){
67110         sqlite3ErrorMsg(pParse, 
67111             "Safety level may not be changed inside a transaction");
67112       }else{
67113         pDb->safety_level = getSafetyLevel(zRight)+1;
67114       }
67115     }
67116   }else
67117 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
67118
67119 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
67120   if( flagPragma(pParse, zLeft, zRight) ){
67121     /* The flagPragma() subroutine also generates any necessary code
67122     ** there is nothing more to do here */
67123   }else
67124 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
67125
67126 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
67127   /*
67128   **   PRAGMA table_info(<table>)
67129   **
67130   ** Return a single row for each column of the named table. The columns of
67131   ** the returned data set are:
67132   **
67133   ** cid:        Column id (numbered from left to right, starting at 0)
67134   ** name:       Column name
67135   ** type:       Column declaration type.
67136   ** notnull:    True if 'NOT NULL' is part of column declaration
67137   ** dflt_value: The default value for the column, if any.
67138   */
67139   if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
67140     Table *pTab;
67141     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
67142     pTab = sqlite3FindTable(db, zRight, zDb);
67143     if( pTab ){
67144       int i;
67145       int nHidden = 0;
67146       Column *pCol;
67147       sqlite3VdbeSetNumCols(v, 6);
67148       pParse->nMem = 6;
67149       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", P4_STATIC);
67150       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P4_STATIC);
67151       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", P4_STATIC);
67152       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", P4_STATIC);
67153       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", P4_STATIC);
67154       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", P4_STATIC);
67155       sqlite3ViewGetColumnNames(pParse, pTab);
67156       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
67157         const Token *pDflt;
67158         if( IsHiddenColumn(pCol) ){
67159           nHidden++;
67160           continue;
67161         }
67162         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
67163         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
67164         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
67165            pCol->zType ? pCol->zType : "", 0);
67166         sqlite3VdbeAddOp2(v, OP_Integer, pCol->notNull, 4);
67167         if( pCol->pDflt && (pDflt = &pCol->pDflt->span)->z ){
67168           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pDflt->z, pDflt->n);
67169         }else{
67170           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
67171         }
67172         sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
67173         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
67174       }
67175     }
67176   }else
67177
67178   if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
67179     Index *pIdx;
67180     Table *pTab;
67181     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
67182     pIdx = sqlite3FindIndex(db, zRight, zDb);
67183     if( pIdx ){
67184       int i;
67185       pTab = pIdx->pTable;
67186       sqlite3VdbeSetNumCols(v, 3);
67187       pParse->nMem = 3;
67188       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", P4_STATIC);
67189       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", P4_STATIC);
67190       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", P4_STATIC);
67191       for(i=0; i<pIdx->nColumn; i++){
67192         int cnum = pIdx->aiColumn[i];
67193         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
67194         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
67195         assert( pTab->nCol>cnum );
67196         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
67197         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
67198       }
67199     }
67200   }else
67201
67202   if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
67203     Index *pIdx;
67204     Table *pTab;
67205     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
67206     pTab = sqlite3FindTable(db, zRight, zDb);
67207     if( pTab ){
67208       v = sqlite3GetVdbe(pParse);
67209       pIdx = pTab->pIndex;
67210       if( pIdx ){
67211         int i = 0; 
67212         sqlite3VdbeSetNumCols(v, 3);
67213         pParse->nMem = 3;
67214         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P4_STATIC);
67215         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P4_STATIC);
67216         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", P4_STATIC);
67217         while(pIdx){
67218           sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
67219           sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
67220           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
67221           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
67222           ++i;
67223           pIdx = pIdx->pNext;
67224         }
67225       }
67226     }
67227   }else
67228
67229   if( sqlite3StrICmp(zLeft, "database_list")==0 ){
67230     int i;
67231     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
67232     sqlite3VdbeSetNumCols(v, 3);
67233     pParse->nMem = 3;
67234     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P4_STATIC);
67235     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P4_STATIC);
67236     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", P4_STATIC);
67237     for(i=0; i<db->nDb; i++){
67238       if( db->aDb[i].pBt==0 ) continue;
67239       assert( db->aDb[i].zName!=0 );
67240       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
67241       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
67242       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
67243            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
67244       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
67245     }
67246   }else
67247
67248   if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
67249     int i = 0;
67250     HashElem *p;
67251     sqlite3VdbeSetNumCols(v, 2);
67252     pParse->nMem = 2;
67253     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P4_STATIC);
67254     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P4_STATIC);
67255     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
67256       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
67257       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
67258       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
67259       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
67260     }
67261   }else
67262 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
67263
67264 #ifndef SQLITE_OMIT_FOREIGN_KEY
67265   if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
67266     FKey *pFK;
67267     Table *pTab;
67268     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
67269     pTab = sqlite3FindTable(db, zRight, zDb);
67270     if( pTab ){
67271       v = sqlite3GetVdbe(pParse);
67272       pFK = pTab->pFKey;
67273       if( pFK ){
67274         int i = 0; 
67275         sqlite3VdbeSetNumCols(v, 5);
67276         pParse->nMem = 5;
67277         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", P4_STATIC);
67278         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", P4_STATIC);
67279         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", P4_STATIC);
67280         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", P4_STATIC);
67281         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", P4_STATIC);
67282         while(pFK){
67283           int j;
67284           for(j=0; j<pFK->nCol; j++){
67285             char *zCol = pFK->aCol[j].zCol;
67286             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
67287             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
67288             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
67289             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
67290                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
67291             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
67292             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
67293           }
67294           ++i;
67295           pFK = pFK->pNextFrom;
67296         }
67297       }
67298     }
67299   }else
67300 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
67301
67302 #ifndef NDEBUG
67303   if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
67304     if( zRight ){
67305       if( getBoolean(zRight) ){
67306         sqlite3ParserTrace(stderr, "parser: ");
67307       }else{
67308         sqlite3ParserTrace(0, 0);
67309       }
67310     }
67311   }else
67312 #endif
67313
67314   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
67315   ** used will be case sensitive or not depending on the RHS.
67316   */
67317   if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
67318     if( zRight ){
67319       sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
67320     }
67321   }else
67322
67323 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
67324 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
67325 #endif
67326
67327 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
67328   /* Pragma "quick_check" is an experimental reduced version of 
67329   ** integrity_check designed to detect most database corruption
67330   ** without most of the overhead of a full integrity-check.
67331   */
67332   if( sqlite3StrICmp(zLeft, "integrity_check")==0
67333    || sqlite3StrICmp(zLeft, "quick_check")==0 
67334   ){
67335     int i, j, addr, mxErr;
67336
67337     /* Code that appears at the end of the integrity check.  If no error
67338     ** messages have been generated, output OK.  Otherwise output the
67339     ** error message
67340     */
67341     static const VdbeOpList endCode[] = {
67342       { OP_AddImm,      1, 0,        0},    /* 0 */
67343       { OP_IfNeg,       1, 0,        0},    /* 1 */
67344       { OP_String8,     0, 3,        0},    /* 2 */
67345       { OP_ResultRow,   3, 1,        0},
67346     };
67347
67348     int isQuick = (zLeft[0]=='q');
67349
67350     /* Initialize the VDBE program */
67351     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
67352     pParse->nMem = 6;
67353     sqlite3VdbeSetNumCols(v, 1);
67354     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", P4_STATIC);
67355
67356     /* Set the maximum error count */
67357     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
67358     if( zRight ){
67359       mxErr = atoi(zRight);
67360       if( mxErr<=0 ){
67361         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
67362       }
67363     }
67364     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
67365
67366     /* Do an integrity check on each database file */
67367     for(i=0; i<db->nDb; i++){
67368       HashElem *x;
67369       Hash *pTbls;
67370       int cnt = 0;
67371
67372       if( OMIT_TEMPDB && i==1 ) continue;
67373
67374       sqlite3CodeVerifySchema(pParse, i);
67375       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
67376       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
67377       sqlite3VdbeJumpHere(v, addr);
67378
67379       /* Do an integrity check of the B-Tree
67380       **
67381       ** Begin by filling registers 2, 3, ... with the root pages numbers
67382       ** for all tables and indices in the database.
67383       */
67384       pTbls = &db->aDb[i].pSchema->tblHash;
67385       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
67386         Table *pTab = sqliteHashData(x);
67387         Index *pIdx;
67388         sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
67389         cnt++;
67390         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
67391           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
67392           cnt++;
67393         }
67394       }
67395       if( cnt==0 ) continue;
67396
67397       /* Make sure sufficient number of registers have been allocated */
67398       if( pParse->nMem < cnt+4 ){
67399         pParse->nMem = cnt+4;
67400       }
67401
67402       /* Do the b-tree integrity checks */
67403       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
67404       sqlite3VdbeChangeP5(v, i);
67405       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
67406       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
67407          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
67408          P4_DYNAMIC);
67409       sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
67410       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
67411       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
67412       sqlite3VdbeJumpHere(v, addr);
67413
67414       /* Make sure all the indices are constructed correctly.
67415       */
67416       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
67417         Table *pTab = sqliteHashData(x);
67418         Index *pIdx;
67419         int loopTop;
67420
67421         if( pTab->pIndex==0 ) continue;
67422         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
67423         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
67424         sqlite3VdbeJumpHere(v, addr);
67425         sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
67426         sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
67427         loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
67428         sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
67429         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
67430           int jmp2;
67431           static const VdbeOpList idxErr[] = {
67432             { OP_AddImm,      1, -1,  0},
67433             { OP_String8,     0,  3,  0},    /* 1 */
67434             { OP_Rowid,       1,  4,  0},
67435             { OP_String8,     0,  5,  0},    /* 3 */
67436             { OP_String8,     0,  6,  0},    /* 4 */
67437             { OP_Concat,      4,  3,  3},
67438             { OP_Concat,      5,  3,  3},
67439             { OP_Concat,      6,  3,  3},
67440             { OP_ResultRow,   3,  1,  0},
67441             { OP_IfPos,       1,  0,  0},    /* 9 */
67442             { OP_Halt,        0,  0,  0},
67443           };
67444           sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 1);
67445           jmp2 = sqlite3VdbeAddOp3(v, OP_Found, j+2, 0, 3);
67446           addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
67447           sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
67448           sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
67449           sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_STATIC);
67450           sqlite3VdbeJumpHere(v, addr+9);
67451           sqlite3VdbeJumpHere(v, jmp2);
67452         }
67453         sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
67454         sqlite3VdbeJumpHere(v, loopTop);
67455         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
67456           static const VdbeOpList cntIdx[] = {
67457              { OP_Integer,      0,  3,  0},
67458              { OP_Rewind,       0,  0,  0},  /* 1 */
67459              { OP_AddImm,       3,  1,  0},
67460              { OP_Next,         0,  0,  0},  /* 3 */
67461              { OP_Eq,           2,  0,  3},  /* 4 */
67462              { OP_AddImm,       1, -1,  0},
67463              { OP_String8,      0,  2,  0},  /* 6 */
67464              { OP_String8,      0,  3,  0},  /* 7 */
67465              { OP_Concat,       3,  2,  2},
67466              { OP_ResultRow,    2,  1,  0},
67467           };
67468           if( pIdx->tnum==0 ) continue;
67469           addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
67470           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
67471           sqlite3VdbeJumpHere(v, addr);
67472           addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
67473           sqlite3VdbeChangeP1(v, addr+1, j+2);
67474           sqlite3VdbeChangeP2(v, addr+1, addr+4);
67475           sqlite3VdbeChangeP1(v, addr+3, j+2);
67476           sqlite3VdbeChangeP2(v, addr+3, addr+2);
67477           sqlite3VdbeJumpHere(v, addr+4);
67478           sqlite3VdbeChangeP4(v, addr+6, 
67479                      "wrong # of entries in index ", P4_STATIC);
67480           sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_STATIC);
67481         }
67482       } 
67483     }
67484     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
67485     sqlite3VdbeChangeP2(v, addr, -mxErr);
67486     sqlite3VdbeJumpHere(v, addr+1);
67487     sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
67488   }else
67489 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
67490
67491 #ifndef SQLITE_OMIT_UTF16
67492   /*
67493   **   PRAGMA encoding
67494   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
67495   **
67496   ** In its first form, this pragma returns the encoding of the main
67497   ** database. If the database is not initialized, it is initialized now.
67498   **
67499   ** The second form of this pragma is a no-op if the main database file
67500   ** has not already been initialized. In this case it sets the default
67501   ** encoding that will be used for the main database file if a new file
67502   ** is created. If an existing main database file is opened, then the
67503   ** default text encoding for the existing database is used.
67504   ** 
67505   ** In all cases new databases created using the ATTACH command are
67506   ** created to use the same default text encoding as the main database. If
67507   ** the main database has not been initialized and/or created when ATTACH
67508   ** is executed, this is done before the ATTACH operation.
67509   **
67510   ** In the second form this pragma sets the text encoding to be used in
67511   ** new database files created using this database handle. It is only
67512   ** useful if invoked immediately after the main database i
67513   */
67514   if( sqlite3StrICmp(zLeft, "encoding")==0 ){
67515     static const struct EncName {
67516       char *zName;
67517       u8 enc;
67518     } encnames[] = {
67519       { "UTF-8",    SQLITE_UTF8        },
67520       { "UTF8",     SQLITE_UTF8        },
67521       { "UTF-16le", SQLITE_UTF16LE     },
67522       { "UTF16le",  SQLITE_UTF16LE     },
67523       { "UTF-16be", SQLITE_UTF16BE     },
67524       { "UTF16be",  SQLITE_UTF16BE     },
67525       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
67526       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
67527       { 0, 0 }
67528     };
67529     const struct EncName *pEnc;
67530     if( !zRight ){    /* "PRAGMA encoding" */
67531       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
67532       sqlite3VdbeSetNumCols(v, 1);
67533       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", P4_STATIC);
67534       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
67535       for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
67536         if( pEnc->enc==ENC(pParse->db) ){
67537           sqlite3VdbeChangeP4(v, -1, pEnc->zName, P4_STATIC);
67538           break;
67539         }
67540       }
67541       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
67542     }else{                        /* "PRAGMA encoding = XXX" */
67543       /* Only change the value of sqlite.enc if the database handle is not
67544       ** initialized. If the main database exists, the new sqlite.enc value
67545       ** will be overwritten when the schema is next loaded. If it does not
67546       ** already exists, it will be created to use the new encoding value.
67547       */
67548       if( 
67549         !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
67550         DbHasProperty(db, 0, DB_Empty) 
67551       ){
67552         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
67553           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
67554             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
67555             break;
67556           }
67557         }
67558         if( !pEnc->zName ){
67559           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
67560         }
67561       }
67562     }
67563   }else
67564 #endif /* SQLITE_OMIT_UTF16 */
67565
67566 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
67567   /*
67568   **   PRAGMA [database.]schema_version
67569   **   PRAGMA [database.]schema_version = <integer>
67570   **
67571   **   PRAGMA [database.]user_version
67572   **   PRAGMA [database.]user_version = <integer>
67573   **
67574   ** The pragma's schema_version and user_version are used to set or get
67575   ** the value of the schema-version and user-version, respectively. Both
67576   ** the schema-version and the user-version are 32-bit signed integers
67577   ** stored in the database header.
67578   **
67579   ** The schema-cookie is usually only manipulated internally by SQLite. It
67580   ** is incremented by SQLite whenever the database schema is modified (by
67581   ** creating or dropping a table or index). The schema version is used by
67582   ** SQLite each time a query is executed to ensure that the internal cache
67583   ** of the schema used when compiling the SQL query matches the schema of
67584   ** the database against which the compiled query is actually executed.
67585   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
67586   ** the schema-version is potentially dangerous and may lead to program
67587   ** crashes or database corruption. Use with caution!
67588   **
67589   ** The user-version is not used internally by SQLite. It may be used by
67590   ** applications for any purpose.
67591   */
67592   if( sqlite3StrICmp(zLeft, "schema_version")==0 
67593    || sqlite3StrICmp(zLeft, "user_version")==0 
67594    || sqlite3StrICmp(zLeft, "freelist_count")==0 
67595   ){
67596     int iCookie;   /* Cookie index. 0 for schema-cookie, 6 for user-cookie. */
67597     sqlite3VdbeUsesBtree(v, iDb);
67598     switch( zLeft[0] ){
67599       case 's': case 'S':
67600         iCookie = 0;
67601         break;
67602       case 'f': case 'F':
67603         iCookie = 1;
67604         iDb = (-1*(iDb+1));
67605         assert(iDb<=0);
67606         break;
67607       default:
67608         iCookie = 5;
67609         break;
67610     }
67611
67612     if( zRight && iDb>=0 ){
67613       /* Write the specified cookie value */
67614       static const VdbeOpList setCookie[] = {
67615         { OP_Transaction,    0,  1,  0},    /* 0 */
67616         { OP_Integer,        0,  1,  0},    /* 1 */
67617         { OP_SetCookie,      0,  0,  1},    /* 2 */
67618       };
67619       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
67620       sqlite3VdbeChangeP1(v, addr, iDb);
67621       sqlite3VdbeChangeP1(v, addr+1, atoi(zRight));
67622       sqlite3VdbeChangeP1(v, addr+2, iDb);
67623       sqlite3VdbeChangeP2(v, addr+2, iCookie);
67624     }else{
67625       /* Read the specified cookie value */
67626       static const VdbeOpList readCookie[] = {
67627         { OP_ReadCookie,      0,  1,  0},    /* 0 */
67628         { OP_ResultRow,       1,  1,  0}
67629       };
67630       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
67631       sqlite3VdbeChangeP1(v, addr, iDb);
67632       sqlite3VdbeChangeP3(v, addr, iCookie);
67633       sqlite3VdbeSetNumCols(v, 1);
67634       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, P4_TRANSIENT);
67635     }
67636   }else
67637 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
67638
67639 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
67640   /*
67641   ** Report the current state of file logs for all databases
67642   */
67643   if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
67644     static const char *const azLockName[] = {
67645       "unlocked", "shared", "reserved", "pending", "exclusive"
67646     };
67647     int i;
67648     Vdbe *v = sqlite3GetVdbe(pParse);
67649     sqlite3VdbeSetNumCols(v, 2);
67650     pParse->nMem = 2;
67651     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", P4_STATIC);
67652     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", P4_STATIC);
67653     for(i=0; i<db->nDb; i++){
67654       Btree *pBt;
67655       Pager *pPager;
67656       const char *zState = "unknown";
67657       int j;
67658       if( db->aDb[i].zName==0 ) continue;
67659       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
67660       pBt = db->aDb[i].pBt;
67661       if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
67662         zState = "closed";
67663       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, 
67664                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
67665          zState = azLockName[j];
67666       }
67667       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
67668       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
67669     }
67670
67671   }else
67672 #endif
67673
67674 #ifdef SQLITE_SSE
67675   /*
67676   ** Check to see if the sqlite_statements table exists.  Create it
67677   ** if it does not.
67678   */
67679   if( sqlite3StrICmp(zLeft, "create_sqlite_statement_table")==0 ){
67680     extern int sqlite3CreateStatementsTable(Parse*);
67681     sqlite3CreateStatementsTable(pParse);
67682   }else
67683 #endif
67684
67685 #if SQLITE_HAS_CODEC
67686   if( sqlite3StrICmp(zLeft, "key")==0 ){
67687     sqlite3_key(db, zRight, strlen(zRight));
67688   }else
67689 #endif
67690 #if SQLITE_HAS_CODEC || defined(SQLITE_ENABLE_CEROD)
67691   if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
67692 #if SQLITE_HAS_CODEC
67693     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
67694       extern void sqlite3_activate_see(const char*);
67695       sqlite3_activate_see(&zRight[4]);
67696     }
67697 #endif
67698 #ifdef SQLITE_ENABLE_CEROD
67699     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
67700       extern void sqlite3_activate_cerod(const char*);
67701       sqlite3_activate_cerod(&zRight[6]);
67702     }
67703 #endif
67704   }
67705 #endif
67706
67707   {}
67708
67709   if( v ){
67710     /* Code an OP_Expire at the end of each PRAGMA program to cause
67711     ** the VDBE implementing the pragma to expire. Most (all?) pragmas
67712     ** are only valid for a single execution.
67713     */
67714     sqlite3VdbeAddOp2(v, OP_Expire, 1, 0);
67715
67716     /*
67717     ** Reset the safety level, in case the fullfsync flag or synchronous
67718     ** setting changed.
67719     */
67720 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
67721     if( db->autoCommit ){
67722       sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
67723                  (db->flags&SQLITE_FullFSync)!=0);
67724     }
67725 #endif
67726   }
67727 pragma_out:
67728   sqlite3DbFree(db, zLeft);
67729   sqlite3DbFree(db, zRight);
67730 }
67731
67732 #endif /* SQLITE_OMIT_PRAGMA || SQLITE_OMIT_PARSER */
67733
67734 /************** End of pragma.c **********************************************/
67735 /************** Begin file prepare.c *****************************************/
67736 /*
67737 ** 2005 May 25
67738 **
67739 ** The author disclaims copyright to this source code.  In place of
67740 ** a legal notice, here is a blessing:
67741 **
67742 **    May you do good and not evil.
67743 **    May you find forgiveness for yourself and forgive others.
67744 **    May you share freely, never taking more than you give.
67745 **
67746 *************************************************************************
67747 ** This file contains the implementation of the sqlite3_prepare()
67748 ** interface, and routines that contribute to loading the database schema
67749 ** from disk.
67750 **
67751 ** $Id: prepare.c,v 1.97 2008/09/08 09:06:19 danielk1977 Exp $
67752 */
67753
67754 /*
67755 ** Fill the InitData structure with an error message that indicates
67756 ** that the database is corrupt.
67757 */
67758 static void corruptSchema(
67759   InitData *pData,     /* Initialization context */
67760   const char *zObj,    /* Object being parsed at the point of error */
67761   const char *zExtra   /* Error information */
67762 ){
67763   sqlite3 *db = pData->db;
67764   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
67765     if( zObj==0 ) zObj = "?";
67766     sqlite3SetString(pData->pzErrMsg, pData->db,
67767        "malformed database schema (%s)", zObj);
67768     if( zExtra && zExtra[0] ){
67769       *pData->pzErrMsg = sqlite3MAppendf(pData->db, *pData->pzErrMsg, "%s - %s",
67770                                   *pData->pzErrMsg, zExtra);
67771     }
67772   }
67773   pData->rc = SQLITE_CORRUPT;
67774 }
67775
67776 /*
67777 ** This is the callback routine for the code that initializes the
67778 ** database.  See sqlite3Init() below for additional information.
67779 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
67780 **
67781 ** Each callback contains the following information:
67782 **
67783 **     argv[0] = name of thing being created
67784 **     argv[1] = root page number for table or index. 0 for trigger or view.
67785 **     argv[2] = SQL text for the CREATE statement.
67786 **
67787 */
67788 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **azColName){
67789   InitData *pData = (InitData*)pInit;
67790   sqlite3 *db = pData->db;
67791   int iDb = pData->iDb;
67792
67793   assert( sqlite3_mutex_held(db->mutex) );
67794   DbClearProperty(db, iDb, DB_Empty);
67795   if( db->mallocFailed ){
67796     corruptSchema(pData, argv[0], 0);
67797     return SQLITE_NOMEM;
67798   }
67799
67800   assert( argc==3 );
67801   assert( iDb>=0 && iDb<db->nDb );
67802   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
67803   if( argv[1]==0 ){
67804     corruptSchema(pData, argv[0], 0);
67805   }else if( argv[2] && argv[2][0] ){
67806     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
67807     ** But because db->init.busy is set to 1, no VDBE code is generated
67808     ** or executed.  All the parser does is build the internal data
67809     ** structures that describe the table, index, or view.
67810     */
67811     char *zErr;
67812     int rc;
67813     u8 lookasideEnabled;
67814     assert( db->init.busy );
67815     db->init.iDb = iDb;
67816     db->init.newTnum = atoi(argv[1]);
67817     lookasideEnabled = db->lookaside.bEnabled;
67818     db->lookaside.bEnabled = 0;
67819     rc = sqlite3_exec(db, argv[2], 0, 0, &zErr);
67820     db->init.iDb = 0;
67821     db->lookaside.bEnabled = lookasideEnabled;
67822     assert( rc!=SQLITE_OK || zErr==0 );
67823     if( SQLITE_OK!=rc ){
67824       pData->rc = rc;
67825       if( rc==SQLITE_NOMEM ){
67826         db->mallocFailed = 1;
67827       }else if( rc!=SQLITE_INTERRUPT ){
67828         corruptSchema(pData, argv[0], zErr);
67829       }
67830       sqlite3DbFree(db, zErr);
67831     }
67832   }else if( argv[0]==0 ){
67833     corruptSchema(pData, 0, 0);
67834   }else{
67835     /* If the SQL column is blank it means this is an index that
67836     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
67837     ** constraint for a CREATE TABLE.  The index should have already
67838     ** been created when we processed the CREATE TABLE.  All we have
67839     ** to do here is record the root page number for that index.
67840     */
67841     Index *pIndex;
67842     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
67843     if( pIndex==0 || pIndex->tnum!=0 ){
67844       /* This can occur if there exists an index on a TEMP table which
67845       ** has the same name as another index on a permanent index.  Since
67846       ** the permanent table is hidden by the TEMP table, we can also
67847       ** safely ignore the index on the permanent table.
67848       */
67849       /* Do Nothing */;
67850     }else{
67851       pIndex->tnum = atoi(argv[1]);
67852     }
67853   }
67854   return 0;
67855 }
67856
67857 /*
67858 ** Attempt to read the database schema and initialize internal
67859 ** data structures for a single database file.  The index of the
67860 ** database file is given by iDb.  iDb==0 is used for the main
67861 ** database.  iDb==1 should never be used.  iDb>=2 is used for
67862 ** auxiliary databases.  Return one of the SQLITE_ error codes to
67863 ** indicate success or failure.
67864 */
67865 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
67866   int rc;
67867   BtCursor *curMain;
67868   int size;
67869   Table *pTab;
67870   Db *pDb;
67871   char const *azArg[4];
67872   int meta[10];
67873   InitData initData;
67874   char const *zMasterSchema;
67875   char const *zMasterName = SCHEMA_TABLE(iDb);
67876
67877   /*
67878   ** The master database table has a structure like this
67879   */
67880   static const char master_schema[] = 
67881      "CREATE TABLE sqlite_master(\n"
67882      "  type text,\n"
67883      "  name text,\n"
67884      "  tbl_name text,\n"
67885      "  rootpage integer,\n"
67886      "  sql text\n"
67887      ")"
67888   ;
67889 #ifndef SQLITE_OMIT_TEMPDB
67890   static const char temp_master_schema[] = 
67891      "CREATE TEMP TABLE sqlite_temp_master(\n"
67892      "  type text,\n"
67893      "  name text,\n"
67894      "  tbl_name text,\n"
67895      "  rootpage integer,\n"
67896      "  sql text\n"
67897      ")"
67898   ;
67899 #else
67900   #define temp_master_schema 0
67901 #endif
67902
67903   assert( iDb>=0 && iDb<db->nDb );
67904   assert( db->aDb[iDb].pSchema );
67905   assert( sqlite3_mutex_held(db->mutex) );
67906   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
67907
67908   /* zMasterSchema and zInitScript are set to point at the master schema
67909   ** and initialisation script appropriate for the database being
67910   ** initialised. zMasterName is the name of the master table.
67911   */
67912   if( !OMIT_TEMPDB && iDb==1 ){
67913     zMasterSchema = temp_master_schema;
67914   }else{
67915     zMasterSchema = master_schema;
67916   }
67917   zMasterName = SCHEMA_TABLE(iDb);
67918
67919   /* Construct the schema tables.  */
67920   azArg[0] = zMasterName;
67921   azArg[1] = "1";
67922   azArg[2] = zMasterSchema;
67923   azArg[3] = 0;
67924   initData.db = db;
67925   initData.iDb = iDb;
67926   initData.rc = SQLITE_OK;
67927   initData.pzErrMsg = pzErrMsg;
67928   (void)sqlite3SafetyOff(db);
67929   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
67930   (void)sqlite3SafetyOn(db);
67931   if( initData.rc ){
67932     rc = initData.rc;
67933     goto error_out;
67934   }
67935   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
67936   if( pTab ){
67937     pTab->tabFlags |= TF_Readonly;
67938   }
67939
67940   /* Create a cursor to hold the database open
67941   */
67942   pDb = &db->aDb[iDb];
67943   if( pDb->pBt==0 ){
67944     if( !OMIT_TEMPDB && iDb==1 ){
67945       DbSetProperty(db, 1, DB_SchemaLoaded);
67946     }
67947     return SQLITE_OK;
67948   }
67949   curMain = sqlite3MallocZero(sqlite3BtreeCursorSize());
67950   if( !curMain ){
67951     rc = SQLITE_NOMEM;
67952     goto error_out;
67953   }
67954   sqlite3BtreeEnter(pDb->pBt);
67955   rc = sqlite3BtreeCursor(pDb->pBt, MASTER_ROOT, 0, 0, curMain);
67956   if( rc!=SQLITE_OK && rc!=SQLITE_EMPTY ){
67957     sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
67958     goto initone_error_out;
67959   }
67960
67961   /* Get the database meta information.
67962   **
67963   ** Meta values are as follows:
67964   **    meta[0]   Schema cookie.  Changes with each schema change.
67965   **    meta[1]   File format of schema layer.
67966   **    meta[2]   Size of the page cache.
67967   **    meta[3]   Use freelist if 0.  Autovacuum if greater than zero.
67968   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
67969   **    meta[5]   The user cookie. Used by the application.
67970   **    meta[6]   Incremental-vacuum flag.
67971   **    meta[7]
67972   **    meta[8]
67973   **    meta[9]
67974   **
67975   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
67976   ** the possible values of meta[4].
67977   */
67978   if( rc==SQLITE_OK ){
67979     int i;
67980     for(i=0; i<sizeof(meta)/sizeof(meta[0]); i++){
67981       rc = sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
67982       if( rc ){
67983         sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
67984         goto initone_error_out;
67985       }
67986     }
67987   }else{
67988     memset(meta, 0, sizeof(meta));
67989   }
67990   pDb->pSchema->schema_cookie = meta[0];
67991
67992   /* If opening a non-empty database, check the text encoding. For the
67993   ** main database, set sqlite3.enc to the encoding of the main database.
67994   ** For an attached db, it is an error if the encoding is not the same
67995   ** as sqlite3.enc.
67996   */
67997   if( meta[4] ){  /* text encoding */
67998     if( iDb==0 ){
67999       /* If opening the main database, set ENC(db). */
68000       ENC(db) = (u8)meta[4];
68001       db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0);
68002     }else{
68003       /* If opening an attached database, the encoding much match ENC(db) */
68004       if( meta[4]!=ENC(db) ){
68005         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
68006             " text encoding as main database");
68007         rc = SQLITE_ERROR;
68008         goto initone_error_out;
68009       }
68010     }
68011   }else{
68012     DbSetProperty(db, iDb, DB_Empty);
68013   }
68014   pDb->pSchema->enc = ENC(db);
68015
68016   if( pDb->pSchema->cache_size==0 ){
68017     size = meta[2];
68018     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
68019     if( size<0 ) size = -size;
68020     pDb->pSchema->cache_size = size;
68021     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
68022   }
68023
68024   /*
68025   ** file_format==1    Version 3.0.0.
68026   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
68027   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
68028   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
68029   */
68030   pDb->pSchema->file_format = meta[1];
68031   if( pDb->pSchema->file_format==0 ){
68032     pDb->pSchema->file_format = 1;
68033   }
68034   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
68035     sqlite3SetString(pzErrMsg, db, "unsupported file format");
68036     rc = SQLITE_ERROR;
68037     goto initone_error_out;
68038   }
68039
68040   /* Ticket #2804:  When we open a database in the newer file format,
68041   ** clear the legacy_file_format pragma flag so that a VACUUM will
68042   ** not downgrade the database and thus invalidate any descending
68043   ** indices that the user might have created.
68044   */
68045   if( iDb==0 && meta[1]>=4 ){
68046     db->flags &= ~SQLITE_LegacyFileFmt;
68047   }
68048
68049   /* Read the schema information out of the schema tables
68050   */
68051   assert( db->init.busy );
68052   if( rc==SQLITE_EMPTY ){
68053     /* For an empty database, there is nothing to read */
68054     rc = SQLITE_OK;
68055   }else{
68056     char *zSql;
68057     zSql = sqlite3MPrintf(db, 
68058         "SELECT name, rootpage, sql FROM '%q'.%s",
68059         db->aDb[iDb].zName, zMasterName);
68060     (void)sqlite3SafetyOff(db);
68061 #ifndef SQLITE_OMIT_AUTHORIZATION
68062     {
68063       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
68064       xAuth = db->xAuth;
68065       db->xAuth = 0;
68066 #endif
68067       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
68068 #ifndef SQLITE_OMIT_AUTHORIZATION
68069       db->xAuth = xAuth;
68070     }
68071 #endif
68072     if( rc==SQLITE_OK ) rc = initData.rc;
68073     (void)sqlite3SafetyOn(db);
68074     sqlite3DbFree(db, zSql);
68075 #ifndef SQLITE_OMIT_ANALYZE
68076     if( rc==SQLITE_OK ){
68077       sqlite3AnalysisLoad(db, iDb);
68078     }
68079 #endif
68080   }
68081   if( db->mallocFailed ){
68082     rc = SQLITE_NOMEM;
68083     sqlite3ResetInternalSchema(db, 0);
68084   }
68085   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
68086     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
68087     ** the schema loaded, even if errors occured. In this situation the 
68088     ** current sqlite3_prepare() operation will fail, but the following one
68089     ** will attempt to compile the supplied statement against whatever subset
68090     ** of the schema was loaded before the error occured. The primary
68091     ** purpose of this is to allow access to the sqlite_master table
68092     ** even when its contents have been corrupted.
68093     */
68094     DbSetProperty(db, iDb, DB_SchemaLoaded);
68095     rc = SQLITE_OK;
68096   }
68097
68098   /* Jump here for an error that occurs after successfully allocating
68099   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
68100   ** before that point, jump to error_out.
68101   */
68102 initone_error_out:
68103   sqlite3BtreeCloseCursor(curMain);
68104   sqlite3_free(curMain);
68105   sqlite3BtreeLeave(pDb->pBt);
68106
68107 error_out:
68108   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
68109     db->mallocFailed = 1;
68110   }
68111   return rc;
68112 }
68113
68114 /*
68115 ** Initialize all database files - the main database file, the file
68116 ** used to store temporary tables, and any additional database files
68117 ** created using ATTACH statements.  Return a success code.  If an
68118 ** error occurs, write an error message into *pzErrMsg.
68119 **
68120 ** After a database is initialized, the DB_SchemaLoaded bit is set
68121 ** bit is set in the flags field of the Db structure. If the database
68122 ** file was of zero-length, then the DB_Empty flag is also set.
68123 */
68124 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
68125   int i, rc;
68126   int commit_internal = !(db->flags&SQLITE_InternChanges);
68127   
68128   assert( sqlite3_mutex_held(db->mutex) );
68129   if( db->init.busy ) return SQLITE_OK;
68130   rc = SQLITE_OK;
68131   db->init.busy = 1;
68132   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
68133     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
68134     rc = sqlite3InitOne(db, i, pzErrMsg);
68135     if( rc ){
68136       sqlite3ResetInternalSchema(db, i);
68137     }
68138   }
68139
68140   /* Once all the other databases have been initialised, load the schema
68141   ** for the TEMP database. This is loaded last, as the TEMP database
68142   ** schema may contain references to objects in other databases.
68143   */
68144 #ifndef SQLITE_OMIT_TEMPDB
68145   if( rc==SQLITE_OK && db->nDb>1 && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
68146     rc = sqlite3InitOne(db, 1, pzErrMsg);
68147     if( rc ){
68148       sqlite3ResetInternalSchema(db, 1);
68149     }
68150   }
68151 #endif
68152
68153   db->init.busy = 0;
68154   if( rc==SQLITE_OK && commit_internal ){
68155     sqlite3CommitInternalChanges(db);
68156   }
68157
68158   return rc; 
68159 }
68160
68161 /*
68162 ** This routine is a no-op if the database schema is already initialised.
68163 ** Otherwise, the schema is loaded. An error code is returned.
68164 */
68165 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
68166   int rc = SQLITE_OK;
68167   sqlite3 *db = pParse->db;
68168   assert( sqlite3_mutex_held(db->mutex) );
68169   if( !db->init.busy ){
68170     rc = sqlite3Init(db, &pParse->zErrMsg);
68171   }
68172   if( rc!=SQLITE_OK ){
68173     pParse->rc = rc;
68174     pParse->nErr++;
68175   }
68176   return rc;
68177 }
68178
68179
68180 /*
68181 ** Check schema cookies in all databases.  If any cookie is out
68182 ** of date, return 0.  If all schema cookies are current, return 1.
68183 */
68184 static int schemaIsValid(sqlite3 *db){
68185   int iDb;
68186   int rc;
68187   BtCursor *curTemp;
68188   int cookie;
68189   int allOk = 1;
68190
68191   curTemp = (BtCursor *)sqlite3Malloc(sqlite3BtreeCursorSize());
68192   if( curTemp ){
68193     assert( sqlite3_mutex_held(db->mutex) );
68194     for(iDb=0; allOk && iDb<db->nDb; iDb++){
68195       Btree *pBt;
68196       pBt = db->aDb[iDb].pBt;
68197       if( pBt==0 ) continue;
68198       memset(curTemp, 0, sqlite3BtreeCursorSize());
68199       rc = sqlite3BtreeCursor(pBt, MASTER_ROOT, 0, 0, curTemp);
68200       if( rc==SQLITE_OK ){
68201         rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&cookie);
68202         if( rc==SQLITE_OK && cookie!=db->aDb[iDb].pSchema->schema_cookie ){
68203           allOk = 0;
68204         }
68205         sqlite3BtreeCloseCursor(curTemp);
68206       }
68207       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
68208         db->mallocFailed = 1;
68209       }
68210     }
68211     sqlite3_free(curTemp);
68212   }else{
68213     allOk = 0;
68214     db->mallocFailed = 1;
68215   }
68216
68217   return allOk;
68218 }
68219
68220 /*
68221 ** Convert a schema pointer into the iDb index that indicates
68222 ** which database file in db->aDb[] the schema refers to.
68223 **
68224 ** If the same database is attached more than once, the first
68225 ** attached database is returned.
68226 */
68227 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
68228   int i = -1000000;
68229
68230   /* If pSchema is NULL, then return -1000000. This happens when code in 
68231   ** expr.c is trying to resolve a reference to a transient table (i.e. one
68232   ** created by a sub-select). In this case the return value of this 
68233   ** function should never be used.
68234   **
68235   ** We return -1000000 instead of the more usual -1 simply because using
68236   ** -1000000 as incorrectly using -1000000 index into db->aDb[] is much 
68237   ** more likely to cause a segfault than -1 (of course there are assert()
68238   ** statements too, but it never hurts to play the odds).
68239   */
68240   assert( sqlite3_mutex_held(db->mutex) );
68241   if( pSchema ){
68242     for(i=0; i<db->nDb; i++){
68243       if( db->aDb[i].pSchema==pSchema ){
68244         break;
68245       }
68246     }
68247     assert( i>=0 &&i>=0 &&  i<db->nDb );
68248   }
68249   return i;
68250 }
68251
68252 /*
68253 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
68254 */
68255 static int sqlite3Prepare(
68256   sqlite3 *db,              /* Database handle. */
68257   const char *zSql,         /* UTF-8 encoded SQL statement. */
68258   int nBytes,               /* Length of zSql in bytes. */
68259   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
68260   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
68261   const char **pzTail       /* OUT: End of parsed string */
68262 ){
68263   Parse sParse;
68264   char *zErrMsg = 0;
68265   int rc = SQLITE_OK;
68266   int i;
68267
68268   assert( ppStmt );
68269   *ppStmt = 0;
68270   if( sqlite3SafetyOn(db) ){
68271     return SQLITE_MISUSE;
68272   }
68273   assert( !db->mallocFailed );
68274   assert( sqlite3_mutex_held(db->mutex) );
68275
68276   /* If any attached database schemas are locked, do not proceed with
68277   ** compilation. Instead return SQLITE_LOCKED immediately.
68278   */
68279   for(i=0; i<db->nDb; i++) {
68280     Btree *pBt = db->aDb[i].pBt;
68281     if( pBt ){
68282       int rc;
68283       rc = sqlite3BtreeSchemaLocked(pBt);
68284       if( rc ){
68285         const char *zDb = db->aDb[i].zName;
68286         sqlite3Error(db, SQLITE_LOCKED, "database schema is locked: %s", zDb);
68287         (void)sqlite3SafetyOff(db);
68288         return sqlite3ApiExit(db, SQLITE_LOCKED);
68289       }
68290     }
68291   }
68292   
68293   memset(&sParse, 0, sizeof(sParse));
68294   sParse.db = db;
68295   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
68296     char *zSqlCopy;
68297     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
68298     if( nBytes>mxLen ){
68299       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
68300       (void)sqlite3SafetyOff(db);
68301       return sqlite3ApiExit(db, SQLITE_TOOBIG);
68302     }
68303     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
68304     if( zSqlCopy ){
68305       sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
68306       sqlite3DbFree(db, zSqlCopy);
68307       sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
68308     }else{
68309       sParse.zTail = &zSql[nBytes];
68310     }
68311   }else{
68312     sqlite3RunParser(&sParse, zSql, &zErrMsg);
68313   }
68314
68315   if( db->mallocFailed ){
68316     sParse.rc = SQLITE_NOMEM;
68317   }
68318   if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
68319   if( sParse.checkSchema && !schemaIsValid(db) ){
68320     sParse.rc = SQLITE_SCHEMA;
68321   }
68322   if( sParse.rc==SQLITE_SCHEMA ){
68323     sqlite3ResetInternalSchema(db, 0);
68324   }
68325   if( db->mallocFailed ){
68326     sParse.rc = SQLITE_NOMEM;
68327   }
68328   if( pzTail ){
68329     *pzTail = sParse.zTail;
68330   }
68331   rc = sParse.rc;
68332
68333 #ifndef SQLITE_OMIT_EXPLAIN
68334   if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
68335     if( sParse.explain==2 ){
68336       sqlite3VdbeSetNumCols(sParse.pVdbe, 3);
68337       sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "order", P4_STATIC);
68338       sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "from", P4_STATIC);
68339       sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "detail", P4_STATIC);
68340     }else{
68341       sqlite3VdbeSetNumCols(sParse.pVdbe, 8);
68342       sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "addr", P4_STATIC);
68343       sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "opcode", P4_STATIC);
68344       sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "p1", P4_STATIC);
68345       sqlite3VdbeSetColName(sParse.pVdbe, 3, COLNAME_NAME, "p2", P4_STATIC);
68346       sqlite3VdbeSetColName(sParse.pVdbe, 4, COLNAME_NAME, "p3", P4_STATIC);
68347       sqlite3VdbeSetColName(sParse.pVdbe, 5, COLNAME_NAME, "p4", P4_STATIC);
68348       sqlite3VdbeSetColName(sParse.pVdbe, 6, COLNAME_NAME, "p5", P4_STATIC);
68349       sqlite3VdbeSetColName(sParse.pVdbe, 7, COLNAME_NAME, "comment",P4_STATIC);
68350     }
68351   }
68352 #endif
68353
68354   if( sqlite3SafetyOff(db) ){
68355     rc = SQLITE_MISUSE;
68356   }
68357
68358   if( saveSqlFlag ){
68359     sqlite3VdbeSetSql(sParse.pVdbe, zSql, sParse.zTail - zSql);
68360   }
68361   if( rc!=SQLITE_OK || db->mallocFailed ){
68362     sqlite3_finalize((sqlite3_stmt*)sParse.pVdbe);
68363     assert(!(*ppStmt));
68364   }else{
68365     *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
68366   }
68367
68368   if( zErrMsg ){
68369     sqlite3Error(db, rc, "%s", zErrMsg);
68370     sqlite3DbFree(db, zErrMsg);
68371   }else{
68372     sqlite3Error(db, rc, 0);
68373   }
68374
68375   rc = sqlite3ApiExit(db, rc);
68376   assert( (rc&db->errMask)==rc );
68377   return rc;
68378 }
68379 static int sqlite3LockAndPrepare(
68380   sqlite3 *db,              /* Database handle. */
68381   const char *zSql,         /* UTF-8 encoded SQL statement. */
68382   int nBytes,               /* Length of zSql in bytes. */
68383   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
68384   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
68385   const char **pzTail       /* OUT: End of parsed string */
68386 ){
68387   int rc;
68388   if( !sqlite3SafetyCheckOk(db) ){
68389     return SQLITE_MISUSE;
68390   }
68391   sqlite3_mutex_enter(db->mutex);
68392   sqlite3BtreeEnterAll(db);
68393   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, ppStmt, pzTail);
68394   sqlite3BtreeLeaveAll(db);
68395   sqlite3_mutex_leave(db->mutex);
68396   return rc;
68397 }
68398
68399 /*
68400 ** Rerun the compilation of a statement after a schema change.
68401 ** Return true if the statement was recompiled successfully.
68402 ** Return false if there is an error of some kind.
68403 */
68404 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
68405   int rc;
68406   sqlite3_stmt *pNew;
68407   const char *zSql;
68408   sqlite3 *db;
68409
68410   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
68411   zSql = sqlite3_sql((sqlite3_stmt *)p);
68412   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
68413   db = sqlite3VdbeDb(p);
68414   assert( sqlite3_mutex_held(db->mutex) );
68415   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, &pNew, 0);
68416   if( rc ){
68417     if( rc==SQLITE_NOMEM ){
68418       db->mallocFailed = 1;
68419     }
68420     assert( pNew==0 );
68421     return 0;
68422   }else{
68423     assert( pNew!=0 );
68424   }
68425   sqlite3VdbeSwap((Vdbe*)pNew, p);
68426   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
68427   sqlite3VdbeResetStepResult((Vdbe*)pNew);
68428   sqlite3VdbeFinalize((Vdbe*)pNew);
68429   return 1;
68430 }
68431
68432
68433 /*
68434 ** Two versions of the official API.  Legacy and new use.  In the legacy
68435 ** version, the original SQL text is not saved in the prepared statement
68436 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
68437 ** sqlite3_step().  In the new version, the original SQL text is retained
68438 ** and the statement is automatically recompiled if an schema change
68439 ** occurs.
68440 */
68441 SQLITE_API int sqlite3_prepare(
68442   sqlite3 *db,              /* Database handle. */
68443   const char *zSql,         /* UTF-8 encoded SQL statement. */
68444   int nBytes,               /* Length of zSql in bytes. */
68445   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
68446   const char **pzTail       /* OUT: End of parsed string */
68447 ){
68448   int rc;
68449   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,ppStmt,pzTail);
68450   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
68451   return rc;
68452 }
68453 SQLITE_API int sqlite3_prepare_v2(
68454   sqlite3 *db,              /* Database handle. */
68455   const char *zSql,         /* UTF-8 encoded SQL statement. */
68456   int nBytes,               /* Length of zSql in bytes. */
68457   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
68458   const char **pzTail       /* OUT: End of parsed string */
68459 ){
68460   int rc;
68461   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,ppStmt,pzTail);
68462   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
68463   return rc;
68464 }
68465
68466
68467 #ifndef SQLITE_OMIT_UTF16
68468 /*
68469 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
68470 */
68471 static int sqlite3Prepare16(
68472   sqlite3 *db,              /* Database handle. */ 
68473   const void *zSql,         /* UTF-8 encoded SQL statement. */
68474   int nBytes,               /* Length of zSql in bytes. */
68475   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
68476   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
68477   const void **pzTail       /* OUT: End of parsed string */
68478 ){
68479   /* This function currently works by first transforming the UTF-16
68480   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
68481   ** tricky bit is figuring out the pointer to return in *pzTail.
68482   */
68483   char *zSql8;
68484   const char *zTail8 = 0;
68485   int rc = SQLITE_OK;
68486
68487   if( !sqlite3SafetyCheckOk(db) ){
68488     return SQLITE_MISUSE;
68489   }
68490   sqlite3_mutex_enter(db->mutex);
68491   zSql8 = sqlite3Utf16to8(db, zSql, nBytes);
68492   if( zSql8 ){
68493     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, ppStmt, &zTail8);
68494   }
68495
68496   if( zTail8 && pzTail ){
68497     /* If sqlite3_prepare returns a tail pointer, we calculate the
68498     ** equivalent pointer into the UTF-16 string by counting the unicode
68499     ** characters between zSql8 and zTail8, and then returning a pointer
68500     ** the same number of characters into the UTF-16 string.
68501     */
68502     int chars_parsed = sqlite3Utf8CharLen(zSql8, zTail8-zSql8);
68503     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
68504   }
68505   sqlite3DbFree(db, zSql8); 
68506   rc = sqlite3ApiExit(db, rc);
68507   sqlite3_mutex_leave(db->mutex);
68508   return rc;
68509 }
68510
68511 /*
68512 ** Two versions of the official API.  Legacy and new use.  In the legacy
68513 ** version, the original SQL text is not saved in the prepared statement
68514 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
68515 ** sqlite3_step().  In the new version, the original SQL text is retained
68516 ** and the statement is automatically recompiled if an schema change
68517 ** occurs.
68518 */
68519 SQLITE_API int sqlite3_prepare16(
68520   sqlite3 *db,              /* Database handle. */ 
68521   const void *zSql,         /* UTF-8 encoded SQL statement. */
68522   int nBytes,               /* Length of zSql in bytes. */
68523   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
68524   const void **pzTail       /* OUT: End of parsed string */
68525 ){
68526   int rc;
68527   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
68528   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
68529   return rc;
68530 }
68531 SQLITE_API int sqlite3_prepare16_v2(
68532   sqlite3 *db,              /* Database handle. */ 
68533   const void *zSql,         /* UTF-8 encoded SQL statement. */
68534   int nBytes,               /* Length of zSql in bytes. */
68535   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
68536   const void **pzTail       /* OUT: End of parsed string */
68537 ){
68538   int rc;
68539   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
68540   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
68541   return rc;
68542 }
68543
68544 #endif /* SQLITE_OMIT_UTF16 */
68545
68546 /************** End of prepare.c *********************************************/
68547 /************** Begin file select.c ******************************************/
68548 /*
68549 ** 2001 September 15
68550 **
68551 ** The author disclaims copyright to this source code.  In place of
68552 ** a legal notice, here is a blessing:
68553 **
68554 **    May you do good and not evil.
68555 **    May you find forgiveness for yourself and forgive others.
68556 **    May you share freely, never taking more than you give.
68557 **
68558 *************************************************************************
68559 ** This file contains C code routines that are called by the parser
68560 ** to handle SELECT statements in SQLite.
68561 **
68562 ** $Id: select.c,v 1.475 2008/09/17 00:13:12 drh Exp $
68563 */
68564
68565
68566 /*
68567 ** Delete all the content of a Select structure but do not deallocate
68568 ** the select structure itself.
68569 */
68570 static void clearSelect(sqlite3 *db, Select *p){
68571   sqlite3ExprListDelete(db, p->pEList);
68572   sqlite3SrcListDelete(db, p->pSrc);
68573   sqlite3ExprDelete(db, p->pWhere);
68574   sqlite3ExprListDelete(db, p->pGroupBy);
68575   sqlite3ExprDelete(db, p->pHaving);
68576   sqlite3ExprListDelete(db, p->pOrderBy);
68577   sqlite3SelectDelete(db, p->pPrior);
68578   sqlite3ExprDelete(db, p->pLimit);
68579   sqlite3ExprDelete(db, p->pOffset);
68580 }
68581
68582 /*
68583 ** Initialize a SelectDest structure.
68584 */
68585 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
68586   pDest->eDest = eDest;
68587   pDest->iParm = iParm;
68588   pDest->affinity = 0;
68589   pDest->iMem = 0;
68590   pDest->nMem = 0;
68591 }
68592
68593
68594 /*
68595 ** Allocate a new Select structure and return a pointer to that
68596 ** structure.
68597 */
68598 SQLITE_PRIVATE Select *sqlite3SelectNew(
68599   Parse *pParse,        /* Parsing context */
68600   ExprList *pEList,     /* which columns to include in the result */
68601   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
68602   Expr *pWhere,         /* the WHERE clause */
68603   ExprList *pGroupBy,   /* the GROUP BY clause */
68604   Expr *pHaving,        /* the HAVING clause */
68605   ExprList *pOrderBy,   /* the ORDER BY clause */
68606   int isDistinct,       /* true if the DISTINCT keyword is present */
68607   Expr *pLimit,         /* LIMIT value.  NULL means not used */
68608   Expr *pOffset         /* OFFSET value.  NULL means no offset */
68609 ){
68610   Select *pNew;
68611   Select standin;
68612   sqlite3 *db = pParse->db;
68613   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
68614   assert( !pOffset || pLimit );   /* Can't have OFFSET without LIMIT. */
68615   if( pNew==0 ){
68616     pNew = &standin;
68617     memset(pNew, 0, sizeof(*pNew));
68618   }
68619   if( pEList==0 ){
68620     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0,0,0), 0);
68621   }
68622   pNew->pEList = pEList;
68623   pNew->pSrc = pSrc;
68624   pNew->pWhere = pWhere;
68625   pNew->pGroupBy = pGroupBy;
68626   pNew->pHaving = pHaving;
68627   pNew->pOrderBy = pOrderBy;
68628   pNew->selFlags = isDistinct ? SF_Distinct : 0;
68629   pNew->op = TK_SELECT;
68630   assert( pOffset==0 || pLimit!=0 );
68631   pNew->pLimit = pLimit;
68632   pNew->pOffset = pOffset;
68633   pNew->addrOpenEphm[0] = -1;
68634   pNew->addrOpenEphm[1] = -1;
68635   pNew->addrOpenEphm[2] = -1;
68636   if( db->mallocFailed ) {
68637     clearSelect(db, pNew);
68638     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
68639     pNew = 0;
68640   }
68641   return pNew;
68642 }
68643
68644 /*
68645 ** Delete the given Select structure and all of its substructures.
68646 */
68647 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
68648   if( p ){
68649     clearSelect(db, p);
68650     sqlite3DbFree(db, p);
68651   }
68652 }
68653
68654 /*
68655 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
68656 ** type of join.  Return an integer constant that expresses that type
68657 ** in terms of the following bit values:
68658 **
68659 **     JT_INNER
68660 **     JT_CROSS
68661 **     JT_OUTER
68662 **     JT_NATURAL
68663 **     JT_LEFT
68664 **     JT_RIGHT
68665 **
68666 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
68667 **
68668 ** If an illegal or unsupported join type is seen, then still return
68669 ** a join type, but put an error in the pParse structure.
68670 */
68671 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
68672   int jointype = 0;
68673   Token *apAll[3];
68674   Token *p;
68675   static const struct {
68676     const char zKeyword[8];
68677     u8 nChar;
68678     u8 code;
68679   } keywords[] = {
68680     { "natural", 7, JT_NATURAL },
68681     { "left",    4, JT_LEFT|JT_OUTER },
68682     { "right",   5, JT_RIGHT|JT_OUTER },
68683     { "full",    4, JT_LEFT|JT_RIGHT|JT_OUTER },
68684     { "outer",   5, JT_OUTER },
68685     { "inner",   5, JT_INNER },
68686     { "cross",   5, JT_INNER|JT_CROSS },
68687   };
68688   int i, j;
68689   apAll[0] = pA;
68690   apAll[1] = pB;
68691   apAll[2] = pC;
68692   for(i=0; i<3 && apAll[i]; i++){
68693     p = apAll[i];
68694     for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
68695       if( p->n==keywords[j].nChar 
68696           && sqlite3StrNICmp((char*)p->z, keywords[j].zKeyword, p->n)==0 ){
68697         jointype |= keywords[j].code;
68698         break;
68699       }
68700     }
68701     if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
68702       jointype |= JT_ERROR;
68703       break;
68704     }
68705   }
68706   if(
68707      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
68708      (jointype & JT_ERROR)!=0
68709   ){
68710     const char *zSp = " ";
68711     assert( pB!=0 );
68712     if( pC==0 ){ zSp++; }
68713     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
68714        "%T %T%s%T", pA, pB, zSp, pC);
68715     jointype = JT_INNER;
68716   }else if( jointype & JT_RIGHT ){
68717     sqlite3ErrorMsg(pParse, 
68718       "RIGHT and FULL OUTER JOINs are not currently supported");
68719     jointype = JT_INNER;
68720   }
68721   return jointype;
68722 }
68723
68724 /*
68725 ** Return the index of a column in a table.  Return -1 if the column
68726 ** is not contained in the table.
68727 */
68728 static int columnIndex(Table *pTab, const char *zCol){
68729   int i;
68730   for(i=0; i<pTab->nCol; i++){
68731     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
68732   }
68733   return -1;
68734 }
68735
68736 /*
68737 ** Set the value of a token to a '\000'-terminated string.
68738 */
68739 static void setToken(Token *p, const char *z){
68740   p->z = (u8*)z;
68741   p->n = z ? strlen(z) : 0;
68742   p->dyn = 0;
68743 }
68744
68745 /*
68746 ** Set the token to the double-quoted and escaped version of the string pointed
68747 ** to by z. For example;
68748 **
68749 **    {a"bc}  ->  {"a""bc"}
68750 */
68751 static void setQuotedToken(Parse *pParse, Token *p, const char *z){
68752
68753   /* Check if the string appears to be quoted using "..." or `...`
68754   ** or [...] or '...' or if the string contains any " characters.  
68755   ** If it does, then record a version of the string with the special
68756   ** characters escaped.
68757   */
68758   const char *z2 = z;
68759   if( *z2!='[' && *z2!='`' && *z2!='\'' ){
68760     while( *z2 ){
68761       if( *z2=='"' ) break;
68762       z2++;
68763     }
68764   }
68765
68766   if( *z2 ){
68767     /* String contains " characters - copy and quote the string. */
68768     p->z = (u8 *)sqlite3MPrintf(pParse->db, "\"%w\"", z);
68769     if( p->z ){
68770       p->n = strlen((char *)p->z);
68771       p->dyn = 1;
68772     }
68773   }else{
68774     /* String contains no " characters - copy the pointer. */
68775     p->z = (u8*)z;
68776     p->n = (z2 - z);
68777     p->dyn = 0;
68778   }
68779 }
68780
68781 /*
68782 ** Create an expression node for an identifier with the name of zName
68783 */
68784 SQLITE_PRIVATE Expr *sqlite3CreateIdExpr(Parse *pParse, const char *zName){
68785   Token dummy;
68786   setToken(&dummy, zName);
68787   return sqlite3PExpr(pParse, TK_ID, 0, 0, &dummy);
68788 }
68789
68790 /*
68791 ** Add a term to the WHERE expression in *ppExpr that requires the
68792 ** zCol column to be equal in the two tables pTab1 and pTab2.
68793 */
68794 static void addWhereTerm(
68795   Parse *pParse,           /* Parsing context */
68796   const char *zCol,        /* Name of the column */
68797   const Table *pTab1,      /* First table */
68798   const char *zAlias1,     /* Alias for first table.  May be NULL */
68799   const Table *pTab2,      /* Second table */
68800   const char *zAlias2,     /* Alias for second table.  May be NULL */
68801   int iRightJoinTable,     /* VDBE cursor for the right table */
68802   Expr **ppExpr,           /* Add the equality term to this expression */
68803   int isOuterJoin          /* True if dealing with an OUTER join */
68804 ){
68805   Expr *pE1a, *pE1b, *pE1c;
68806   Expr *pE2a, *pE2b, *pE2c;
68807   Expr *pE;
68808
68809   pE1a = sqlite3CreateIdExpr(pParse, zCol);
68810   pE2a = sqlite3CreateIdExpr(pParse, zCol);
68811   if( zAlias1==0 ){
68812     zAlias1 = pTab1->zName;
68813   }
68814   pE1b = sqlite3CreateIdExpr(pParse, zAlias1);
68815   if( zAlias2==0 ){
68816     zAlias2 = pTab2->zName;
68817   }
68818   pE2b = sqlite3CreateIdExpr(pParse, zAlias2);
68819   pE1c = sqlite3PExpr(pParse, TK_DOT, pE1b, pE1a, 0);
68820   pE2c = sqlite3PExpr(pParse, TK_DOT, pE2b, pE2a, 0);
68821   pE = sqlite3PExpr(pParse, TK_EQ, pE1c, pE2c, 0);
68822   if( pE && isOuterJoin ){
68823     ExprSetProperty(pE, EP_FromJoin);
68824     pE->iRightJoinTable = iRightJoinTable;
68825   }
68826   *ppExpr = sqlite3ExprAnd(pParse->db,*ppExpr, pE);
68827 }
68828
68829 /*
68830 ** Set the EP_FromJoin property on all terms of the given expression.
68831 ** And set the Expr.iRightJoinTable to iTable for every term in the
68832 ** expression.
68833 **
68834 ** The EP_FromJoin property is used on terms of an expression to tell
68835 ** the LEFT OUTER JOIN processing logic that this term is part of the
68836 ** join restriction specified in the ON or USING clause and not a part
68837 ** of the more general WHERE clause.  These terms are moved over to the
68838 ** WHERE clause during join processing but we need to remember that they
68839 ** originated in the ON or USING clause.
68840 **
68841 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
68842 ** expression depends on table iRightJoinTable even if that table is not
68843 ** explicitly mentioned in the expression.  That information is needed
68844 ** for cases like this:
68845 **
68846 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
68847 **
68848 ** The where clause needs to defer the handling of the t1.x=5
68849 ** term until after the t2 loop of the join.  In that way, a
68850 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
68851 ** defer the handling of t1.x=5, it will be processed immediately
68852 ** after the t1 loop and rows with t1.x!=5 will never appear in
68853 ** the output, which is incorrect.
68854 */
68855 static void setJoinExpr(Expr *p, int iTable){
68856   while( p ){
68857     ExprSetProperty(p, EP_FromJoin);
68858     p->iRightJoinTable = iTable;
68859     setJoinExpr(p->pLeft, iTable);
68860     p = p->pRight;
68861   } 
68862 }
68863
68864 /*
68865 ** This routine processes the join information for a SELECT statement.
68866 ** ON and USING clauses are converted into extra terms of the WHERE clause.
68867 ** NATURAL joins also create extra WHERE clause terms.
68868 **
68869 ** The terms of a FROM clause are contained in the Select.pSrc structure.
68870 ** The left most table is the first entry in Select.pSrc.  The right-most
68871 ** table is the last entry.  The join operator is held in the entry to
68872 ** the left.  Thus entry 0 contains the join operator for the join between
68873 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
68874 ** also attached to the left entry.
68875 **
68876 ** This routine returns the number of errors encountered.
68877 */
68878 static int sqliteProcessJoin(Parse *pParse, Select *p){
68879   SrcList *pSrc;                  /* All tables in the FROM clause */
68880   int i, j;                       /* Loop counters */
68881   struct SrcList_item *pLeft;     /* Left table being joined */
68882   struct SrcList_item *pRight;    /* Right table being joined */
68883
68884   pSrc = p->pSrc;
68885   pLeft = &pSrc->a[0];
68886   pRight = &pLeft[1];
68887   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
68888     Table *pLeftTab = pLeft->pTab;
68889     Table *pRightTab = pRight->pTab;
68890     int isOuter;
68891
68892     if( pLeftTab==0 || pRightTab==0 ) continue;
68893     isOuter = (pRight->jointype & JT_OUTER)!=0;
68894
68895     /* When the NATURAL keyword is present, add WHERE clause terms for
68896     ** every column that the two tables have in common.
68897     */
68898     if( pRight->jointype & JT_NATURAL ){
68899       if( pRight->pOn || pRight->pUsing ){
68900         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
68901            "an ON or USING clause", 0);
68902         return 1;
68903       }
68904       for(j=0; j<pLeftTab->nCol; j++){
68905         char *zName = pLeftTab->aCol[j].zName;
68906         if( columnIndex(pRightTab, zName)>=0 ){
68907           addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, 
68908                               pRightTab, pRight->zAlias,
68909                               pRight->iCursor, &p->pWhere, isOuter);
68910           
68911         }
68912       }
68913     }
68914
68915     /* Disallow both ON and USING clauses in the same join
68916     */
68917     if( pRight->pOn && pRight->pUsing ){
68918       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
68919         "clauses in the same join");
68920       return 1;
68921     }
68922
68923     /* Add the ON clause to the end of the WHERE clause, connected by
68924     ** an AND operator.
68925     */
68926     if( pRight->pOn ){
68927       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
68928       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
68929       pRight->pOn = 0;
68930     }
68931
68932     /* Create extra terms on the WHERE clause for each column named
68933     ** in the USING clause.  Example: If the two tables to be joined are 
68934     ** A and B and the USING clause names X, Y, and Z, then add this
68935     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
68936     ** Report an error if any column mentioned in the USING clause is
68937     ** not contained in both tables to be joined.
68938     */
68939     if( pRight->pUsing ){
68940       IdList *pList = pRight->pUsing;
68941       for(j=0; j<pList->nId; j++){
68942         char *zName = pList->a[j].zName;
68943         if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
68944           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
68945             "not present in both tables", zName);
68946           return 1;
68947         }
68948         addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, 
68949                             pRightTab, pRight->zAlias,
68950                             pRight->iCursor, &p->pWhere, isOuter);
68951       }
68952     }
68953   }
68954   return 0;
68955 }
68956
68957 /*
68958 ** Insert code into "v" that will push the record on the top of the
68959 ** stack into the sorter.
68960 */
68961 static void pushOntoSorter(
68962   Parse *pParse,         /* Parser context */
68963   ExprList *pOrderBy,    /* The ORDER BY clause */
68964   Select *pSelect,       /* The whole SELECT statement */
68965   int regData            /* Register holding data to be sorted */
68966 ){
68967   Vdbe *v = pParse->pVdbe;
68968   int nExpr = pOrderBy->nExpr;
68969   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
68970   int regRecord = sqlite3GetTempReg(pParse);
68971   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
68972   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
68973   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
68974   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
68975   sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
68976   sqlite3ReleaseTempReg(pParse, regRecord);
68977   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
68978   if( pSelect->iLimit ){
68979     int addr1, addr2;
68980     int iLimit;
68981     if( pSelect->iOffset ){
68982       iLimit = pSelect->iOffset+1;
68983     }else{
68984       iLimit = pSelect->iLimit;
68985     }
68986     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
68987     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
68988     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
68989     sqlite3VdbeJumpHere(v, addr1);
68990     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
68991     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
68992     sqlite3VdbeJumpHere(v, addr2);
68993     pSelect->iLimit = 0;
68994   }
68995 }
68996
68997 /*
68998 ** Add code to implement the OFFSET
68999 */
69000 static void codeOffset(
69001   Vdbe *v,          /* Generate code into this VM */
69002   Select *p,        /* The SELECT statement being coded */
69003   int iContinue     /* Jump here to skip the current record */
69004 ){
69005   if( p->iOffset && iContinue!=0 ){
69006     int addr;
69007     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
69008     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
69009     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
69010     VdbeComment((v, "skip OFFSET records"));
69011     sqlite3VdbeJumpHere(v, addr);
69012   }
69013 }
69014
69015 /*
69016 ** Add code that will check to make sure the N registers starting at iMem
69017 ** form a distinct entry.  iTab is a sorting index that holds previously
69018 ** seen combinations of the N values.  A new entry is made in iTab
69019 ** if the current N values are new.
69020 **
69021 ** A jump to addrRepeat is made and the N+1 values are popped from the
69022 ** stack if the top N elements are not distinct.
69023 */
69024 static void codeDistinct(
69025   Parse *pParse,     /* Parsing and code generating context */
69026   int iTab,          /* A sorting index used to test for distinctness */
69027   int addrRepeat,    /* Jump to here if not distinct */
69028   int N,             /* Number of elements */
69029   int iMem           /* First element */
69030 ){
69031   Vdbe *v;
69032   int r1;
69033
69034   v = pParse->pVdbe;
69035   r1 = sqlite3GetTempReg(pParse);
69036   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
69037   sqlite3VdbeAddOp3(v, OP_Found, iTab, addrRepeat, r1);
69038   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
69039   sqlite3ReleaseTempReg(pParse, r1);
69040 }
69041
69042 /*
69043 ** Generate an error message when a SELECT is used within a subexpression
69044 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
69045 ** column.  We do this in a subroutine because the error occurs in multiple
69046 ** places.
69047 */
69048 static int checkForMultiColumnSelectError(
69049   Parse *pParse,       /* Parse context. */
69050   SelectDest *pDest,   /* Destination of SELECT results */
69051   int nExpr            /* Number of result columns returned by SELECT */
69052 ){
69053   int eDest = pDest->eDest;
69054   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
69055     sqlite3ErrorMsg(pParse, "only a single result allowed for "
69056        "a SELECT that is part of an expression");
69057     return 1;
69058   }else{
69059     return 0;
69060   }
69061 }
69062
69063 /*
69064 ** This routine generates the code for the inside of the inner loop
69065 ** of a SELECT.
69066 **
69067 ** If srcTab and nColumn are both zero, then the pEList expressions
69068 ** are evaluated in order to get the data for this row.  If nColumn>0
69069 ** then data is pulled from srcTab and pEList is used only to get the
69070 ** datatypes for each column.
69071 */
69072 static void selectInnerLoop(
69073   Parse *pParse,          /* The parser context */
69074   Select *p,              /* The complete select statement being coded */
69075   ExprList *pEList,       /* List of values being extracted */
69076   int srcTab,             /* Pull data from this table */
69077   int nColumn,            /* Number of columns in the source table */
69078   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
69079   int distinct,           /* If >=0, make sure results are distinct */
69080   SelectDest *pDest,      /* How to dispose of the results */
69081   int iContinue,          /* Jump here to continue with next row */
69082   int iBreak              /* Jump here to break out of the inner loop */
69083 ){
69084   Vdbe *v = pParse->pVdbe;
69085   int i;
69086   int hasDistinct;        /* True if the DISTINCT keyword is present */
69087   int regResult;              /* Start of memory holding result set */
69088   int eDest = pDest->eDest;   /* How to dispose of results */
69089   int iParm = pDest->iParm;   /* First argument to disposal method */
69090   int nResultCol;             /* Number of result columns */
69091
69092   if( v==0 ) return;
69093   assert( pEList!=0 );
69094   hasDistinct = distinct>=0;
69095   if( pOrderBy==0 && !hasDistinct ){
69096     codeOffset(v, p, iContinue);
69097   }
69098
69099   /* Pull the requested columns.
69100   */
69101   if( nColumn>0 ){
69102     nResultCol = nColumn;
69103   }else{
69104     nResultCol = pEList->nExpr;
69105   }
69106   if( pDest->iMem==0 ){
69107     pDest->iMem = pParse->nMem+1;
69108     pDest->nMem = nResultCol;
69109     pParse->nMem += nResultCol;
69110   }else if( pDest->nMem!=nResultCol ){
69111     /* This happens when two SELECTs of a compound SELECT have differing
69112     ** numbers of result columns.  The error message will be generated by
69113     ** a higher-level routine. */
69114     return;
69115   }
69116   regResult = pDest->iMem;
69117   if( nColumn>0 ){
69118     for(i=0; i<nColumn; i++){
69119       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
69120     }
69121   }else if( eDest!=SRT_Exists ){
69122     /* If the destination is an EXISTS(...) expression, the actual
69123     ** values returned by the SELECT are not required.
69124     */
69125     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
69126   }
69127   nColumn = nResultCol;
69128
69129   /* If the DISTINCT keyword was present on the SELECT statement
69130   ** and this row has been seen before, then do not make this row
69131   ** part of the result.
69132   */
69133   if( hasDistinct ){
69134     assert( pEList!=0 );
69135     assert( pEList->nExpr==nColumn );
69136     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
69137     if( pOrderBy==0 ){
69138       codeOffset(v, p, iContinue);
69139     }
69140   }
69141
69142   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
69143     return;
69144   }
69145
69146   switch( eDest ){
69147     /* In this mode, write each query result to the key of the temporary
69148     ** table iParm.
69149     */
69150 #ifndef SQLITE_OMIT_COMPOUND_SELECT
69151     case SRT_Union: {
69152       int r1;
69153       r1 = sqlite3GetTempReg(pParse);
69154       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
69155       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
69156       sqlite3ReleaseTempReg(pParse, r1);
69157       break;
69158     }
69159
69160     /* Construct a record from the query result, but instead of
69161     ** saving that record, use it as a key to delete elements from
69162     ** the temporary table iParm.
69163     */
69164     case SRT_Except: {
69165       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
69166       break;
69167     }
69168 #endif
69169
69170     /* Store the result as data using a unique key.
69171     */
69172     case SRT_Table:
69173     case SRT_EphemTab: {
69174       int r1 = sqlite3GetTempReg(pParse);
69175       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
69176       if( pOrderBy ){
69177         pushOntoSorter(pParse, pOrderBy, p, r1);
69178       }else{
69179         int r2 = sqlite3GetTempReg(pParse);
69180         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
69181         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
69182         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
69183         sqlite3ReleaseTempReg(pParse, r2);
69184       }
69185       sqlite3ReleaseTempReg(pParse, r1);
69186       break;
69187     }
69188
69189 #ifndef SQLITE_OMIT_SUBQUERY
69190     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
69191     ** then there should be a single item on the stack.  Write this
69192     ** item into the set table with bogus data.
69193     */
69194     case SRT_Set: {
69195       assert( nColumn==1 );
69196       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
69197       if( pOrderBy ){
69198         /* At first glance you would think we could optimize out the
69199         ** ORDER BY in this case since the order of entries in the set
69200         ** does not matter.  But there might be a LIMIT clause, in which
69201         ** case the order does matter */
69202         pushOntoSorter(pParse, pOrderBy, p, regResult);
69203       }else{
69204         int r1 = sqlite3GetTempReg(pParse);
69205         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
69206         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
69207         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
69208         sqlite3ReleaseTempReg(pParse, r1);
69209       }
69210       break;
69211     }
69212
69213     /* If any row exist in the result set, record that fact and abort.
69214     */
69215     case SRT_Exists: {
69216       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
69217       /* The LIMIT clause will terminate the loop for us */
69218       break;
69219     }
69220
69221     /* If this is a scalar select that is part of an expression, then
69222     ** store the results in the appropriate memory cell and break out
69223     ** of the scan loop.
69224     */
69225     case SRT_Mem: {
69226       assert( nColumn==1 );
69227       if( pOrderBy ){
69228         pushOntoSorter(pParse, pOrderBy, p, regResult);
69229       }else{
69230         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
69231         /* The LIMIT clause will jump out of the loop for us */
69232       }
69233       break;
69234     }
69235 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
69236
69237     /* Send the data to the callback function or to a subroutine.  In the
69238     ** case of a subroutine, the subroutine itself is responsible for
69239     ** popping the data from the stack.
69240     */
69241     case SRT_Coroutine:
69242     case SRT_Output: {
69243       if( pOrderBy ){
69244         int r1 = sqlite3GetTempReg(pParse);
69245         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
69246         pushOntoSorter(pParse, pOrderBy, p, r1);
69247         sqlite3ReleaseTempReg(pParse, r1);
69248       }else if( eDest==SRT_Coroutine ){
69249         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
69250       }else{
69251         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
69252         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
69253       }
69254       break;
69255     }
69256
69257 #if !defined(SQLITE_OMIT_TRIGGER)
69258     /* Discard the results.  This is used for SELECT statements inside
69259     ** the body of a TRIGGER.  The purpose of such selects is to call
69260     ** user-defined functions that have side effects.  We do not care
69261     ** about the actual results of the select.
69262     */
69263     default: {
69264       assert( eDest==SRT_Discard );
69265       break;
69266     }
69267 #endif
69268   }
69269
69270   /* Jump to the end of the loop if the LIMIT is reached.
69271   */
69272   if( p->iLimit ){
69273     assert( pOrderBy==0 );  /* If there is an ORDER BY, the call to
69274                             ** pushOntoSorter() would have cleared p->iLimit */
69275     sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
69276     sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak);
69277   }
69278 }
69279
69280 /*
69281 ** Given an expression list, generate a KeyInfo structure that records
69282 ** the collating sequence for each expression in that expression list.
69283 **
69284 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
69285 ** KeyInfo structure is appropriate for initializing a virtual index to
69286 ** implement that clause.  If the ExprList is the result set of a SELECT
69287 ** then the KeyInfo structure is appropriate for initializing a virtual
69288 ** index to implement a DISTINCT test.
69289 **
69290 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
69291 ** function is responsible for seeing that this structure is eventually
69292 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
69293 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
69294 */
69295 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
69296   sqlite3 *db = pParse->db;
69297   int nExpr;
69298   KeyInfo *pInfo;
69299   struct ExprList_item *pItem;
69300   int i;
69301
69302   nExpr = pList->nExpr;
69303   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
69304   if( pInfo ){
69305     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
69306     pInfo->nField = nExpr;
69307     pInfo->enc = ENC(db);
69308     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
69309       CollSeq *pColl;
69310       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
69311       if( !pColl ){
69312         pColl = db->pDfltColl;
69313       }
69314       pInfo->aColl[i] = pColl;
69315       pInfo->aSortOrder[i] = pItem->sortOrder;
69316     }
69317   }
69318   return pInfo;
69319 }
69320
69321
69322 /*
69323 ** If the inner loop was generated using a non-null pOrderBy argument,
69324 ** then the results were placed in a sorter.  After the loop is terminated
69325 ** we need to run the sorter and output the results.  The following
69326 ** routine generates the code needed to do that.
69327 */
69328 static void generateSortTail(
69329   Parse *pParse,    /* Parsing context */
69330   Select *p,        /* The SELECT statement */
69331   Vdbe *v,          /* Generate code into this VDBE */
69332   int nColumn,      /* Number of columns of data */
69333   SelectDest *pDest /* Write the sorted results here */
69334 ){
69335   int brk = sqlite3VdbeMakeLabel(v);
69336   int cont = sqlite3VdbeMakeLabel(v);
69337   int addr;
69338   int iTab;
69339   int pseudoTab = 0;
69340   ExprList *pOrderBy = p->pOrderBy;
69341
69342   int eDest = pDest->eDest;
69343   int iParm = pDest->iParm;
69344
69345   int regRow;
69346   int regRowid;
69347
69348   iTab = pOrderBy->iECursor;
69349   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
69350     pseudoTab = pParse->nTab++;
69351     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, nColumn);
69352     sqlite3VdbeAddOp2(v, OP_OpenPseudo, pseudoTab, eDest==SRT_Output);
69353   }
69354   addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, brk);
69355   codeOffset(v, p, cont);
69356   regRow = sqlite3GetTempReg(pParse);
69357   regRowid = sqlite3GetTempReg(pParse);
69358   sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
69359   switch( eDest ){
69360     case SRT_Table:
69361     case SRT_EphemTab: {
69362       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
69363       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
69364       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
69365       break;
69366     }
69367 #ifndef SQLITE_OMIT_SUBQUERY
69368     case SRT_Set: {
69369       assert( nColumn==1 );
69370       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
69371       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
69372       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
69373       break;
69374     }
69375     case SRT_Mem: {
69376       assert( nColumn==1 );
69377       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
69378       /* The LIMIT clause will terminate the loop for us */
69379       break;
69380     }
69381 #endif
69382     case SRT_Output:
69383     case SRT_Coroutine: {
69384       int i;
69385       sqlite3VdbeAddOp2(v, OP_Integer, 1, regRowid);
69386       sqlite3VdbeAddOp3(v, OP_Insert, pseudoTab, regRow, regRowid);
69387       for(i=0; i<nColumn; i++){
69388         assert( regRow!=pDest->iMem+i );
69389         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
69390       }
69391       if( eDest==SRT_Output ){
69392         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
69393         sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
69394       }else{
69395         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
69396       }
69397       break;
69398     }
69399     default: {
69400       /* Do nothing */
69401       break;
69402     }
69403   }
69404   sqlite3ReleaseTempReg(pParse, regRow);
69405   sqlite3ReleaseTempReg(pParse, regRowid);
69406
69407   /* LIMIT has been implemented by the pushOntoSorter() routine.
69408   */
69409   assert( p->iLimit==0 );
69410
69411   /* The bottom of the loop
69412   */
69413   sqlite3VdbeResolveLabel(v, cont);
69414   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
69415   sqlite3VdbeResolveLabel(v, brk);
69416   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
69417     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
69418   }
69419
69420 }
69421
69422 /*
69423 ** Return a pointer to a string containing the 'declaration type' of the
69424 ** expression pExpr. The string may be treated as static by the caller.
69425 **
69426 ** The declaration type is the exact datatype definition extracted from the
69427 ** original CREATE TABLE statement if the expression is a column. The
69428 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
69429 ** is considered a column can be complex in the presence of subqueries. The
69430 ** result-set expression in all of the following SELECT statements is 
69431 ** considered a column by this function.
69432 **
69433 **   SELECT col FROM tbl;
69434 **   SELECT (SELECT col FROM tbl;
69435 **   SELECT (SELECT col FROM tbl);
69436 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
69437 ** 
69438 ** The declaration type for any expression other than a column is NULL.
69439 */
69440 static const char *columnType(
69441   NameContext *pNC, 
69442   Expr *pExpr,
69443   const char **pzOriginDb,
69444   const char **pzOriginTab,
69445   const char **pzOriginCol
69446 ){
69447   char const *zType = 0;
69448   char const *zOriginDb = 0;
69449   char const *zOriginTab = 0;
69450   char const *zOriginCol = 0;
69451   int j;
69452   if( pExpr==0 || pNC->pSrcList==0 ) return 0;
69453
69454   switch( pExpr->op ){
69455     case TK_AGG_COLUMN:
69456     case TK_COLUMN: {
69457       /* The expression is a column. Locate the table the column is being
69458       ** extracted from in NameContext.pSrcList. This table may be real
69459       ** database table or a subquery.
69460       */
69461       Table *pTab = 0;            /* Table structure column is extracted from */
69462       Select *pS = 0;             /* Select the column is extracted from */
69463       int iCol = pExpr->iColumn;  /* Index of column in pTab */
69464       while( pNC && !pTab ){
69465         SrcList *pTabList = pNC->pSrcList;
69466         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
69467         if( j<pTabList->nSrc ){
69468           pTab = pTabList->a[j].pTab;
69469           pS = pTabList->a[j].pSelect;
69470         }else{
69471           pNC = pNC->pNext;
69472         }
69473       }
69474
69475       if( pTab==0 ){
69476         /* FIX ME:
69477         ** This can occurs if you have something like "SELECT new.x;" inside
69478         ** a trigger.  In other words, if you reference the special "new"
69479         ** table in the result set of a select.  We do not have a good way
69480         ** to find the actual table type, so call it "TEXT".  This is really
69481         ** something of a bug, but I do not know how to fix it.
69482         **
69483         ** This code does not produce the correct answer - it just prevents
69484         ** a segfault.  See ticket #1229.
69485         */
69486         zType = "TEXT";
69487         break;
69488       }
69489
69490       assert( pTab );
69491       if( pS ){
69492         /* The "table" is actually a sub-select or a view in the FROM clause
69493         ** of the SELECT statement. Return the declaration type and origin
69494         ** data for the result-set column of the sub-select.
69495         */
69496         if( iCol>=0 && iCol<pS->pEList->nExpr ){
69497           /* If iCol is less than zero, then the expression requests the
69498           ** rowid of the sub-select or view. This expression is legal (see 
69499           ** test case misc2.2.2) - it always evaluates to NULL.
69500           */
69501           NameContext sNC;
69502           Expr *p = pS->pEList->a[iCol].pExpr;
69503           sNC.pSrcList = pS->pSrc;
69504           sNC.pNext = 0;
69505           sNC.pParse = pNC->pParse;
69506           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
69507         }
69508       }else if( pTab->pSchema ){
69509         /* A real table */
69510         assert( !pS );
69511         if( iCol<0 ) iCol = pTab->iPKey;
69512         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
69513         if( iCol<0 ){
69514           zType = "INTEGER";
69515           zOriginCol = "rowid";
69516         }else{
69517           zType = pTab->aCol[iCol].zType;
69518           zOriginCol = pTab->aCol[iCol].zName;
69519         }
69520         zOriginTab = pTab->zName;
69521         if( pNC->pParse ){
69522           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
69523           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
69524         }
69525       }
69526       break;
69527     }
69528 #ifndef SQLITE_OMIT_SUBQUERY
69529     case TK_SELECT: {
69530       /* The expression is a sub-select. Return the declaration type and
69531       ** origin info for the single column in the result set of the SELECT
69532       ** statement.
69533       */
69534       NameContext sNC;
69535       Select *pS = pExpr->pSelect;
69536       Expr *p = pS->pEList->a[0].pExpr;
69537       sNC.pSrcList = pS->pSrc;
69538       sNC.pNext = pNC;
69539       sNC.pParse = pNC->pParse;
69540       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
69541       break;
69542     }
69543 #endif
69544   }
69545   
69546   if( pzOriginDb ){
69547     assert( pzOriginTab && pzOriginCol );
69548     *pzOriginDb = zOriginDb;
69549     *pzOriginTab = zOriginTab;
69550     *pzOriginCol = zOriginCol;
69551   }
69552   return zType;
69553 }
69554
69555 /*
69556 ** Generate code that will tell the VDBE the declaration types of columns
69557 ** in the result set.
69558 */
69559 static void generateColumnTypes(
69560   Parse *pParse,      /* Parser context */
69561   SrcList *pTabList,  /* List of tables */
69562   ExprList *pEList    /* Expressions defining the result set */
69563 ){
69564 #ifndef SQLITE_OMIT_DECLTYPE
69565   Vdbe *v = pParse->pVdbe;
69566   int i;
69567   NameContext sNC;
69568   sNC.pSrcList = pTabList;
69569   sNC.pParse = pParse;
69570   for(i=0; i<pEList->nExpr; i++){
69571     Expr *p = pEList->a[i].pExpr;
69572     const char *zType;
69573 #ifdef SQLITE_ENABLE_COLUMN_METADATA
69574     const char *zOrigDb = 0;
69575     const char *zOrigTab = 0;
69576     const char *zOrigCol = 0;
69577     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
69578
69579     /* The vdbe must make its own copy of the column-type and other 
69580     ** column specific strings, in case the schema is reset before this
69581     ** virtual machine is deleted.
69582     */
69583     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, P4_TRANSIENT);
69584     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, P4_TRANSIENT);
69585     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, P4_TRANSIENT);
69586 #else
69587     zType = columnType(&sNC, p, 0, 0, 0);
69588 #endif
69589     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, P4_TRANSIENT);
69590   }
69591 #endif /* SQLITE_OMIT_DECLTYPE */
69592 }
69593
69594 /*
69595 ** Generate code that will tell the VDBE the names of columns
69596 ** in the result set.  This information is used to provide the
69597 ** azCol[] values in the callback.
69598 */
69599 static void generateColumnNames(
69600   Parse *pParse,      /* Parser context */
69601   SrcList *pTabList,  /* List of tables */
69602   ExprList *pEList    /* Expressions defining the result set */
69603 ){
69604   Vdbe *v = pParse->pVdbe;
69605   int i, j;
69606   sqlite3 *db = pParse->db;
69607   int fullNames, shortNames;
69608
69609 #ifndef SQLITE_OMIT_EXPLAIN
69610   /* If this is an EXPLAIN, skip this step */
69611   if( pParse->explain ){
69612     return;
69613   }
69614 #endif
69615
69616   assert( v!=0 );
69617   if( pParse->colNamesSet || v==0 || db->mallocFailed ) return;
69618   pParse->colNamesSet = 1;
69619   fullNames = (db->flags & SQLITE_FullColNames)!=0;
69620   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
69621   sqlite3VdbeSetNumCols(v, pEList->nExpr);
69622   for(i=0; i<pEList->nExpr; i++){
69623     Expr *p;
69624     p = pEList->a[i].pExpr;
69625     if( p==0 ) continue;
69626     if( pEList->a[i].zName ){
69627       char *zName = pEList->a[i].zName;
69628       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, strlen(zName));
69629     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
69630       Table *pTab;
69631       char *zCol;
69632       int iCol = p->iColumn;
69633       for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
69634       assert( j<pTabList->nSrc );
69635       pTab = pTabList->a[j].pTab;
69636       if( iCol<0 ) iCol = pTab->iPKey;
69637       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
69638       if( iCol<0 ){
69639         zCol = "rowid";
69640       }else{
69641         zCol = pTab->aCol[iCol].zName;
69642       }
69643       if( !shortNames && !fullNames ){
69644         sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
69645       }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
69646         char *zName = 0;
69647         char *zTab;
69648  
69649         zTab = pTabList->a[j].zAlias;
69650         if( fullNames || zTab==0 ) zTab = pTab->zName;
69651         zName = sqlite3MPrintf(db, "%s.%s", zTab, zCol);
69652         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, P4_DYNAMIC);
69653       }else{
69654         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, strlen(zCol));
69655       }
69656     }else{
69657       sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
69658     }
69659   }
69660   generateColumnTypes(pParse, pTabList, pEList);
69661 }
69662
69663 #ifndef SQLITE_OMIT_COMPOUND_SELECT
69664 /*
69665 ** Name of the connection operator, used for error messages.
69666 */
69667 static const char *selectOpName(int id){
69668   char *z;
69669   switch( id ){
69670     case TK_ALL:       z = "UNION ALL";   break;
69671     case TK_INTERSECT: z = "INTERSECT";   break;
69672     case TK_EXCEPT:    z = "EXCEPT";      break;
69673     default:           z = "UNION";       break;
69674   }
69675   return z;
69676 }
69677 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
69678
69679 /*
69680 ** Given a an expression list (which is really the list of expressions
69681 ** that form the result set of a SELECT statement) compute appropriate
69682 ** column names for a table that would hold the expression list.
69683 **
69684 ** All column names will be unique.
69685 **
69686 ** Only the column names are computed.  Column.zType, Column.zColl,
69687 ** and other fields of Column are zeroed.
69688 **
69689 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
69690 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
69691 */
69692 static int selectColumnsFromExprList(
69693   Parse *pParse,          /* Parsing context */
69694   ExprList *pEList,       /* Expr list from which to derive column names */
69695   int *pnCol,             /* Write the number of columns here */
69696   Column **paCol          /* Write the new column list here */
69697 ){
69698   sqlite3 *db = pParse->db;
69699   int i, j, cnt;
69700   Column *aCol, *pCol;
69701   int nCol;
69702   Expr *p;
69703   char *zName;
69704   int nName;
69705
69706   *pnCol = nCol = pEList->nExpr;
69707   aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
69708   if( aCol==0 ) return SQLITE_NOMEM;
69709   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
69710     /* Get an appropriate name for the column
69711     */
69712     p = pEList->a[i].pExpr;
69713     assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
69714     if( (zName = pEList->a[i].zName)!=0 ){
69715       /* If the column contains an "AS <name>" phrase, use <name> as the name */
69716       zName = sqlite3DbStrDup(db, zName);
69717     }else{
69718       Expr *pCol = p;
69719       Table *pTab;
69720       while( pCol->op==TK_DOT ) pCol = pCol->pRight;
69721       if( pCol->op==TK_COLUMN && (pTab = pCol->pTab)!=0 ){
69722         /* For columns use the column name name */
69723         int iCol = pCol->iColumn;
69724         if( iCol<0 ) iCol = pTab->iPKey;
69725         zName = sqlite3MPrintf(db, "%s",
69726                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
69727       }else{
69728         /* Use the original text of the column expression as its name */
69729         zName = sqlite3MPrintf(db, "%T", &pCol->span);
69730       }
69731     }
69732     if( db->mallocFailed ){
69733       sqlite3DbFree(db, zName);
69734       break;
69735     }
69736     sqlite3Dequote(zName);
69737
69738     /* Make sure the column name is unique.  If the name is not unique,
69739     ** append a integer to the name so that it becomes unique.
69740     */
69741     nName = strlen(zName);
69742     for(j=cnt=0; j<i; j++){
69743       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
69744         char *zNewName;
69745         zName[nName] = 0;
69746         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
69747         sqlite3DbFree(db, zName);
69748         zName = zNewName;
69749         j = -1;
69750         if( zName==0 ) break;
69751       }
69752     }
69753     pCol->zName = zName;
69754   }
69755   if( db->mallocFailed ){
69756     int j;
69757     for(j=0; j<i; j++){
69758       sqlite3DbFree(db, aCol[j].zName);
69759     }
69760     sqlite3DbFree(db, aCol);
69761     *paCol = 0;
69762     *pnCol = 0;
69763     return SQLITE_NOMEM;
69764   }
69765   return SQLITE_OK;
69766 }
69767
69768 /*
69769 ** Add type and collation information to a column list based on
69770 ** a SELECT statement.
69771 ** 
69772 ** The column list presumably came from selectColumnNamesFromExprList().
69773 ** The column list has only names, not types or collations.  This
69774 ** routine goes through and adds the types and collations.
69775 **
69776 ** This routine requires that all indentifiers in the SELECT
69777 ** statement be resolved.
69778 */
69779 static void selectAddColumnTypeAndCollation(
69780   Parse *pParse,        /* Parsing contexts */
69781   int nCol,             /* Number of columns */
69782   Column *aCol,         /* List of columns */
69783   Select *pSelect       /* SELECT used to determine types and collations */
69784 ){
69785   sqlite3 *db = pParse->db;
69786   NameContext sNC;
69787   Column *pCol;
69788   CollSeq *pColl;
69789   int i;
69790   Expr *p;
69791   struct ExprList_item *a;
69792
69793   assert( pSelect!=0 );
69794   assert( (pSelect->selFlags & SF_Resolved)!=0 );
69795   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
69796   if( db->mallocFailed ) return;
69797   memset(&sNC, 0, sizeof(sNC));
69798   sNC.pSrcList = pSelect->pSrc;
69799   a = pSelect->pEList->a;
69800   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
69801     p = a[i].pExpr;
69802     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
69803     pCol->affinity = sqlite3ExprAffinity(p);
69804     pColl = sqlite3ExprCollSeq(pParse, p);
69805     if( pColl ){
69806       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
69807     }
69808   }
69809 }
69810
69811 /*
69812 ** Given a SELECT statement, generate a Table structure that describes
69813 ** the result set of that SELECT.
69814 */
69815 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
69816   Table *pTab;
69817   sqlite3 *db = pParse->db;
69818   int savedFlags;
69819
69820   savedFlags = db->flags;
69821   db->flags &= ~SQLITE_FullColNames;
69822   db->flags |= SQLITE_ShortColNames;
69823   sqlite3SelectPrep(pParse, pSelect, 0);
69824   if( pParse->nErr ) return 0;
69825   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
69826   db->flags = savedFlags;
69827   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
69828   if( pTab==0 ){
69829     return 0;
69830   }
69831   pTab->db = db;
69832   pTab->nRef = 1;
69833   pTab->zName = 0;
69834   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
69835   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
69836   pTab->iPKey = -1;
69837   if( db->mallocFailed ){
69838     sqlite3DeleteTable(pTab);
69839     return 0;
69840   }
69841   return pTab;
69842 }
69843
69844 /*
69845 ** Get a VDBE for the given parser context.  Create a new one if necessary.
69846 ** If an error occurs, return NULL and leave a message in pParse.
69847 */
69848 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
69849   Vdbe *v = pParse->pVdbe;
69850   if( v==0 ){
69851     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
69852 #ifndef SQLITE_OMIT_TRACE
69853     if( v ){
69854       sqlite3VdbeAddOp0(v, OP_Trace);
69855     }
69856 #endif
69857   }
69858   return v;
69859 }
69860
69861
69862 /*
69863 ** Compute the iLimit and iOffset fields of the SELECT based on the
69864 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
69865 ** that appear in the original SQL statement after the LIMIT and OFFSET
69866 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
69867 ** are the integer memory register numbers for counters used to compute 
69868 ** the limit and offset.  If there is no limit and/or offset, then 
69869 ** iLimit and iOffset are negative.
69870 **
69871 ** This routine changes the values of iLimit and iOffset only if
69872 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
69873 ** iOffset should have been preset to appropriate default values
69874 ** (usually but not always -1) prior to calling this routine.
69875 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
69876 ** redefined.  The UNION ALL operator uses this property to force
69877 ** the reuse of the same limit and offset registers across multiple
69878 ** SELECT statements.
69879 */
69880 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
69881   Vdbe *v = 0;
69882   int iLimit = 0;
69883   int iOffset;
69884   int addr1;
69885   if( p->iLimit ) return;
69886
69887   /* 
69888   ** "LIMIT -1" always shows all rows.  There is some
69889   ** contraversy about what the correct behavior should be.
69890   ** The current implementation interprets "LIMIT 0" to mean
69891   ** no rows.
69892   */
69893   if( p->pLimit ){
69894     p->iLimit = iLimit = ++pParse->nMem;
69895     v = sqlite3GetVdbe(pParse);
69896     if( v==0 ) return;
69897     sqlite3ExprCode(pParse, p->pLimit, iLimit);
69898     sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
69899     VdbeComment((v, "LIMIT counter"));
69900     sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
69901   }
69902   if( p->pOffset ){
69903     p->iOffset = iOffset = ++pParse->nMem;
69904     if( p->pLimit ){
69905       pParse->nMem++;   /* Allocate an extra register for limit+offset */
69906     }
69907     v = sqlite3GetVdbe(pParse);
69908     if( v==0 ) return;
69909     sqlite3ExprCode(pParse, p->pOffset, iOffset);
69910     sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
69911     VdbeComment((v, "OFFSET counter"));
69912     addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
69913     sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
69914     sqlite3VdbeJumpHere(v, addr1);
69915     if( p->pLimit ){
69916       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
69917       VdbeComment((v, "LIMIT+OFFSET"));
69918       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
69919       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
69920       sqlite3VdbeJumpHere(v, addr1);
69921     }
69922   }
69923 }
69924
69925 #ifndef SQLITE_OMIT_COMPOUND_SELECT
69926 /*
69927 ** Return the appropriate collating sequence for the iCol-th column of
69928 ** the result set for the compound-select statement "p".  Return NULL if
69929 ** the column has no default collating sequence.
69930 **
69931 ** The collating sequence for the compound select is taken from the
69932 ** left-most term of the select that has a collating sequence.
69933 */
69934 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
69935   CollSeq *pRet;
69936   if( p->pPrior ){
69937     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
69938   }else{
69939     pRet = 0;
69940   }
69941   if( pRet==0 ){
69942     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
69943   }
69944   return pRet;
69945 }
69946 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
69947
69948 /* Forward reference */
69949 static int multiSelectOrderBy(
69950   Parse *pParse,        /* Parsing context */
69951   Select *p,            /* The right-most of SELECTs to be coded */
69952   SelectDest *pDest     /* What to do with query results */
69953 );
69954
69955
69956 #ifndef SQLITE_OMIT_COMPOUND_SELECT
69957 /*
69958 ** This routine is called to process a compound query form from
69959 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
69960 ** INTERSECT
69961 **
69962 ** "p" points to the right-most of the two queries.  the query on the
69963 ** left is p->pPrior.  The left query could also be a compound query
69964 ** in which case this routine will be called recursively. 
69965 **
69966 ** The results of the total query are to be written into a destination
69967 ** of type eDest with parameter iParm.
69968 **
69969 ** Example 1:  Consider a three-way compound SQL statement.
69970 **
69971 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
69972 **
69973 ** This statement is parsed up as follows:
69974 **
69975 **     SELECT c FROM t3
69976 **      |
69977 **      `----->  SELECT b FROM t2
69978 **                |
69979 **                `------>  SELECT a FROM t1
69980 **
69981 ** The arrows in the diagram above represent the Select.pPrior pointer.
69982 ** So if this routine is called with p equal to the t3 query, then
69983 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
69984 **
69985 ** Notice that because of the way SQLite parses compound SELECTs, the
69986 ** individual selects always group from left to right.
69987 */
69988 static int multiSelect(
69989   Parse *pParse,        /* Parsing context */
69990   Select *p,            /* The right-most of SELECTs to be coded */
69991   SelectDest *pDest     /* What to do with query results */
69992 ){
69993   int rc = SQLITE_OK;   /* Success code from a subroutine */
69994   Select *pPrior;       /* Another SELECT immediately to our left */
69995   Vdbe *v;              /* Generate code to this VDBE */
69996   SelectDest dest;      /* Alternative data destination */
69997   Select *pDelete = 0;  /* Chain of simple selects to delete */
69998   sqlite3 *db;          /* Database connection */
69999
70000   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
70001   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
70002   */
70003   assert( p && p->pPrior );  /* Calling function guarantees this much */
70004   db = pParse->db;
70005   pPrior = p->pPrior;
70006   assert( pPrior->pRightmost!=pPrior );
70007   assert( pPrior->pRightmost==p->pRightmost );
70008   dest = *pDest;
70009   if( pPrior->pOrderBy ){
70010     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
70011       selectOpName(p->op));
70012     rc = 1;
70013     goto multi_select_end;
70014   }
70015   if( pPrior->pLimit ){
70016     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
70017       selectOpName(p->op));
70018     rc = 1;
70019     goto multi_select_end;
70020   }
70021
70022   v = sqlite3GetVdbe(pParse);
70023   assert( v!=0 );  /* The VDBE already created by calling function */
70024
70025   /* Create the destination temporary table if necessary
70026   */
70027   if( dest.eDest==SRT_EphemTab ){
70028     assert( p->pEList );
70029     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
70030     dest.eDest = SRT_Table;
70031   }
70032
70033   /* Make sure all SELECTs in the statement have the same number of elements
70034   ** in their result sets.
70035   */
70036   assert( p->pEList && pPrior->pEList );
70037   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
70038     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
70039       " do not have the same number of result columns", selectOpName(p->op));
70040     rc = 1;
70041     goto multi_select_end;
70042   }
70043
70044   /* Compound SELECTs that have an ORDER BY clause are handled separately.
70045   */
70046   if( p->pOrderBy ){
70047     return multiSelectOrderBy(pParse, p, pDest);
70048   }
70049
70050   /* Generate code for the left and right SELECT statements.
70051   */
70052   switch( p->op ){
70053     case TK_ALL: {
70054       int addr = 0;
70055       assert( !pPrior->pLimit );
70056       pPrior->pLimit = p->pLimit;
70057       pPrior->pOffset = p->pOffset;
70058       rc = sqlite3Select(pParse, pPrior, &dest);
70059       p->pLimit = 0;
70060       p->pOffset = 0;
70061       if( rc ){
70062         goto multi_select_end;
70063       }
70064       p->pPrior = 0;
70065       p->iLimit = pPrior->iLimit;
70066       p->iOffset = pPrior->iOffset;
70067       if( p->iLimit ){
70068         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
70069         VdbeComment((v, "Jump ahead if LIMIT reached"));
70070       }
70071       rc = sqlite3Select(pParse, p, &dest);
70072       pDelete = p->pPrior;
70073       p->pPrior = pPrior;
70074       if( rc ){
70075         goto multi_select_end;
70076       }
70077       if( addr ){
70078         sqlite3VdbeJumpHere(v, addr);
70079       }
70080       break;
70081     }
70082     case TK_EXCEPT:
70083     case TK_UNION: {
70084       int unionTab;    /* Cursor number of the temporary table holding result */
70085       int op = 0;      /* One of the SRT_ operations to apply to self */
70086       int priorOp;     /* The SRT_ operation to apply to prior selects */
70087       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
70088       int addr;
70089       SelectDest uniondest;
70090
70091       priorOp = SRT_Union;
70092       if( dest.eDest==priorOp && !p->pLimit && !p->pOffset ){
70093         /* We can reuse a temporary table generated by a SELECT to our
70094         ** right.
70095         */
70096         unionTab = dest.iParm;
70097       }else{
70098         /* We will need to create our own temporary table to hold the
70099         ** intermediate results.
70100         */
70101         unionTab = pParse->nTab++;
70102         assert( p->pOrderBy==0 );
70103         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
70104         assert( p->addrOpenEphm[0] == -1 );
70105         p->addrOpenEphm[0] = addr;
70106         p->pRightmost->selFlags |= SF_UsesEphemeral;
70107         assert( p->pEList );
70108       }
70109
70110       /* Code the SELECT statements to our left
70111       */
70112       assert( !pPrior->pOrderBy );
70113       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
70114       rc = sqlite3Select(pParse, pPrior, &uniondest);
70115       if( rc ){
70116         goto multi_select_end;
70117       }
70118
70119       /* Code the current SELECT statement
70120       */
70121       if( p->op==TK_EXCEPT ){
70122         op = SRT_Except;
70123       }else{
70124         assert( p->op==TK_UNION );
70125         op = SRT_Union;
70126       }
70127       p->pPrior = 0;
70128       pLimit = p->pLimit;
70129       p->pLimit = 0;
70130       pOffset = p->pOffset;
70131       p->pOffset = 0;
70132       uniondest.eDest = op;
70133       rc = sqlite3Select(pParse, p, &uniondest);
70134       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
70135       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
70136       sqlite3ExprListDelete(db, p->pOrderBy);
70137       pDelete = p->pPrior;
70138       p->pPrior = pPrior;
70139       p->pOrderBy = 0;
70140       sqlite3ExprDelete(db, p->pLimit);
70141       p->pLimit = pLimit;
70142       p->pOffset = pOffset;
70143       p->iLimit = 0;
70144       p->iOffset = 0;
70145       if( rc ){
70146         goto multi_select_end;
70147       }
70148
70149
70150       /* Convert the data in the temporary table into whatever form
70151       ** it is that we currently need.
70152       */      
70153       if( dest.eDest!=priorOp || unionTab!=dest.iParm ){
70154         int iCont, iBreak, iStart;
70155         assert( p->pEList );
70156         if( dest.eDest==SRT_Output ){
70157           Select *pFirst = p;
70158           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
70159           generateColumnNames(pParse, 0, pFirst->pEList);
70160         }
70161         iBreak = sqlite3VdbeMakeLabel(v);
70162         iCont = sqlite3VdbeMakeLabel(v);
70163         computeLimitRegisters(pParse, p, iBreak);
70164         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
70165         iStart = sqlite3VdbeCurrentAddr(v);
70166         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
70167                         0, -1, &dest, iCont, iBreak);
70168         sqlite3VdbeResolveLabel(v, iCont);
70169         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
70170         sqlite3VdbeResolveLabel(v, iBreak);
70171         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
70172       }
70173       break;
70174     }
70175     case TK_INTERSECT: {
70176       int tab1, tab2;
70177       int iCont, iBreak, iStart;
70178       Expr *pLimit, *pOffset;
70179       int addr;
70180       SelectDest intersectdest;
70181       int r1;
70182
70183       /* INTERSECT is different from the others since it requires
70184       ** two temporary tables.  Hence it has its own case.  Begin
70185       ** by allocating the tables we will need.
70186       */
70187       tab1 = pParse->nTab++;
70188       tab2 = pParse->nTab++;
70189       assert( p->pOrderBy==0 );
70190
70191       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
70192       assert( p->addrOpenEphm[0] == -1 );
70193       p->addrOpenEphm[0] = addr;
70194       p->pRightmost->selFlags |= SF_UsesEphemeral;
70195       assert( p->pEList );
70196
70197       /* Code the SELECTs to our left into temporary table "tab1".
70198       */
70199       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
70200       rc = sqlite3Select(pParse, pPrior, &intersectdest);
70201       if( rc ){
70202         goto multi_select_end;
70203       }
70204
70205       /* Code the current SELECT into temporary table "tab2"
70206       */
70207       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
70208       assert( p->addrOpenEphm[1] == -1 );
70209       p->addrOpenEphm[1] = addr;
70210       p->pPrior = 0;
70211       pLimit = p->pLimit;
70212       p->pLimit = 0;
70213       pOffset = p->pOffset;
70214       p->pOffset = 0;
70215       intersectdest.iParm = tab2;
70216       rc = sqlite3Select(pParse, p, &intersectdest);
70217       pDelete = p->pPrior;
70218       p->pPrior = pPrior;
70219       sqlite3ExprDelete(db, p->pLimit);
70220       p->pLimit = pLimit;
70221       p->pOffset = pOffset;
70222       if( rc ){
70223         goto multi_select_end;
70224       }
70225
70226       /* Generate code to take the intersection of the two temporary
70227       ** tables.
70228       */
70229       assert( p->pEList );
70230       if( dest.eDest==SRT_Output ){
70231         Select *pFirst = p;
70232         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
70233         generateColumnNames(pParse, 0, pFirst->pEList);
70234       }
70235       iBreak = sqlite3VdbeMakeLabel(v);
70236       iCont = sqlite3VdbeMakeLabel(v);
70237       computeLimitRegisters(pParse, p, iBreak);
70238       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
70239       r1 = sqlite3GetTempReg(pParse);
70240       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
70241       sqlite3VdbeAddOp3(v, OP_NotFound, tab2, iCont, r1);
70242       sqlite3ReleaseTempReg(pParse, r1);
70243       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
70244                       0, -1, &dest, iCont, iBreak);
70245       sqlite3VdbeResolveLabel(v, iCont);
70246       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
70247       sqlite3VdbeResolveLabel(v, iBreak);
70248       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
70249       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
70250       break;
70251     }
70252   }
70253
70254   /* Compute collating sequences used by 
70255   ** temporary tables needed to implement the compound select.
70256   ** Attach the KeyInfo structure to all temporary tables.
70257   **
70258   ** This section is run by the right-most SELECT statement only.
70259   ** SELECT statements to the left always skip this part.  The right-most
70260   ** SELECT might also skip this part if it has no ORDER BY clause and
70261   ** no temp tables are required.
70262   */
70263   if( p->selFlags & SF_UsesEphemeral ){
70264     int i;                        /* Loop counter */
70265     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
70266     Select *pLoop;                /* For looping through SELECT statements */
70267     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
70268     int nCol;                     /* Number of columns in result set */
70269
70270     assert( p->pRightmost==p );
70271     nCol = p->pEList->nExpr;
70272     pKeyInfo = sqlite3DbMallocZero(db,
70273                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
70274     if( !pKeyInfo ){
70275       rc = SQLITE_NOMEM;
70276       goto multi_select_end;
70277     }
70278
70279     pKeyInfo->enc = ENC(db);
70280     pKeyInfo->nField = nCol;
70281
70282     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
70283       *apColl = multiSelectCollSeq(pParse, p, i);
70284       if( 0==*apColl ){
70285         *apColl = db->pDfltColl;
70286       }
70287     }
70288
70289     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
70290       for(i=0; i<2; i++){
70291         int addr = pLoop->addrOpenEphm[i];
70292         if( addr<0 ){
70293           /* If [0] is unused then [1] is also unused.  So we can
70294           ** always safely abort as soon as the first unused slot is found */
70295           assert( pLoop->addrOpenEphm[1]<0 );
70296           break;
70297         }
70298         sqlite3VdbeChangeP2(v, addr, nCol);
70299         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
70300         pLoop->addrOpenEphm[i] = -1;
70301       }
70302     }
70303     sqlite3DbFree(db, pKeyInfo);
70304   }
70305
70306 multi_select_end:
70307   pDest->iMem = dest.iMem;
70308   pDest->nMem = dest.nMem;
70309   sqlite3SelectDelete(db, pDelete);
70310   return rc;
70311 }
70312 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
70313
70314 /*
70315 ** Code an output subroutine for a coroutine implementation of a
70316 ** SELECT statment.
70317 **
70318 ** The data to be output is contained in pIn->iMem.  There are
70319 ** pIn->nMem columns to be output.  pDest is where the output should
70320 ** be sent.
70321 **
70322 ** regReturn is the number of the register holding the subroutine
70323 ** return address.
70324 **
70325 ** If regPrev>0 then it is a the first register in a vector that
70326 ** records the previous output.  mem[regPrev] is a flag that is false
70327 ** if there has been no previous output.  If regPrev>0 then code is
70328 ** generated to suppress duplicates.  pKeyInfo is used for comparing
70329 ** keys.
70330 **
70331 ** If the LIMIT found in p->iLimit is reached, jump immediately to
70332 ** iBreak.
70333 */
70334 static int generateOutputSubroutine(
70335   Parse *pParse,          /* Parsing context */
70336   Select *p,              /* The SELECT statement */
70337   SelectDest *pIn,        /* Coroutine supplying data */
70338   SelectDest *pDest,      /* Where to send the data */
70339   int regReturn,          /* The return address register */
70340   int regPrev,            /* Previous result register.  No uniqueness if 0 */
70341   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
70342   int p4type,             /* The p4 type for pKeyInfo */
70343   int iBreak              /* Jump here if we hit the LIMIT */
70344 ){
70345   Vdbe *v = pParse->pVdbe;
70346   int iContinue;
70347   int addr;
70348
70349   addr = sqlite3VdbeCurrentAddr(v);
70350   iContinue = sqlite3VdbeMakeLabel(v);
70351
70352   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
70353   */
70354   if( regPrev ){
70355     int j1, j2;
70356     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
70357     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
70358                               (char*)pKeyInfo, p4type);
70359     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
70360     sqlite3VdbeJumpHere(v, j1);
70361     sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
70362     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
70363   }
70364   if( pParse->db->mallocFailed ) return 0;
70365
70366   /* Suppress the the first OFFSET entries if there is an OFFSET clause
70367   */
70368   codeOffset(v, p, iContinue);
70369
70370   switch( pDest->eDest ){
70371     /* Store the result as data using a unique key.
70372     */
70373     case SRT_Table:
70374     case SRT_EphemTab: {
70375       int r1 = sqlite3GetTempReg(pParse);
70376       int r2 = sqlite3GetTempReg(pParse);
70377       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
70378       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
70379       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
70380       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
70381       sqlite3ReleaseTempReg(pParse, r2);
70382       sqlite3ReleaseTempReg(pParse, r1);
70383       break;
70384     }
70385
70386 #ifndef SQLITE_OMIT_SUBQUERY
70387     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
70388     ** then there should be a single item on the stack.  Write this
70389     ** item into the set table with bogus data.
70390     */
70391     case SRT_Set: {
70392       int r1;
70393       assert( pIn->nMem==1 );
70394       p->affinity = 
70395          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
70396       r1 = sqlite3GetTempReg(pParse);
70397       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
70398       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
70399       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
70400       sqlite3ReleaseTempReg(pParse, r1);
70401       break;
70402     }
70403
70404 #if 0  /* Never occurs on an ORDER BY query */
70405     /* If any row exist in the result set, record that fact and abort.
70406     */
70407     case SRT_Exists: {
70408       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
70409       /* The LIMIT clause will terminate the loop for us */
70410       break;
70411     }
70412 #endif
70413
70414     /* If this is a scalar select that is part of an expression, then
70415     ** store the results in the appropriate memory cell and break out
70416     ** of the scan loop.
70417     */
70418     case SRT_Mem: {
70419       assert( pIn->nMem==1 );
70420       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
70421       /* The LIMIT clause will jump out of the loop for us */
70422       break;
70423     }
70424 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
70425
70426     /* The results are stored in a sequence of registers
70427     ** starting at pDest->iMem.  Then the co-routine yields.
70428     */
70429     case SRT_Coroutine: {
70430       if( pDest->iMem==0 ){
70431         pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
70432         pDest->nMem = pIn->nMem;
70433       }
70434       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
70435       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
70436       break;
70437     }
70438
70439     /* Results are stored in a sequence of registers.  Then the
70440     ** OP_ResultRow opcode is used to cause sqlite3_step() to return
70441     ** the next row of result.
70442     */
70443     case SRT_Output: {
70444       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
70445       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
70446       break;
70447     }
70448
70449 #if !defined(SQLITE_OMIT_TRIGGER)
70450     /* Discard the results.  This is used for SELECT statements inside
70451     ** the body of a TRIGGER.  The purpose of such selects is to call
70452     ** user-defined functions that have side effects.  We do not care
70453     ** about the actual results of the select.
70454     */
70455     default: {
70456       break;
70457     }
70458 #endif
70459   }
70460
70461   /* Jump to the end of the loop if the LIMIT is reached.
70462   */
70463   if( p->iLimit ){
70464     sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
70465     sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak);
70466   }
70467
70468   /* Generate the subroutine return
70469   */
70470   sqlite3VdbeResolveLabel(v, iContinue);
70471   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
70472
70473   return addr;
70474 }
70475
70476 /*
70477 ** Alternative compound select code generator for cases when there
70478 ** is an ORDER BY clause.
70479 **
70480 ** We assume a query of the following form:
70481 **
70482 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
70483 **
70484 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
70485 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
70486 ** co-routines.  Then run the co-routines in parallel and merge the results
70487 ** into the output.  In addition to the two coroutines (called selectA and
70488 ** selectB) there are 7 subroutines:
70489 **
70490 **    outA:    Move the output of the selectA coroutine into the output
70491 **             of the compound query.
70492 **
70493 **    outB:    Move the output of the selectB coroutine into the output
70494 **             of the compound query.  (Only generated for UNION and
70495 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
70496 **             appears only in B.)
70497 **
70498 **    AltB:    Called when there is data from both coroutines and A<B.
70499 **
70500 **    AeqB:    Called when there is data from both coroutines and A==B.
70501 **
70502 **    AgtB:    Called when there is data from both coroutines and A>B.
70503 **
70504 **    EofA:    Called when data is exhausted from selectA.
70505 **
70506 **    EofB:    Called when data is exhausted from selectB.
70507 **
70508 ** The implementation of the latter five subroutines depend on which 
70509 ** <operator> is used:
70510 **
70511 **
70512 **             UNION ALL         UNION            EXCEPT          INTERSECT
70513 **          -------------  -----------------  --------------  -----------------
70514 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
70515 **
70516 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
70517 **
70518 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
70519 **
70520 **   EofA:   outB, nextB      outB, nextB          halt             halt
70521 **
70522 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
70523 **
70524 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
70525 ** causes an immediate jump to EofA and an EOF on B following nextB causes
70526 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
70527 ** following nextX causes a jump to the end of the select processing.
70528 **
70529 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
70530 ** within the output subroutine.  The regPrev register set holds the previously
70531 ** output value.  A comparison is made against this value and the output
70532 ** is skipped if the next results would be the same as the previous.
70533 **
70534 ** The implementation plan is to implement the two coroutines and seven
70535 ** subroutines first, then put the control logic at the bottom.  Like this:
70536 **
70537 **          goto Init
70538 **     coA: coroutine for left query (A)
70539 **     coB: coroutine for right query (B)
70540 **    outA: output one row of A
70541 **    outB: output one row of B (UNION and UNION ALL only)
70542 **    EofA: ...
70543 **    EofB: ...
70544 **    AltB: ...
70545 **    AeqB: ...
70546 **    AgtB: ...
70547 **    Init: initialize coroutine registers
70548 **          yield coA
70549 **          if eof(A) goto EofA
70550 **          yield coB
70551 **          if eof(B) goto EofB
70552 **    Cmpr: Compare A, B
70553 **          Jump AltB, AeqB, AgtB
70554 **     End: ...
70555 **
70556 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
70557 ** actually called using Gosub and they do not Return.  EofA and EofB loop
70558 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
70559 ** and AgtB jump to either L2 or to one of EofA or EofB.
70560 */
70561 #ifndef SQLITE_OMIT_COMPOUND_SELECT
70562 static int multiSelectOrderBy(
70563   Parse *pParse,        /* Parsing context */
70564   Select *p,            /* The right-most of SELECTs to be coded */
70565   SelectDest *pDest     /* What to do with query results */
70566 ){
70567   int i, j;             /* Loop counters */
70568   Select *pPrior;       /* Another SELECT immediately to our left */
70569   Vdbe *v;              /* Generate code to this VDBE */
70570   SelectDest destA;     /* Destination for coroutine A */
70571   SelectDest destB;     /* Destination for coroutine B */
70572   int regAddrA;         /* Address register for select-A coroutine */
70573   int regEofA;          /* Flag to indicate when select-A is complete */
70574   int regAddrB;         /* Address register for select-B coroutine */
70575   int regEofB;          /* Flag to indicate when select-B is complete */
70576   int addrSelectA;      /* Address of the select-A coroutine */
70577   int addrSelectB;      /* Address of the select-B coroutine */
70578   int regOutA;          /* Address register for the output-A subroutine */
70579   int regOutB;          /* Address register for the output-B subroutine */
70580   int addrOutA;         /* Address of the output-A subroutine */
70581   int addrOutB;         /* Address of the output-B subroutine */
70582   int addrEofA;         /* Address of the select-A-exhausted subroutine */
70583   int addrEofB;         /* Address of the select-B-exhausted subroutine */
70584   int addrAltB;         /* Address of the A<B subroutine */
70585   int addrAeqB;         /* Address of the A==B subroutine */
70586   int addrAgtB;         /* Address of the A>B subroutine */
70587   int regLimitA;        /* Limit register for select-A */
70588   int regLimitB;        /* Limit register for select-A */
70589   int regPrev;          /* A range of registers to hold previous output */
70590   int savedLimit;       /* Saved value of p->iLimit */
70591   int savedOffset;      /* Saved value of p->iOffset */
70592   int labelCmpr;        /* Label for the start of the merge algorithm */
70593   int labelEnd;         /* Label for the end of the overall SELECT stmt */
70594   int j1;               /* Jump instructions that get retargetted */
70595   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
70596   KeyInfo *pKeyDup;     /* Comparison information for duplicate removal */
70597   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
70598   sqlite3 *db;          /* Database connection */
70599   ExprList *pOrderBy;   /* The ORDER BY clause */
70600   int nOrderBy;         /* Number of terms in the ORDER BY clause */
70601   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
70602
70603   assert( p->pOrderBy!=0 );
70604   db = pParse->db;
70605   v = pParse->pVdbe;
70606   if( v==0 ) return SQLITE_NOMEM;
70607   labelEnd = sqlite3VdbeMakeLabel(v);
70608   labelCmpr = sqlite3VdbeMakeLabel(v);
70609
70610
70611   /* Patch up the ORDER BY clause
70612   */
70613   op = p->op;  
70614   pPrior = p->pPrior;
70615   assert( pPrior->pOrderBy==0 );
70616   pOrderBy = p->pOrderBy;
70617   assert( pOrderBy );
70618   nOrderBy = pOrderBy->nExpr;
70619
70620   /* For operators other than UNION ALL we have to make sure that
70621   ** the ORDER BY clause covers every term of the result set.  Add
70622   ** terms to the ORDER BY clause as necessary.
70623   */
70624   if( op!=TK_ALL ){
70625     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
70626       struct ExprList_item *pItem;
70627       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
70628         assert( pItem->iCol>0 );
70629         if( pItem->iCol==i ) break;
70630       }
70631       if( j==nOrderBy ){
70632         Expr *pNew = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, 0);
70633         if( pNew==0 ) return SQLITE_NOMEM;
70634         pNew->flags |= EP_IntValue;
70635         pNew->iTable = i;
70636         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew, 0);
70637         pOrderBy->a[nOrderBy++].iCol = i;
70638       }
70639     }
70640   }
70641
70642   /* Compute the comparison permutation and keyinfo that is used with
70643   ** the permutation in order to comparisons to determine if the next
70644   ** row of results comes from selectA or selectB.  Also add explicit
70645   ** collations to the ORDER BY clause terms so that when the subqueries
70646   ** to the right and the left are evaluated, they use the correct
70647   ** collation.
70648   */
70649   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
70650   if( aPermute ){
70651     struct ExprList_item *pItem;
70652     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
70653       assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
70654       aPermute[i] = pItem->iCol - 1;
70655     }
70656     pKeyMerge =
70657       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
70658     if( pKeyMerge ){
70659       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
70660       pKeyMerge->nField = nOrderBy;
70661       pKeyMerge->enc = ENC(db);
70662       for(i=0; i<nOrderBy; i++){
70663         CollSeq *pColl;
70664         Expr *pTerm = pOrderBy->a[i].pExpr;
70665         if( pTerm->flags & EP_ExpCollate ){
70666           pColl = pTerm->pColl;
70667         }else{
70668           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
70669           pTerm->flags |= EP_ExpCollate;
70670           pTerm->pColl = pColl;
70671         }
70672         pKeyMerge->aColl[i] = pColl;
70673         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
70674       }
70675     }
70676   }else{
70677     pKeyMerge = 0;
70678   }
70679
70680   /* Reattach the ORDER BY clause to the query.
70681   */
70682   p->pOrderBy = pOrderBy;
70683   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy);
70684
70685   /* Allocate a range of temporary registers and the KeyInfo needed
70686   ** for the logic that removes duplicate result rows when the
70687   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
70688   */
70689   if( op==TK_ALL ){
70690     regPrev = 0;
70691   }else{
70692     int nExpr = p->pEList->nExpr;
70693     assert( nOrderBy>=nExpr );
70694     regPrev = sqlite3GetTempRange(pParse, nExpr+1);
70695     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
70696     pKeyDup = sqlite3DbMallocZero(db,
70697                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
70698     if( pKeyDup ){
70699       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
70700       pKeyDup->nField = nExpr;
70701       pKeyDup->enc = ENC(db);
70702       for(i=0; i<nExpr; i++){
70703         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
70704         pKeyDup->aSortOrder[i] = 0;
70705       }
70706     }
70707   }
70708  
70709   /* Separate the left and the right query from one another
70710   */
70711   p->pPrior = 0;
70712   pPrior->pRightmost = 0;
70713   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
70714   if( pPrior->pPrior==0 ){
70715     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
70716   }
70717
70718   /* Compute the limit registers */
70719   computeLimitRegisters(pParse, p, labelEnd);
70720   if( p->iLimit && op==TK_ALL ){
70721     regLimitA = ++pParse->nMem;
70722     regLimitB = ++pParse->nMem;
70723     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
70724                                   regLimitA);
70725     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
70726   }else{
70727     regLimitA = regLimitB = 0;
70728   }
70729   sqlite3ExprDelete(db, p->pLimit);
70730   p->pLimit = 0;
70731   sqlite3ExprDelete(db, p->pOffset);
70732   p->pOffset = 0;
70733
70734   regAddrA = ++pParse->nMem;
70735   regEofA = ++pParse->nMem;
70736   regAddrB = ++pParse->nMem;
70737   regEofB = ++pParse->nMem;
70738   regOutA = ++pParse->nMem;
70739   regOutB = ++pParse->nMem;
70740   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
70741   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
70742
70743   /* Jump past the various subroutines and coroutines to the main
70744   ** merge loop
70745   */
70746   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
70747   addrSelectA = sqlite3VdbeCurrentAddr(v);
70748
70749
70750   /* Generate a coroutine to evaluate the SELECT statement to the
70751   ** left of the compound operator - the "A" select.
70752   */
70753   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
70754   pPrior->iLimit = regLimitA;
70755   sqlite3Select(pParse, pPrior, &destA);
70756   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
70757   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
70758   VdbeNoopComment((v, "End coroutine for left SELECT"));
70759
70760   /* Generate a coroutine to evaluate the SELECT statement on 
70761   ** the right - the "B" select
70762   */
70763   addrSelectB = sqlite3VdbeCurrentAddr(v);
70764   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
70765   savedLimit = p->iLimit;
70766   savedOffset = p->iOffset;
70767   p->iLimit = regLimitB;
70768   p->iOffset = 0;  
70769   sqlite3Select(pParse, p, &destB);
70770   p->iLimit = savedLimit;
70771   p->iOffset = savedOffset;
70772   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
70773   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
70774   VdbeNoopComment((v, "End coroutine for right SELECT"));
70775
70776   /* Generate a subroutine that outputs the current row of the A
70777   ** select as the next output row of the compound select.
70778   */
70779   VdbeNoopComment((v, "Output routine for A"));
70780   addrOutA = generateOutputSubroutine(pParse,
70781                  p, &destA, pDest, regOutA,
70782                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
70783   
70784   /* Generate a subroutine that outputs the current row of the B
70785   ** select as the next output row of the compound select.
70786   */
70787   if( op==TK_ALL || op==TK_UNION ){
70788     VdbeNoopComment((v, "Output routine for B"));
70789     addrOutB = generateOutputSubroutine(pParse,
70790                  p, &destB, pDest, regOutB,
70791                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
70792   }
70793
70794   /* Generate a subroutine to run when the results from select A
70795   ** are exhausted and only data in select B remains.
70796   */
70797   VdbeNoopComment((v, "eof-A subroutine"));
70798   if( op==TK_EXCEPT || op==TK_INTERSECT ){
70799     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
70800   }else{  
70801     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
70802     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
70803     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
70804     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
70805   }
70806
70807   /* Generate a subroutine to run when the results from select B
70808   ** are exhausted and only data in select A remains.
70809   */
70810   if( op==TK_INTERSECT ){
70811     addrEofB = addrEofA;
70812   }else{  
70813     VdbeNoopComment((v, "eof-B subroutine"));
70814     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
70815     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
70816     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
70817     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
70818   }
70819
70820   /* Generate code to handle the case of A<B
70821   */
70822   VdbeNoopComment((v, "A-lt-B subroutine"));
70823   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
70824   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
70825   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
70826   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
70827
70828   /* Generate code to handle the case of A==B
70829   */
70830   if( op==TK_ALL ){
70831     addrAeqB = addrAltB;
70832   }else if( op==TK_INTERSECT ){
70833     addrAeqB = addrAltB;
70834     addrAltB++;
70835   }else{
70836     VdbeNoopComment((v, "A-eq-B subroutine"));
70837     addrAeqB =
70838     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
70839     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
70840     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
70841   }
70842
70843   /* Generate code to handle the case of A>B
70844   */
70845   VdbeNoopComment((v, "A-gt-B subroutine"));
70846   addrAgtB = sqlite3VdbeCurrentAddr(v);
70847   if( op==TK_ALL || op==TK_UNION ){
70848     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
70849   }
70850   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
70851   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
70852   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
70853
70854   /* This code runs once to initialize everything.
70855   */
70856   sqlite3VdbeJumpHere(v, j1);
70857   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
70858   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
70859   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
70860   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
70861   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
70862   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
70863
70864   /* Implement the main merge loop
70865   */
70866   sqlite3VdbeResolveLabel(v, labelCmpr);
70867   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
70868   sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
70869                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
70870   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
70871
70872   /* Release temporary registers
70873   */
70874   if( regPrev ){
70875     sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
70876   }
70877
70878   /* Jump to the this point in order to terminate the query.
70879   */
70880   sqlite3VdbeResolveLabel(v, labelEnd);
70881
70882   /* Set the number of output columns
70883   */
70884   if( pDest->eDest==SRT_Output ){
70885     Select *pFirst = pPrior;
70886     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
70887     generateColumnNames(pParse, 0, pFirst->pEList);
70888   }
70889
70890   /* Reassembly the compound query so that it will be freed correctly
70891   ** by the calling function */
70892   if( p->pPrior ){
70893     sqlite3SelectDelete(db, p->pPrior);
70894   }
70895   p->pPrior = pPrior;
70896
70897   /*** TBD:  Insert subroutine calls to close cursors on incomplete
70898   **** subqueries ****/
70899   return SQLITE_OK;
70900 }
70901 #endif
70902
70903 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
70904 /* Forward Declarations */
70905 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
70906 static void substSelect(sqlite3*, Select *, int, ExprList *);
70907
70908 /*
70909 ** Scan through the expression pExpr.  Replace every reference to
70910 ** a column in table number iTable with a copy of the iColumn-th
70911 ** entry in pEList.  (But leave references to the ROWID column 
70912 ** unchanged.)
70913 **
70914 ** This routine is part of the flattening procedure.  A subquery
70915 ** whose result set is defined by pEList appears as entry in the
70916 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
70917 ** FORM clause entry is iTable.  This routine make the necessary 
70918 ** changes to pExpr so that it refers directly to the source table
70919 ** of the subquery rather the result set of the subquery.
70920 */
70921 static void substExpr(
70922   sqlite3 *db,        /* Report malloc errors to this connection */
70923   Expr *pExpr,        /* Expr in which substitution occurs */
70924   int iTable,         /* Table to be substituted */
70925   ExprList *pEList    /* Substitute expressions */
70926 ){
70927   if( pExpr==0 ) return;
70928   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
70929     if( pExpr->iColumn<0 ){
70930       pExpr->op = TK_NULL;
70931     }else{
70932       Expr *pNew;
70933       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
70934       assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
70935       pNew = pEList->a[pExpr->iColumn].pExpr;
70936       assert( pNew!=0 );
70937       pExpr->op = pNew->op;
70938       assert( pExpr->pLeft==0 );
70939       pExpr->pLeft = sqlite3ExprDup(db, pNew->pLeft);
70940       assert( pExpr->pRight==0 );
70941       pExpr->pRight = sqlite3ExprDup(db, pNew->pRight);
70942       assert( pExpr->pList==0 );
70943       pExpr->pList = sqlite3ExprListDup(db, pNew->pList);
70944       pExpr->iTable = pNew->iTable;
70945       pExpr->pTab = pNew->pTab;
70946       pExpr->iColumn = pNew->iColumn;
70947       pExpr->iAgg = pNew->iAgg;
70948       sqlite3TokenCopy(db, &pExpr->token, &pNew->token);
70949       sqlite3TokenCopy(db, &pExpr->span, &pNew->span);
70950       pExpr->pSelect = sqlite3SelectDup(db, pNew->pSelect);
70951       pExpr->flags = pNew->flags;
70952     }
70953   }else{
70954     substExpr(db, pExpr->pLeft, iTable, pEList);
70955     substExpr(db, pExpr->pRight, iTable, pEList);
70956     substSelect(db, pExpr->pSelect, iTable, pEList);
70957     substExprList(db, pExpr->pList, iTable, pEList);
70958   }
70959 }
70960 static void substExprList(
70961   sqlite3 *db,         /* Report malloc errors here */
70962   ExprList *pList,     /* List to scan and in which to make substitutes */
70963   int iTable,          /* Table to be substituted */
70964   ExprList *pEList     /* Substitute values */
70965 ){
70966   int i;
70967   if( pList==0 ) return;
70968   for(i=0; i<pList->nExpr; i++){
70969     substExpr(db, pList->a[i].pExpr, iTable, pEList);
70970   }
70971 }
70972 static void substSelect(
70973   sqlite3 *db,         /* Report malloc errors here */
70974   Select *p,           /* SELECT statement in which to make substitutions */
70975   int iTable,          /* Table to be replaced */
70976   ExprList *pEList     /* Substitute values */
70977 ){
70978   SrcList *pSrc;
70979   struct SrcList_item *pItem;
70980   int i;
70981   if( !p ) return;
70982   substExprList(db, p->pEList, iTable, pEList);
70983   substExprList(db, p->pGroupBy, iTable, pEList);
70984   substExprList(db, p->pOrderBy, iTable, pEList);
70985   substExpr(db, p->pHaving, iTable, pEList);
70986   substExpr(db, p->pWhere, iTable, pEList);
70987   substSelect(db, p->pPrior, iTable, pEList);
70988   pSrc = p->pSrc;
70989   if( pSrc ){
70990     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
70991       substSelect(db, pItem->pSelect, iTable, pEList);
70992     }
70993   }
70994 }
70995 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
70996
70997 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
70998 /*
70999 ** This routine attempts to flatten subqueries in order to speed
71000 ** execution.  It returns 1 if it makes changes and 0 if no flattening
71001 ** occurs.
71002 **
71003 ** To understand the concept of flattening, consider the following
71004 ** query:
71005 **
71006 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
71007 **
71008 ** The default way of implementing this query is to execute the
71009 ** subquery first and store the results in a temporary table, then
71010 ** run the outer query on that temporary table.  This requires two
71011 ** passes over the data.  Furthermore, because the temporary table
71012 ** has no indices, the WHERE clause on the outer query cannot be
71013 ** optimized.
71014 **
71015 ** This routine attempts to rewrite queries such as the above into
71016 ** a single flat select, like this:
71017 **
71018 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
71019 **
71020 ** The code generated for this simpification gives the same result
71021 ** but only has to scan the data once.  And because indices might 
71022 ** exist on the table t1, a complete scan of the data might be
71023 ** avoided.
71024 **
71025 ** Flattening is only attempted if all of the following are true:
71026 **
71027 **   (1)  The subquery and the outer query do not both use aggregates.
71028 **
71029 **   (2)  The subquery is not an aggregate or the outer query is not a join.
71030 **
71031 **   (3)  The subquery is not the right operand of a left outer join
71032 **        (Originally ticket #306.  Strenghtened by ticket #3300)
71033 **
71034 **   (4)  The subquery is not DISTINCT or the outer query is not a join.
71035 **
71036 **   (5)  The subquery is not DISTINCT or the outer query does not use
71037 **        aggregates.
71038 **
71039 **   (6)  The subquery does not use aggregates or the outer query is not
71040 **        DISTINCT.
71041 **
71042 **   (7)  The subquery has a FROM clause.
71043 **
71044 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
71045 **
71046 **   (9)  The subquery does not use LIMIT or the outer query does not use
71047 **        aggregates.
71048 **
71049 **  (10)  The subquery does not use aggregates or the outer query does not
71050 **        use LIMIT.
71051 **
71052 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
71053 **
71054 **  (12)  Not implemented.  Subsumed into restriction (3).  Was previously
71055 **        a separate restriction deriving from ticket #350.
71056 **
71057 **  (13)  The subquery and outer query do not both use LIMIT
71058 **
71059 **  (14)  The subquery does not use OFFSET
71060 **
71061 **  (15)  The outer query is not part of a compound select or the
71062 **        subquery does not have both an ORDER BY and a LIMIT clause.
71063 **        (See ticket #2339)
71064 **
71065 **  (16)  The outer query is not an aggregate or the subquery does
71066 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
71067 **        until we introduced the group_concat() function.  
71068 **
71069 **  (17)  The sub-query is not a compound select, or it is a UNION ALL 
71070 **        compound clause made up entirely of non-aggregate queries, and 
71071 **        the parent query:
71072 **
71073 **          * is not itself part of a compound select,
71074 **          * is not an aggregate or DISTINCT query, and
71075 **          * has no other tables or sub-selects in the FROM clause.
71076 **
71077 **        The parent and sub-query may contain WHERE clauses. Subject to
71078 **        rules (11), (13) and (14), they may also contain ORDER BY,
71079 **        LIMIT and OFFSET clauses.
71080 **
71081 **  (18)  If the sub-query is a compound select, then all terms of the
71082 **        ORDER by clause of the parent must be simple references to 
71083 **        columns of the sub-query.
71084 **
71085 **  (19)  The subquery does not use LIMIT or the outer query does not
71086 **        have a WHERE clause.
71087 **
71088 ** In this routine, the "p" parameter is a pointer to the outer query.
71089 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
71090 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
71091 **
71092 ** If flattening is not attempted, this routine is a no-op and returns 0.
71093 ** If flattening is attempted this routine returns 1.
71094 **
71095 ** All of the expression analysis must occur on both the outer query and
71096 ** the subquery before this routine runs.
71097 */
71098 static int flattenSubquery(
71099   Parse *pParse,       /* Parsing context */
71100   Select *p,           /* The parent or outer SELECT statement */
71101   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
71102   int isAgg,           /* True if outer SELECT uses aggregate functions */
71103   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
71104 ){
71105   const char *zSavedAuthContext = pParse->zAuthContext;
71106   Select *pParent;
71107   Select *pSub;       /* The inner query or "subquery" */
71108   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
71109   SrcList *pSrc;      /* The FROM clause of the outer query */
71110   SrcList *pSubSrc;   /* The FROM clause of the subquery */
71111   ExprList *pList;    /* The result set of the outer query */
71112   int iParent;        /* VDBE cursor number of the pSub result set temp table */
71113   int i;              /* Loop counter */
71114   Expr *pWhere;                    /* The WHERE clause */
71115   struct SrcList_item *pSubitem;   /* The subquery */
71116   sqlite3 *db = pParse->db;
71117
71118   /* Check to see if flattening is permitted.  Return 0 if not.
71119   */
71120   if( p==0 ) return 0;
71121   pSrc = p->pSrc;
71122   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
71123   pSubitem = &pSrc->a[iFrom];
71124   iParent = pSubitem->iCursor;
71125   pSub = pSubitem->pSelect;
71126   assert( pSub!=0 );
71127   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
71128   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
71129   pSubSrc = pSub->pSrc;
71130   assert( pSubSrc );
71131   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
71132   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
71133   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
71134   ** became arbitrary expressions, we were forced to add restrictions (13)
71135   ** and (14). */
71136   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
71137   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
71138   if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
71139     return 0;                                            /* Restriction (15) */
71140   }
71141   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
71142   if( ((pSub->selFlags & SF_Distinct)!=0 || pSub->pLimit) 
71143          && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
71144      return 0;       
71145   }
71146   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
71147      return 0;         /* Restriction (6)  */
71148   }
71149   if( p->pOrderBy && pSub->pOrderBy ){
71150      return 0;                                           /* Restriction (11) */
71151   }
71152   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
71153   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
71154
71155   /* OBSOLETE COMMENT 1:
71156   ** Restriction 3:  If the subquery is a join, make sure the subquery is 
71157   ** not used as the right operand of an outer join.  Examples of why this
71158   ** is not allowed:
71159   **
71160   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
71161   **
71162   ** If we flatten the above, we would get
71163   **
71164   **         (t1 LEFT OUTER JOIN t2) JOIN t3
71165   **
71166   ** which is not at all the same thing.
71167   **
71168   ** OBSOLETE COMMENT 2:
71169   ** Restriction 12:  If the subquery is the right operand of a left outer
71170   ** join, make sure the subquery has no WHERE clause.
71171   ** An examples of why this is not allowed:
71172   **
71173   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
71174   **
71175   ** If we flatten the above, we would get
71176   **
71177   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
71178   **
71179   ** But the t2.x>0 test will always fail on a NULL row of t2, which
71180   ** effectively converts the OUTER JOIN into an INNER JOIN.
71181   **
71182   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
71183   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
71184   ** is fraught with danger.  Best to avoid the whole thing.  If the
71185   ** subquery is the right term of a LEFT JOIN, then do not flatten.
71186   */
71187   if( (pSubitem->jointype & JT_OUTER)!=0 ){
71188     return 0;
71189   }
71190
71191   /* Restriction 17: If the sub-query is a compound SELECT, then it must
71192   ** use only the UNION ALL operator. And none of the simple select queries
71193   ** that make up the compound SELECT are allowed to be aggregate or distinct
71194   ** queries.
71195   */
71196   if( pSub->pPrior ){
71197     if( p->pPrior || isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
71198       return 0;
71199     }
71200     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
71201       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
71202        || (pSub1->pPrior && pSub1->op!=TK_ALL) 
71203        || !pSub1->pSrc || pSub1->pSrc->nSrc!=1
71204       ){
71205         return 0;
71206       }
71207     }
71208
71209     /* Restriction 18. */
71210     if( p->pOrderBy ){
71211       int ii;
71212       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
71213         if( p->pOrderBy->a[ii].iCol==0 ) return 0;
71214       }
71215     }
71216   }
71217
71218   /***** If we reach this point, flattening is permitted. *****/
71219
71220   /* Authorize the subquery */
71221   pParse->zAuthContext = pSubitem->zName;
71222   sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
71223   pParse->zAuthContext = zSavedAuthContext;
71224
71225   /* If the sub-query is a compound SELECT statement, then (by restrictions
71226   ** 17 and 18 above) it must be a UNION ALL and the parent query must 
71227   ** be of the form:
71228   **
71229   **     SELECT <expr-list> FROM (<sub-query>) <where-clause> 
71230   **
71231   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
71232   ** creates N copies of the parent query without any ORDER BY, LIMIT or 
71233   ** OFFSET clauses and joins them to the left-hand-side of the original
71234   ** using UNION ALL operators. In this case N is the number of simple
71235   ** select statements in the compound sub-query.
71236   */
71237   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
71238     Select *pNew;
71239     ExprList *pOrderBy = p->pOrderBy;
71240     Expr *pLimit = p->pLimit;
71241     Expr *pOffset = p->pOffset;
71242     Select *pPrior = p->pPrior;
71243     p->pOrderBy = 0;
71244     p->pSrc = 0;
71245     p->pPrior = 0;
71246     p->pLimit = 0;
71247     pNew = sqlite3SelectDup(db, p);
71248     pNew->pPrior = pPrior;
71249     p->pPrior = pNew;
71250     p->pOrderBy = pOrderBy;
71251     p->op = TK_ALL;
71252     p->pSrc = pSrc;
71253     p->pLimit = pLimit;
71254     p->pOffset = pOffset;
71255     p->pRightmost = 0;
71256     pNew->pRightmost = 0;
71257   }
71258
71259   /* Begin flattening the iFrom-th entry of the FROM clause 
71260   ** in the outer query.
71261   */
71262   pSub = pSub1 = pSubitem->pSelect;
71263   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
71264     int nSubSrc = pSubSrc->nSrc;
71265     int jointype = 0;
71266     pSubSrc = pSub->pSrc;
71267     pSrc = pParent->pSrc;
71268
71269     /* Move all of the FROM elements of the subquery into the
71270     ** the FROM clause of the outer query.  Before doing this, remember
71271     ** the cursor number for the original outer query FROM element in
71272     ** iParent.  The iParent cursor will never be used.  Subsequent code
71273     ** will scan expressions looking for iParent references and replace
71274     ** those references with expressions that resolve to the subquery FROM
71275     ** elements we are now copying in.
71276     */
71277     if( pSrc ){
71278       Table *pTabToDel;
71279       pSubitem = &pSrc->a[iFrom];
71280       nSubSrc = pSubSrc->nSrc;
71281       jointype = pSubitem->jointype;
71282       sqlite3DbFree(db, pSubitem->zDatabase);
71283       sqlite3DbFree(db, pSubitem->zName);
71284       sqlite3DbFree(db, pSubitem->zAlias);
71285       pSubitem->zDatabase = 0;
71286       pSubitem->zName = 0;
71287       pSubitem->zAlias = 0;
71288
71289       /* If the FROM element is a subquery, defer deleting the Table
71290       ** object associated with that subquery until code generation is
71291       ** complete, since there may still exist Expr.pTab entires that
71292       ** refer to the subquery even after flattening.  Ticket #3346.
71293       */
71294       if( (pTabToDel = pSubitem->pTab)!=0 ){
71295         if( pTabToDel->nRef==1 ){
71296           pTabToDel->pNextZombie = pParse->pZombieTab;
71297           pParse->pZombieTab = pTabToDel;
71298         }else{
71299           pTabToDel->nRef--;
71300         }
71301       }
71302       pSubitem->pTab = 0;
71303     }
71304     if( nSubSrc!=1 || !pSrc ){
71305       int extra = nSubSrc - 1;
71306       for(i=(pSrc?1:0); i<nSubSrc; i++){
71307         pSrc = sqlite3SrcListAppend(db, pSrc, 0, 0);
71308         if( pSrc==0 ){
71309           pParent->pSrc = 0;
71310           return 1;
71311         }
71312       }
71313       pParent->pSrc = pSrc;
71314       for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
71315         pSrc->a[i] = pSrc->a[i-extra];
71316       }
71317     }
71318     for(i=0; i<nSubSrc; i++){
71319       pSrc->a[i+iFrom] = pSubSrc->a[i];
71320       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
71321     }
71322     pSrc->a[iFrom].jointype = jointype;
71323   
71324     /* Now begin substituting subquery result set expressions for 
71325     ** references to the iParent in the outer query.
71326     ** 
71327     ** Example:
71328     **
71329     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
71330     **   \                     \_____________ subquery __________/          /
71331     **    \_____________________ outer query ______________________________/
71332     **
71333     ** We look at every expression in the outer query and every place we see
71334     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
71335     */
71336     pList = pParent->pEList;
71337     for(i=0; i<pList->nExpr; i++){
71338       Expr *pExpr;
71339       if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
71340         pList->a[i].zName = 
71341                sqlite3DbStrNDup(db, (char*)pExpr->span.z, pExpr->span.n);
71342       }
71343     }
71344     substExprList(db, pParent->pEList, iParent, pSub->pEList);
71345     if( isAgg ){
71346       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
71347       substExpr(db, pParent->pHaving, iParent, pSub->pEList);
71348     }
71349     if( pSub->pOrderBy ){
71350       assert( pParent->pOrderBy==0 );
71351       pParent->pOrderBy = pSub->pOrderBy;
71352       pSub->pOrderBy = 0;
71353     }else if( pParent->pOrderBy ){
71354       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
71355     }
71356     if( pSub->pWhere ){
71357       pWhere = sqlite3ExprDup(db, pSub->pWhere);
71358     }else{
71359       pWhere = 0;
71360     }
71361     if( subqueryIsAgg ){
71362       assert( pParent->pHaving==0 );
71363       pParent->pHaving = pParent->pWhere;
71364       pParent->pWhere = pWhere;
71365       substExpr(db, pParent->pHaving, iParent, pSub->pEList);
71366       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 
71367                                   sqlite3ExprDup(db, pSub->pHaving));
71368       assert( pParent->pGroupBy==0 );
71369       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy);
71370     }else{
71371       substExpr(db, pParent->pWhere, iParent, pSub->pEList);
71372       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
71373     }
71374   
71375     /* The flattened query is distinct if either the inner or the
71376     ** outer query is distinct. 
71377     */
71378     pParent->selFlags |= pSub->selFlags & SF_Distinct;
71379   
71380     /*
71381     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
71382     **
71383     ** One is tempted to try to add a and b to combine the limits.  But this
71384     ** does not work if either limit is negative.
71385     */
71386     if( pSub->pLimit ){
71387       pParent->pLimit = pSub->pLimit;
71388       pSub->pLimit = 0;
71389     }
71390   }
71391
71392   /* Finially, delete what is left of the subquery and return
71393   ** success.
71394   */
71395   sqlite3SelectDelete(db, pSub1);
71396
71397   return 1;
71398 }
71399 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
71400
71401 /*
71402 ** Analyze the SELECT statement passed as an argument to see if it
71403 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if 
71404 ** it is, or 0 otherwise. At present, a query is considered to be
71405 ** a min()/max() query if:
71406 **
71407 **   1. There is a single object in the FROM clause.
71408 **
71409 **   2. There is a single expression in the result set, and it is
71410 **      either min(x) or max(x), where x is a column reference.
71411 */
71412 static int minMaxQuery(Parse *pParse, Select *p){
71413   Expr *pExpr;
71414   ExprList *pEList = p->pEList;
71415
71416   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
71417   pExpr = pEList->a[0].pExpr;
71418   pEList = pExpr->pList;
71419   if( pExpr->op!=TK_AGG_FUNCTION || pEList==0 || pEList->nExpr!=1 ) return 0;
71420   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
71421   if( pExpr->token.n!=3 ) return WHERE_ORDERBY_NORMAL;
71422   if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){
71423     return WHERE_ORDERBY_MIN;
71424   }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){
71425     return WHERE_ORDERBY_MAX;
71426   }
71427   return WHERE_ORDERBY_NORMAL;
71428 }
71429
71430 /*
71431 ** This routine is a Walker callback for "expanding" a SELECT statement.
71432 ** "Expanding" means to do the following:
71433 **
71434 **    (1)  Make sure VDBE cursor numbers have been assigned to every
71435 **         element of the FROM clause.
71436 **
71437 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
71438 **         defines FROM clause.  When views appear in the FROM clause,
71439 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
71440 **         that implements the view.  A copy is made of the view's SELECT
71441 **         statement so that we can freely modify or delete that statement
71442 **         without worrying about messing up the presistent representation
71443 **         of the view.
71444 **
71445 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
71446 **         on joins and the ON and USING clause of joins.
71447 **
71448 **    (4)  Scan the list of columns in the result set (pEList) looking
71449 **         for instances of the "*" operator or the TABLE.* operator.
71450 **         If found, expand each "*" to be every column in every table
71451 **         and TABLE.* to be every column in TABLE.
71452 **
71453 */
71454 static int selectExpander(Walker *pWalker, Select *p){
71455   Parse *pParse = pWalker->pParse;
71456   int i, j, k;
71457   SrcList *pTabList;
71458   ExprList *pEList;
71459   struct SrcList_item *pFrom;
71460   sqlite3 *db = pParse->db;
71461
71462   if( db->mallocFailed  ){
71463     return WRC_Abort;
71464   }
71465   if( p->pSrc==0 || (p->selFlags & SF_Expanded)!=0 ){
71466     return WRC_Prune;
71467   }
71468   p->selFlags |= SF_Expanded;
71469   pTabList = p->pSrc;
71470   pEList = p->pEList;
71471
71472   /* Make sure cursor numbers have been assigned to all entries in
71473   ** the FROM clause of the SELECT statement.
71474   */
71475   sqlite3SrcListAssignCursors(pParse, pTabList);
71476
71477   /* Look up every table named in the FROM clause of the select.  If
71478   ** an entry of the FROM clause is a subquery instead of a table or view,
71479   ** then create a transient table structure to describe the subquery.
71480   */
71481   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
71482     Table *pTab;
71483     if( pFrom->pTab!=0 ){
71484       /* This statement has already been prepared.  There is no need
71485       ** to go further. */
71486       assert( i==0 );
71487       return WRC_Prune;
71488     }
71489     if( pFrom->zName==0 ){
71490 #ifndef SQLITE_OMIT_SUBQUERY
71491       Select *pSel = pFrom->pSelect;
71492       /* A sub-query in the FROM clause of a SELECT */
71493       assert( pSel!=0 );
71494       assert( pFrom->pTab==0 );
71495       sqlite3WalkSelect(pWalker, pSel);
71496       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
71497       if( pTab==0 ) return WRC_Abort;
71498       pTab->db = db;
71499       pTab->nRef = 1;
71500       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
71501       while( pSel->pPrior ){ pSel = pSel->pPrior; }
71502       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
71503       pTab->iPKey = -1;
71504       pTab->tabFlags |= TF_Ephemeral;
71505 #endif
71506     }else{
71507       /* An ordinary table or view name in the FROM clause */
71508       assert( pFrom->pTab==0 );
71509       pFrom->pTab = pTab = 
71510         sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
71511       if( pTab==0 ) return WRC_Abort;
71512       pTab->nRef++;
71513 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
71514       if( pTab->pSelect || IsVirtual(pTab) ){
71515         /* We reach here if the named table is a really a view */
71516         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
71517
71518         /* If pFrom->pSelect!=0 it means we are dealing with a
71519         ** view within a view.  The SELECT structure has already been
71520         ** copied by the outer view so we can skip the copy step here
71521         ** in the inner view.
71522         */
71523         if( pFrom->pSelect==0 ){
71524           pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect);
71525           sqlite3WalkSelect(pWalker, pFrom->pSelect);
71526         }
71527       }
71528 #endif
71529     }
71530   }
71531
71532   /* Process NATURAL keywords, and ON and USING clauses of joins.
71533   */
71534   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
71535     return WRC_Abort;
71536   }
71537
71538   /* For every "*" that occurs in the column list, insert the names of
71539   ** all columns in all tables.  And for every TABLE.* insert the names
71540   ** of all columns in TABLE.  The parser inserted a special expression
71541   ** with the TK_ALL operator for each "*" that it found in the column list.
71542   ** The following code just has to locate the TK_ALL expressions and expand
71543   ** each one to the list of all columns in all tables.
71544   **
71545   ** The first loop just checks to see if there are any "*" operators
71546   ** that need expanding.
71547   */
71548   for(k=0; k<pEList->nExpr; k++){
71549     Expr *pE = pEList->a[k].pExpr;
71550     if( pE->op==TK_ALL ) break;
71551     if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
71552          && pE->pLeft && pE->pLeft->op==TK_ID ) break;
71553   }
71554   if( k<pEList->nExpr ){
71555     /*
71556     ** If we get here it means the result set contains one or more "*"
71557     ** operators that need to be expanded.  Loop through each expression
71558     ** in the result set and expand them one by one.
71559     */
71560     struct ExprList_item *a = pEList->a;
71561     ExprList *pNew = 0;
71562     int flags = pParse->db->flags;
71563     int longNames = (flags & SQLITE_FullColNames)!=0
71564                       && (flags & SQLITE_ShortColNames)==0;
71565
71566     for(k=0; k<pEList->nExpr; k++){
71567       Expr *pE = a[k].pExpr;
71568       if( pE->op!=TK_ALL &&
71569            (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
71570         /* This particular expression does not need to be expanded.
71571         */
71572         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr, 0);
71573         if( pNew ){
71574           pNew->a[pNew->nExpr-1].zName = a[k].zName;
71575         }
71576         a[k].pExpr = 0;
71577         a[k].zName = 0;
71578       }else{
71579         /* This expression is a "*" or a "TABLE.*" and needs to be
71580         ** expanded. */
71581         int tableSeen = 0;      /* Set to 1 when TABLE matches */
71582         char *zTName;            /* text of name of TABLE */
71583         if( pE->op==TK_DOT && pE->pLeft ){
71584           zTName = sqlite3NameFromToken(db, &pE->pLeft->token);
71585         }else{
71586           zTName = 0;
71587         }
71588         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
71589           Table *pTab = pFrom->pTab;
71590           char *zTabName = pFrom->zAlias;
71591           if( zTabName==0 || zTabName[0]==0 ){ 
71592             zTabName = pTab->zName;
71593           }
71594           if( db->mallocFailed ) break;
71595           if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
71596             continue;
71597           }
71598           tableSeen = 1;
71599           for(j=0; j<pTab->nCol; j++){
71600             Expr *pExpr, *pRight;
71601             char *zName = pTab->aCol[j].zName;
71602
71603             /* If a column is marked as 'hidden' (currently only possible
71604             ** for virtual tables), do not include it in the expanded
71605             ** result-set list.
71606             */
71607             if( IsHiddenColumn(&pTab->aCol[j]) ){
71608               assert(IsVirtual(pTab));
71609               continue;
71610             }
71611
71612             if( i>0 ){
71613               struct SrcList_item *pLeft = &pTabList->a[i-1];
71614               if( (pLeft[1].jointype & JT_NATURAL)!=0 &&
71615                         columnIndex(pLeft->pTab, zName)>=0 ){
71616                 /* In a NATURAL join, omit the join columns from the 
71617                 ** table on the right */
71618                 continue;
71619               }
71620               if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){
71621                 /* In a join with a USING clause, omit columns in the
71622                 ** using clause from the table on the right. */
71623                 continue;
71624               }
71625             }
71626             pRight = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
71627             if( pRight==0 ) break;
71628             setQuotedToken(pParse, &pRight->token, zName);
71629             if( longNames || pTabList->nSrc>1 ){
71630               Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
71631               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
71632               if( pExpr==0 ) break;
71633               setQuotedToken(pParse, &pLeft->token, zTabName);
71634               setToken(&pExpr->span, 
71635                   sqlite3MPrintf(db, "%s.%s", zTabName, zName));
71636               pExpr->span.dyn = 1;
71637               pExpr->token.z = 0;
71638               pExpr->token.n = 0;
71639               pExpr->token.dyn = 0;
71640             }else{
71641               pExpr = pRight;
71642               pExpr->span = pExpr->token;
71643               pExpr->span.dyn = 0;
71644             }
71645             if( longNames ){
71646               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pExpr->span);
71647             }else{
71648               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pRight->token);
71649             }
71650           }
71651         }
71652         if( !tableSeen ){
71653           if( zTName ){
71654             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
71655           }else{
71656             sqlite3ErrorMsg(pParse, "no tables specified");
71657           }
71658         }
71659         sqlite3DbFree(db, zTName);
71660       }
71661     }
71662     sqlite3ExprListDelete(db, pEList);
71663     p->pEList = pNew;
71664   }
71665 #if SQLITE_MAX_COLUMN
71666   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
71667     sqlite3ErrorMsg(pParse, "too many columns in result set");
71668   }
71669 #endif
71670   return WRC_Continue;
71671 }
71672
71673 /*
71674 ** No-op routine for the parse-tree walker.
71675 **
71676 ** When this routine is the Walker.xExprCallback then expression trees
71677 ** are walked without any actions being taken at each node.  Presumably,
71678 ** when this routine is used for Walker.xExprCallback then 
71679 ** Walker.xSelectCallback is set to do something useful for every 
71680 ** subquery in the parser tree.
71681 */
71682 static int exprWalkNoop(Walker *pWalker, Expr *pExpr){
71683   return WRC_Continue;
71684 }
71685
71686 /*
71687 ** This routine "expands" a SELECT statement and all of its subqueries.
71688 ** For additional information on what it means to "expand" a SELECT
71689 ** statement, see the comment on the selectExpand worker callback above.
71690 **
71691 ** Expanding a SELECT statement is the first step in processing a
71692 ** SELECT statement.  The SELECT statement must be expanded before
71693 ** name resolution is performed.
71694 **
71695 ** If anything goes wrong, an error message is written into pParse.
71696 ** The calling function can detect the problem by looking at pParse->nErr
71697 ** and/or pParse->db->mallocFailed.
71698 */
71699 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
71700   Walker w;
71701   w.xSelectCallback = selectExpander;
71702   w.xExprCallback = exprWalkNoop;
71703   w.pParse = pParse;
71704   sqlite3WalkSelect(&w, pSelect);
71705 }
71706
71707
71708 #ifndef SQLITE_OMIT_SUBQUERY
71709 /*
71710 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
71711 ** interface.
71712 **
71713 ** For each FROM-clause subquery, add Column.zType and Column.zColl
71714 ** information to the Table structure that represents the result set
71715 ** of that subquery.
71716 **
71717 ** The Table structure that represents the result set was constructed
71718 ** by selectExpander() but the type and collation information was omitted
71719 ** at that point because identifiers had not yet been resolved.  This
71720 ** routine is called after identifier resolution.
71721 */
71722 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
71723   Parse *pParse;
71724   int i;
71725   SrcList *pTabList;
71726   struct SrcList_item *pFrom;
71727
71728   assert( p->selFlags & SF_Resolved );
71729   if( (p->selFlags & SF_HasTypeInfo)==0 ){
71730     p->selFlags |= SF_HasTypeInfo;
71731     pParse = pWalker->pParse;
71732     pTabList = p->pSrc;
71733     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
71734       Table *pTab = pFrom->pTab;
71735       if( pTab && (pTab->tabFlags & TF_Ephemeral)!=0 ){
71736         /* A sub-query in the FROM clause of a SELECT */
71737         Select *pSel = pFrom->pSelect;
71738         assert( pSel );
71739         while( pSel->pPrior ) pSel = pSel->pPrior;
71740         selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
71741       }
71742     }
71743   }
71744   return WRC_Continue;
71745 }
71746 #endif
71747
71748
71749 /*
71750 ** This routine adds datatype and collating sequence information to
71751 ** the Table structures of all FROM-clause subqueries in a
71752 ** SELECT statement.
71753 **
71754 ** Use this routine after name resolution.
71755 */
71756 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
71757 #ifndef SQLITE_OMIT_SUBQUERY
71758   Walker w;
71759   w.xSelectCallback = selectAddSubqueryTypeInfo;
71760   w.xExprCallback = exprWalkNoop;
71761   w.pParse = pParse;
71762   sqlite3WalkSelect(&w, pSelect);
71763 #endif
71764 }
71765
71766
71767 /*
71768 ** This routine sets of a SELECT statement for processing.  The
71769 ** following is accomplished:
71770 **
71771 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
71772 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
71773 **     *  ON and USING clauses are shifted into WHERE statements
71774 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
71775 **     *  Identifiers in expression are matched to tables.
71776 **
71777 ** This routine acts recursively on all subqueries within the SELECT.
71778 */
71779 SQLITE_PRIVATE void sqlite3SelectPrep(
71780   Parse *pParse,         /* The parser context */
71781   Select *p,             /* The SELECT statement being coded. */
71782   NameContext *pOuterNC  /* Name context for container */
71783 ){
71784   sqlite3 *db;
71785   if( p==0 ) return;
71786   db = pParse->db;
71787   if( p->selFlags & SF_HasTypeInfo ) return;
71788   if( pParse->nErr || db->mallocFailed ) return;
71789   sqlite3SelectExpand(pParse, p);
71790   if( pParse->nErr || db->mallocFailed ) return;
71791   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
71792   if( pParse->nErr || db->mallocFailed ) return;
71793   sqlite3SelectAddTypeInfo(pParse, p);
71794 }
71795
71796 /*
71797 ** Reset the aggregate accumulator.
71798 **
71799 ** The aggregate accumulator is a set of memory cells that hold
71800 ** intermediate results while calculating an aggregate.  This
71801 ** routine simply stores NULLs in all of those memory cells.
71802 */
71803 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
71804   Vdbe *v = pParse->pVdbe;
71805   int i;
71806   struct AggInfo_func *pFunc;
71807   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
71808     return;
71809   }
71810   for(i=0; i<pAggInfo->nColumn; i++){
71811     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
71812   }
71813   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
71814     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
71815     if( pFunc->iDistinct>=0 ){
71816       Expr *pE = pFunc->pExpr;
71817       if( pE->pList==0 || pE->pList->nExpr!=1 ){
71818         sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed "
71819            "by an expression");
71820         pFunc->iDistinct = -1;
71821       }else{
71822         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList);
71823         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
71824                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
71825       }
71826     }
71827   }
71828 }
71829
71830 /*
71831 ** Invoke the OP_AggFinalize opcode for every aggregate function
71832 ** in the AggInfo structure.
71833 */
71834 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
71835   Vdbe *v = pParse->pVdbe;
71836   int i;
71837   struct AggInfo_func *pF;
71838   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
71839     ExprList *pList = pF->pExpr->pList;
71840     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
71841                       (void*)pF->pFunc, P4_FUNCDEF);
71842   }
71843 }
71844
71845 /*
71846 ** Update the accumulator memory cells for an aggregate based on
71847 ** the current cursor position.
71848 */
71849 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
71850   Vdbe *v = pParse->pVdbe;
71851   int i;
71852   struct AggInfo_func *pF;
71853   struct AggInfo_col *pC;
71854
71855   pAggInfo->directMode = 1;
71856   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
71857     int nArg;
71858     int addrNext = 0;
71859     int regAgg;
71860     ExprList *pList = pF->pExpr->pList;
71861     if( pList ){
71862       nArg = pList->nExpr;
71863       regAgg = sqlite3GetTempRange(pParse, nArg);
71864       sqlite3ExprCodeExprList(pParse, pList, regAgg, 0);
71865     }else{
71866       nArg = 0;
71867       regAgg = 0;
71868     }
71869     if( pF->iDistinct>=0 ){
71870       addrNext = sqlite3VdbeMakeLabel(v);
71871       assert( nArg==1 );
71872       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
71873     }
71874     if( pF->pFunc->needCollSeq ){
71875       CollSeq *pColl = 0;
71876       struct ExprList_item *pItem;
71877       int j;
71878       assert( pList!=0 );  /* pList!=0 if pF->pFunc->needCollSeq is true */
71879       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
71880         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
71881       }
71882       if( !pColl ){
71883         pColl = pParse->db->pDfltColl;
71884       }
71885       sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
71886     }
71887     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
71888                       (void*)pF->pFunc, P4_FUNCDEF);
71889     sqlite3VdbeChangeP5(v, nArg);
71890     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
71891     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
71892     if( addrNext ){
71893       sqlite3VdbeResolveLabel(v, addrNext);
71894     }
71895   }
71896   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
71897     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
71898   }
71899   pAggInfo->directMode = 0;
71900 }
71901
71902 /*
71903 ** Generate code for the SELECT statement given in the p argument.  
71904 **
71905 ** The results are distributed in various ways depending on the
71906 ** contents of the SelectDest structure pointed to by argument pDest
71907 ** as follows:
71908 **
71909 **     pDest->eDest    Result
71910 **     ------------    -------------------------------------------
71911 **     SRT_Output      Generate a row of output (using the OP_ResultRow
71912 **                     opcode) for each row in the result set.
71913 **
71914 **     SRT_Mem         Only valid if the result is a single column.
71915 **                     Store the first column of the first result row
71916 **                     in register pDest->iParm then abandon the rest
71917 **                     of the query.  This destination implies "LIMIT 1".
71918 **
71919 **     SRT_Set         The result must be a single column.  Store each
71920 **                     row of result as the key in table pDest->iParm. 
71921 **                     Apply the affinity pDest->affinity before storing
71922 **                     results.  Used to implement "IN (SELECT ...)".
71923 **
71924 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
71925 **
71926 **     SRT_Except      Remove results from the temporary table pDest->iParm.
71927 **
71928 **     SRT_Table       Store results in temporary table pDest->iParm.
71929 **                     This is like SRT_EphemTab except that the table
71930 **                     is assumed to already be open.
71931 **
71932 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
71933 **                     the result there. The cursor is left open after
71934 **                     returning.  This is like SRT_Table except that
71935 **                     this destination uses OP_OpenEphemeral to create
71936 **                     the table first.
71937 **
71938 **     SRT_Coroutine   Generate a co-routine that returns a new row of
71939 **                     results each time it is invoked.  The entry point
71940 **                     of the co-routine is stored in register pDest->iParm.
71941 **
71942 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
71943 **                     set is not empty.
71944 **
71945 **     SRT_Discard     Throw the results away.  This is used by SELECT
71946 **                     statements within triggers whose only purpose is
71947 **                     the side-effects of functions.
71948 **
71949 ** This routine returns the number of errors.  If any errors are
71950 ** encountered, then an appropriate error message is left in
71951 ** pParse->zErrMsg.
71952 **
71953 ** This routine does NOT free the Select structure passed in.  The
71954 ** calling function needs to do that.
71955 */
71956 SQLITE_PRIVATE int sqlite3Select(
71957   Parse *pParse,         /* The parser context */
71958   Select *p,             /* The SELECT statement being coded. */
71959   SelectDest *pDest      /* What to do with the query results */
71960 ){
71961   int i, j;              /* Loop counters */
71962   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
71963   Vdbe *v;               /* The virtual machine under construction */
71964   int isAgg;             /* True for select lists like "count(*)" */
71965   ExprList *pEList;      /* List of columns to extract. */
71966   SrcList *pTabList;     /* List of tables to select from */
71967   Expr *pWhere;          /* The WHERE clause.  May be NULL */
71968   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
71969   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
71970   Expr *pHaving;         /* The HAVING clause.  May be NULL */
71971   int isDistinct;        /* True if the DISTINCT keyword is present */
71972   int distinct;          /* Table to use for the distinct set */
71973   int rc = 1;            /* Value to return from this function */
71974   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
71975   AggInfo sAggInfo;      /* Information used by aggregate queries */
71976   int iEnd;              /* Address of the end of the query */
71977   sqlite3 *db;           /* The database connection */
71978
71979   db = pParse->db;
71980   if( p==0 || db->mallocFailed || pParse->nErr ){
71981     return 1;
71982   }
71983   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
71984   memset(&sAggInfo, 0, sizeof(sAggInfo));
71985
71986   pOrderBy = p->pOrderBy;
71987   if( IgnorableOrderby(pDest) ){
71988     p->pOrderBy = 0;
71989
71990     /* In these cases the DISTINCT operator makes no difference to the
71991     ** results, so remove it if it were specified.
71992     */
71993     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
71994            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
71995     p->selFlags &= ~SF_Distinct;
71996   }
71997   sqlite3SelectPrep(pParse, p, 0);
71998   if( pParse->nErr ){
71999     goto select_end;
72000   }
72001   p->pOrderBy = pOrderBy;
72002
72003
72004   /* Make local copies of the parameters for this query.
72005   */
72006   pTabList = p->pSrc;
72007   isAgg = (p->selFlags & SF_Aggregate)!=0;
72008   pEList = p->pEList;
72009   if( pEList==0 ) goto select_end;
72010
72011   /* 
72012   ** Do not even attempt to generate any code if we have already seen
72013   ** errors before this routine starts.
72014   */
72015   if( pParse->nErr>0 ) goto select_end;
72016
72017   /* ORDER BY is ignored for some destinations.
72018   */
72019   if( IgnorableOrderby(pDest) ){
72020     pOrderBy = 0;
72021   }
72022
72023   /* Begin generating code.
72024   */
72025   v = sqlite3GetVdbe(pParse);
72026   if( v==0 ) goto select_end;
72027
72028   /* Generate code for all sub-queries in the FROM clause
72029   */
72030 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
72031   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
72032     struct SrcList_item *pItem = &pTabList->a[i];
72033     SelectDest dest;
72034     Select *pSub = pItem->pSelect;
72035     int isAggSub;
72036
72037     if( pSub==0 || pItem->isPopulated ) continue;
72038
72039     /* Increment Parse.nHeight by the height of the largest expression
72040     ** tree refered to by this, the parent select. The child select
72041     ** may contain expression trees of at most
72042     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
72043     ** more conservative than necessary, but much easier than enforcing
72044     ** an exact limit.
72045     */
72046     pParse->nHeight += sqlite3SelectExprHeight(p);
72047
72048     /* Check to see if the subquery can be absorbed into the parent. */
72049     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
72050     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
72051       if( isAggSub ){
72052         isAgg = 1;
72053         p->selFlags |= SF_Aggregate;
72054       }
72055       i = -1;
72056     }else{
72057       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
72058       assert( pItem->isPopulated==0 );
72059       sqlite3Select(pParse, pSub, &dest);
72060       pItem->isPopulated = 1;
72061     }
72062     if( pParse->nErr || db->mallocFailed ){
72063       goto select_end;
72064     }
72065     pParse->nHeight -= sqlite3SelectExprHeight(p);
72066     pTabList = p->pSrc;
72067     if( !IgnorableOrderby(pDest) ){
72068       pOrderBy = p->pOrderBy;
72069     }
72070   }
72071   pEList = p->pEList;
72072 #endif
72073   pWhere = p->pWhere;
72074   pGroupBy = p->pGroupBy;
72075   pHaving = p->pHaving;
72076   isDistinct = (p->selFlags & SF_Distinct)!=0;
72077
72078 #ifndef SQLITE_OMIT_COMPOUND_SELECT
72079   /* If there is are a sequence of queries, do the earlier ones first.
72080   */
72081   if( p->pPrior ){
72082     if( p->pRightmost==0 ){
72083       Select *pLoop, *pRight = 0;
72084       int cnt = 0;
72085       int mxSelect;
72086       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
72087         pLoop->pRightmost = p;
72088         pLoop->pNext = pRight;
72089         pRight = pLoop;
72090       }
72091       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
72092       if( mxSelect && cnt>mxSelect ){
72093         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
72094         return 1;
72095       }
72096     }
72097     return multiSelect(pParse, p, pDest);
72098   }
72099 #endif
72100
72101   /* If writing to memory or generating a set
72102   ** only a single column may be output.
72103   */
72104 #ifndef SQLITE_OMIT_SUBQUERY
72105   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
72106     goto select_end;
72107   }
72108 #endif
72109
72110   /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
72111   ** GROUP BY might use an index, DISTINCT never does.
72112   */
72113   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct && !p->pGroupBy ){
72114     p->pGroupBy = sqlite3ExprListDup(db, p->pEList);
72115     pGroupBy = p->pGroupBy;
72116     p->selFlags &= ~SF_Distinct;
72117     isDistinct = 0;
72118   }
72119
72120   /* If there is an ORDER BY clause, then this sorting
72121   ** index might end up being unused if the data can be 
72122   ** extracted in pre-sorted order.  If that is the case, then the
72123   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
72124   ** we figure out that the sorting index is not needed.  The addrSortIndex
72125   ** variable is used to facilitate that change.
72126   */
72127   if( pOrderBy ){
72128     KeyInfo *pKeyInfo;
72129     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
72130     pOrderBy->iECursor = pParse->nTab++;
72131     p->addrOpenEphm[2] = addrSortIndex =
72132       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
72133                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
72134                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
72135   }else{
72136     addrSortIndex = -1;
72137   }
72138
72139   /* If the output is destined for a temporary table, open that table.
72140   */
72141   if( pDest->eDest==SRT_EphemTab ){
72142     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
72143   }
72144
72145   /* Set the limiter.
72146   */
72147   iEnd = sqlite3VdbeMakeLabel(v);
72148   computeLimitRegisters(pParse, p, iEnd);
72149
72150   /* Open a virtual index to use for the distinct set.
72151   */
72152   if( isDistinct ){
72153     KeyInfo *pKeyInfo;
72154     assert( isAgg || pGroupBy );
72155     distinct = pParse->nTab++;
72156     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
72157     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
72158                         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
72159   }else{
72160     distinct = -1;
72161   }
72162
72163   /* Aggregate and non-aggregate queries are handled differently */
72164   if( !isAgg && pGroupBy==0 ){
72165     /* This case is for non-aggregate queries
72166     ** Begin the database scan
72167     */
72168     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
72169     if( pWInfo==0 ) goto select_end;
72170
72171     /* If sorting index that was created by a prior OP_OpenEphemeral 
72172     ** instruction ended up not being needed, then change the OP_OpenEphemeral
72173     ** into an OP_Noop.
72174     */
72175     if( addrSortIndex>=0 && pOrderBy==0 ){
72176       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
72177       p->addrOpenEphm[2] = -1;
72178     }
72179
72180     /* Use the standard inner loop
72181     */
72182     assert(!isDistinct);
72183     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
72184                     pWInfo->iContinue, pWInfo->iBreak);
72185
72186     /* End the database scan loop.
72187     */
72188     sqlite3WhereEnd(pWInfo);
72189   }else{
72190     /* This is the processing for aggregate queries */
72191     NameContext sNC;    /* Name context for processing aggregate information */
72192     int iAMem;          /* First Mem address for storing current GROUP BY */
72193     int iBMem;          /* First Mem address for previous GROUP BY */
72194     int iUseFlag;       /* Mem address holding flag indicating that at least
72195                         ** one row of the input to the aggregator has been
72196                         ** processed */
72197     int iAbortFlag;     /* Mem address which causes query abort if positive */
72198     int groupBySort;    /* Rows come from source in GROUP BY order */
72199     int addrEnd;        /* End of processing for this SELECT */
72200
72201     /* Remove any and all aliases between the result set and the
72202     ** GROUP BY clause.
72203     */
72204     if( pGroupBy ){
72205       int i;                        /* Loop counter */
72206       struct ExprList_item *pItem;  /* For looping over expression in a list */
72207
72208       for(i=p->pEList->nExpr, pItem=p->pEList->a; i>0; i--, pItem++){
72209         pItem->iAlias = 0;
72210       }
72211       for(i=pGroupBy->nExpr, pItem=pGroupBy->a; i>0; i--, pItem++){
72212         pItem->iAlias = 0;
72213       }
72214     }
72215
72216  
72217     /* Create a label to jump to when we want to abort the query */
72218     addrEnd = sqlite3VdbeMakeLabel(v);
72219
72220     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
72221     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
72222     ** SELECT statement.
72223     */
72224     memset(&sNC, 0, sizeof(sNC));
72225     sNC.pParse = pParse;
72226     sNC.pSrcList = pTabList;
72227     sNC.pAggInfo = &sAggInfo;
72228     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
72229     sAggInfo.pGroupBy = pGroupBy;
72230     sqlite3ExprAnalyzeAggList(&sNC, pEList);
72231     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
72232     if( pHaving ){
72233       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
72234     }
72235     sAggInfo.nAccumulator = sAggInfo.nColumn;
72236     for(i=0; i<sAggInfo.nFunc; i++){
72237       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList);
72238     }
72239     if( db->mallocFailed ) goto select_end;
72240
72241     /* Processing for aggregates with GROUP BY is very different and
72242     ** much more complex than aggregates without a GROUP BY.
72243     */
72244     if( pGroupBy ){
72245       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
72246       int j1;             /* A-vs-B comparision jump */
72247       int addrOutputRow;  /* Start of subroutine that outputs a result row */
72248       int regOutputRow;   /* Return address register for output subroutine */
72249       int addrSetAbort;   /* Set the abort flag and return */
72250       int addrTopOfLoop;  /* Top of the input loop */
72251       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
72252       int addrReset;      /* Subroutine for resetting the accumulator */
72253       int regReset;       /* Return address register for reset subroutine */
72254
72255       /* If there is a GROUP BY clause we might need a sorting index to
72256       ** implement it.  Allocate that sorting index now.  If it turns out
72257       ** that we do not need it after all, the OpenEphemeral instruction
72258       ** will be converted into a Noop.  
72259       */
72260       sAggInfo.sortingIdx = pParse->nTab++;
72261       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
72262       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 
72263           sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
72264           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
72265
72266       /* Initialize memory locations used by GROUP BY aggregate processing
72267       */
72268       iUseFlag = ++pParse->nMem;
72269       iAbortFlag = ++pParse->nMem;
72270       regOutputRow = ++pParse->nMem;
72271       addrOutputRow = sqlite3VdbeMakeLabel(v);
72272       regReset = ++pParse->nMem;
72273       addrReset = sqlite3VdbeMakeLabel(v);
72274       iAMem = pParse->nMem + 1;
72275       pParse->nMem += pGroupBy->nExpr;
72276       iBMem = pParse->nMem + 1;
72277       pParse->nMem += pGroupBy->nExpr;
72278       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
72279       VdbeComment((v, "clear abort flag"));
72280       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
72281       VdbeComment((v, "indicate accumulator empty"));
72282
72283       /* Begin a loop that will extract all source rows in GROUP BY order.
72284       ** This might involve two separate loops with an OP_Sort in between, or
72285       ** it might be a single loop that uses an index to extract information
72286       ** in the right order to begin with.
72287       */
72288       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
72289       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
72290       if( pWInfo==0 ) goto select_end;
72291       if( pGroupBy==0 ){
72292         /* The optimizer is able to deliver rows in group by order so
72293         ** we do not have to sort.  The OP_OpenEphemeral table will be
72294         ** cancelled later because we still need to use the pKeyInfo
72295         */
72296         pGroupBy = p->pGroupBy;
72297         groupBySort = 0;
72298       }else{
72299         /* Rows are coming out in undetermined order.  We have to push
72300         ** each row into a sorting index, terminate the first loop,
72301         ** then loop over the sorting index in order to get the output
72302         ** in sorted order
72303         */
72304         int regBase;
72305         int regRecord;
72306         int nCol;
72307         int nGroupBy;
72308
72309         groupBySort = 1;
72310         nGroupBy = pGroupBy->nExpr;
72311         nCol = nGroupBy + 1;
72312         j = nGroupBy+1;
72313         for(i=0; i<sAggInfo.nColumn; i++){
72314           if( sAggInfo.aCol[i].iSorterColumn>=j ){
72315             nCol++;
72316             j++;
72317           }
72318         }
72319         regBase = sqlite3GetTempRange(pParse, nCol);
72320         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
72321         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
72322         j = nGroupBy+1;
72323         for(i=0; i<sAggInfo.nColumn; i++){
72324           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
72325           if( pCol->iSorterColumn>=j ){
72326             int r1 = j + regBase;
72327             int r2;
72328
72329             r2 = sqlite3ExprCodeGetColumn(pParse, 
72330                                pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
72331             if( r1!=r2 ){
72332               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
72333             }
72334             j++;
72335           }
72336         }
72337         regRecord = sqlite3GetTempReg(pParse);
72338         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
72339         sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
72340         sqlite3ReleaseTempReg(pParse, regRecord);
72341         sqlite3ReleaseTempRange(pParse, regBase, nCol);
72342         sqlite3WhereEnd(pWInfo);
72343         sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
72344         VdbeComment((v, "GROUP BY sort"));
72345         sAggInfo.useSortingIdx = 1;
72346       }
72347
72348       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
72349       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
72350       ** Then compare the current GROUP BY terms against the GROUP BY terms
72351       ** from the previous row currently stored in a0, a1, a2...
72352       */
72353       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
72354       for(j=0; j<pGroupBy->nExpr; j++){
72355         if( groupBySort ){
72356           sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
72357         }else{
72358           sAggInfo.directMode = 1;
72359           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
72360         }
72361       }
72362       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
72363                           (char*)pKeyInfo, P4_KEYINFO);
72364       j1 = sqlite3VdbeCurrentAddr(v);
72365       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
72366
72367       /* Generate code that runs whenever the GROUP BY changes.
72368       ** Changes in the GROUP BY are detected by the previous code
72369       ** block.  If there were no changes, this block is skipped.
72370       **
72371       ** This code copies current group by terms in b0,b1,b2,...
72372       ** over to a0,a1,a2.  It then calls the output subroutine
72373       ** and resets the aggregate accumulator registers in preparation
72374       ** for the next GROUP BY batch.
72375       */
72376       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
72377       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
72378       VdbeComment((v, "output one row"));
72379       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
72380       VdbeComment((v, "check abort flag"));
72381       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
72382       VdbeComment((v, "reset accumulator"));
72383
72384       /* Update the aggregate accumulators based on the content of
72385       ** the current row
72386       */
72387       sqlite3VdbeJumpHere(v, j1);
72388       updateAccumulator(pParse, &sAggInfo);
72389       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
72390       VdbeComment((v, "indicate data in accumulator"));
72391
72392       /* End of the loop
72393       */
72394       if( groupBySort ){
72395         sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
72396       }else{
72397         sqlite3WhereEnd(pWInfo);
72398         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
72399       }
72400
72401       /* Output the final row of result
72402       */
72403       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
72404       VdbeComment((v, "output final row"));
72405
72406       /* Jump over the subroutines
72407       */
72408       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
72409
72410       /* Generate a subroutine that outputs a single row of the result
72411       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
72412       ** is less than or equal to zero, the subroutine is a no-op.  If
72413       ** the processing calls for the query to abort, this subroutine
72414       ** increments the iAbortFlag memory location before returning in
72415       ** order to signal the caller to abort.
72416       */
72417       addrSetAbort = sqlite3VdbeCurrentAddr(v);
72418       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
72419       VdbeComment((v, "set abort flag"));
72420       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
72421       sqlite3VdbeResolveLabel(v, addrOutputRow);
72422       addrOutputRow = sqlite3VdbeCurrentAddr(v);
72423       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
72424       VdbeComment((v, "Groupby result generator entry point"));
72425       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
72426       finalizeAggFunctions(pParse, &sAggInfo);
72427       if( pHaving ){
72428         sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
72429       }
72430       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
72431                       distinct, pDest,
72432                       addrOutputRow+1, addrSetAbort);
72433       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
72434       VdbeComment((v, "end groupby result generator"));
72435
72436       /* Generate a subroutine that will reset the group-by accumulator
72437       */
72438       sqlite3VdbeResolveLabel(v, addrReset);
72439       resetAccumulator(pParse, &sAggInfo);
72440       sqlite3VdbeAddOp1(v, OP_Return, regReset);
72441      
72442     } /* endif pGroupBy */
72443     else {
72444       ExprList *pMinMax = 0;
72445       ExprList *pDel = 0;
72446       u8 flag;
72447
72448       /* Check if the query is of one of the following forms:
72449       **
72450       **   SELECT min(x) FROM ...
72451       **   SELECT max(x) FROM ...
72452       **
72453       ** If it is, then ask the code in where.c to attempt to sort results
72454       ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 
72455       ** If where.c is able to produce results sorted in this order, then
72456       ** add vdbe code to break out of the processing loop after the 
72457       ** first iteration (since the first iteration of the loop is 
72458       ** guaranteed to operate on the row with the minimum or maximum 
72459       ** value of x, the only row required).
72460       **
72461       ** A special flag must be passed to sqlite3WhereBegin() to slightly
72462       ** modify behaviour as follows:
72463       **
72464       **   + If the query is a "SELECT min(x)", then the loop coded by
72465       **     where.c should not iterate over any values with a NULL value
72466       **     for x.
72467       **
72468       **   + The optimizer code in where.c (the thing that decides which
72469       **     index or indices to use) should place a different priority on 
72470       **     satisfying the 'ORDER BY' clause than it does in other cases.
72471       **     Refer to code and comments in where.c for details.
72472       */
72473       flag = minMaxQuery(pParse, p);
72474       if( flag ){
72475         pDel = pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->pList);
72476         if( pMinMax && !db->mallocFailed ){
72477           pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN;
72478           pMinMax->a[0].pExpr->op = TK_COLUMN;
72479         }
72480       }
72481
72482       /* This case runs if the aggregate has no GROUP BY clause.  The
72483       ** processing is much simpler since there is only a single row
72484       ** of output.
72485       */
72486       resetAccumulator(pParse, &sAggInfo);
72487       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
72488       if( pWInfo==0 ){
72489         sqlite3ExprListDelete(db, pDel);
72490         goto select_end;
72491       }
72492       updateAccumulator(pParse, &sAggInfo);
72493       if( !pMinMax && flag ){
72494         sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
72495         VdbeComment((v, "%s() by index",(flag==WHERE_ORDERBY_MIN?"min":"max")));
72496       }
72497       sqlite3WhereEnd(pWInfo);
72498       finalizeAggFunctions(pParse, &sAggInfo);
72499       pOrderBy = 0;
72500       if( pHaving ){
72501         sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
72502       }
72503       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 
72504                       pDest, addrEnd, addrEnd);
72505
72506       sqlite3ExprListDelete(db, pDel);
72507     }
72508     sqlite3VdbeResolveLabel(v, addrEnd);
72509     
72510   } /* endif aggregate query */
72511
72512   /* If there is an ORDER BY clause, then we need to sort the results
72513   ** and send them to the callback one by one.
72514   */
72515   if( pOrderBy ){
72516     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
72517   }
72518
72519   /* Jump here to skip this query
72520   */
72521   sqlite3VdbeResolveLabel(v, iEnd);
72522
72523   /* The SELECT was successfully coded.   Set the return code to 0
72524   ** to indicate no errors.
72525   */
72526   rc = 0;
72527
72528   /* Control jumps to here if an error is encountered above, or upon
72529   ** successful coding of the SELECT.
72530   */
72531 select_end:
72532
72533   /* Identify column names if results of the SELECT are to be output.
72534   */
72535   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
72536     generateColumnNames(pParse, pTabList, pEList);
72537   }
72538
72539   sqlite3DbFree(db, sAggInfo.aCol);
72540   sqlite3DbFree(db, sAggInfo.aFunc);
72541   return rc;
72542 }
72543
72544 #if defined(SQLITE_DEBUG)
72545 /*
72546 *******************************************************************************
72547 ** The following code is used for testing and debugging only.  The code
72548 ** that follows does not appear in normal builds.
72549 **
72550 ** These routines are used to print out the content of all or part of a 
72551 ** parse structures such as Select or Expr.  Such printouts are useful
72552 ** for helping to understand what is happening inside the code generator
72553 ** during the execution of complex SELECT statements.
72554 **
72555 ** These routine are not called anywhere from within the normal
72556 ** code base.  Then are intended to be called from within the debugger
72557 ** or from temporary "printf" statements inserted for debugging.
72558 */
72559 SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
72560   if( p->token.z && p->token.n>0 ){
72561     sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z);
72562   }else{
72563     sqlite3DebugPrintf("(%d", p->op);
72564   }
72565   if( p->pLeft ){
72566     sqlite3DebugPrintf(" ");
72567     sqlite3PrintExpr(p->pLeft);
72568   }
72569   if( p->pRight ){
72570     sqlite3DebugPrintf(" ");
72571     sqlite3PrintExpr(p->pRight);
72572   }
72573   sqlite3DebugPrintf(")");
72574 }
72575 SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
72576   int i;
72577   for(i=0; i<pList->nExpr; i++){
72578     sqlite3PrintExpr(pList->a[i].pExpr);
72579     if( i<pList->nExpr-1 ){
72580       sqlite3DebugPrintf(", ");
72581     }
72582   }
72583 }
72584 SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
72585   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
72586   sqlite3PrintExprList(p->pEList);
72587   sqlite3DebugPrintf("\n");
72588   if( p->pSrc ){
72589     char *zPrefix;
72590     int i;
72591     zPrefix = "FROM";
72592     for(i=0; i<p->pSrc->nSrc; i++){
72593       struct SrcList_item *pItem = &p->pSrc->a[i];
72594       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
72595       zPrefix = "";
72596       if( pItem->pSelect ){
72597         sqlite3DebugPrintf("(\n");
72598         sqlite3PrintSelect(pItem->pSelect, indent+10);
72599         sqlite3DebugPrintf("%*s)", indent+8, "");
72600       }else if( pItem->zName ){
72601         sqlite3DebugPrintf("%s", pItem->zName);
72602       }
72603       if( pItem->pTab ){
72604         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
72605       }
72606       if( pItem->zAlias ){
72607         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
72608       }
72609       if( i<p->pSrc->nSrc-1 ){
72610         sqlite3DebugPrintf(",");
72611       }
72612       sqlite3DebugPrintf("\n");
72613     }
72614   }
72615   if( p->pWhere ){
72616     sqlite3DebugPrintf("%*s WHERE ", indent, "");
72617     sqlite3PrintExpr(p->pWhere);
72618     sqlite3DebugPrintf("\n");
72619   }
72620   if( p->pGroupBy ){
72621     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
72622     sqlite3PrintExprList(p->pGroupBy);
72623     sqlite3DebugPrintf("\n");
72624   }
72625   if( p->pHaving ){
72626     sqlite3DebugPrintf("%*s HAVING ", indent, "");
72627     sqlite3PrintExpr(p->pHaving);
72628     sqlite3DebugPrintf("\n");
72629   }
72630   if( p->pOrderBy ){
72631     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
72632     sqlite3PrintExprList(p->pOrderBy);
72633     sqlite3DebugPrintf("\n");
72634   }
72635 }
72636 /* End of the structure debug printing code
72637 *****************************************************************************/
72638 #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
72639
72640 /************** End of select.c **********************************************/
72641 /************** Begin file table.c *******************************************/
72642 /*
72643 ** 2001 September 15
72644 **
72645 ** The author disclaims copyright to this source code.  In place of
72646 ** a legal notice, here is a blessing:
72647 **
72648 **    May you do good and not evil.
72649 **    May you find forgiveness for yourself and forgive others.
72650 **    May you share freely, never taking more than you give.
72651 **
72652 *************************************************************************
72653 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
72654 ** interface routines.  These are just wrappers around the main
72655 ** interface routine of sqlite3_exec().
72656 **
72657 ** These routines are in a separate files so that they will not be linked
72658 ** if they are not used.
72659 **
72660 ** $Id: table.c,v 1.36 2008/07/08 22:28:49 shane Exp $
72661 */
72662
72663 #ifndef SQLITE_OMIT_GET_TABLE
72664
72665 /*
72666 ** This structure is used to pass data from sqlite3_get_table() through
72667 ** to the callback function is uses to build the result.
72668 */
72669 typedef struct TabResult {
72670   char **azResult;
72671   char *zErrMsg;
72672   int nResult;
72673   int nAlloc;
72674   int nRow;
72675   int nColumn;
72676   int nData;
72677   int rc;
72678 } TabResult;
72679
72680 /*
72681 ** This routine is called once for each row in the result table.  Its job
72682 ** is to fill in the TabResult structure appropriately, allocating new
72683 ** memory as necessary.
72684 */
72685 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
72686   TabResult *p = (TabResult*)pArg;
72687   int need;
72688   int i;
72689   char *z;
72690
72691   /* Make sure there is enough space in p->azResult to hold everything
72692   ** we need to remember from this invocation of the callback.
72693   */
72694   if( p->nRow==0 && argv!=0 ){
72695     need = nCol*2;
72696   }else{
72697     need = nCol;
72698   }
72699   if( p->nData + need >= p->nAlloc ){
72700     char **azNew;
72701     p->nAlloc = p->nAlloc*2 + need + 1;
72702     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
72703     if( azNew==0 ) goto malloc_failed;
72704     p->azResult = azNew;
72705   }
72706
72707   /* If this is the first row, then generate an extra row containing
72708   ** the names of all columns.
72709   */
72710   if( p->nRow==0 ){
72711     p->nColumn = nCol;
72712     for(i=0; i<nCol; i++){
72713       z = sqlite3_mprintf("%s", colv[i]);
72714       if( z==0 ) goto malloc_failed;
72715       p->azResult[p->nData++] = z;
72716     }
72717   }else if( p->nColumn!=nCol ){
72718     sqlite3_free(p->zErrMsg);
72719     p->zErrMsg = sqlite3_mprintf(
72720        "sqlite3_get_table() called with two or more incompatible queries"
72721     );
72722     p->rc = SQLITE_ERROR;
72723     return 1;
72724   }
72725
72726   /* Copy over the row data
72727   */
72728   if( argv!=0 ){
72729     for(i=0; i<nCol; i++){
72730       if( argv[i]==0 ){
72731         z = 0;
72732       }else{
72733         int n = strlen(argv[i])+1;
72734         z = sqlite3_malloc( n );
72735         if( z==0 ) goto malloc_failed;
72736         memcpy(z, argv[i], n);
72737       }
72738       p->azResult[p->nData++] = z;
72739     }
72740     p->nRow++;
72741   }
72742   return 0;
72743
72744 malloc_failed:
72745   p->rc = SQLITE_NOMEM;
72746   return 1;
72747 }
72748
72749 /*
72750 ** Query the database.  But instead of invoking a callback for each row,
72751 ** malloc() for space to hold the result and return the entire results
72752 ** at the conclusion of the call.
72753 **
72754 ** The result that is written to ***pazResult is held in memory obtained
72755 ** from malloc().  But the caller cannot free this memory directly.  
72756 ** Instead, the entire table should be passed to sqlite3_free_table() when
72757 ** the calling procedure is finished using it.
72758 */
72759 SQLITE_API int sqlite3_get_table(
72760   sqlite3 *db,                /* The database on which the SQL executes */
72761   const char *zSql,           /* The SQL to be executed */
72762   char ***pazResult,          /* Write the result table here */
72763   int *pnRow,                 /* Write the number of rows in the result here */
72764   int *pnColumn,              /* Write the number of columns of result here */
72765   char **pzErrMsg             /* Write error messages here */
72766 ){
72767   int rc;
72768   TabResult res;
72769
72770   *pazResult = 0;
72771   if( pnColumn ) *pnColumn = 0;
72772   if( pnRow ) *pnRow = 0;
72773   res.zErrMsg = 0;
72774   res.nResult = 0;
72775   res.nRow = 0;
72776   res.nColumn = 0;
72777   res.nData = 1;
72778   res.nAlloc = 20;
72779   res.rc = SQLITE_OK;
72780   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
72781   if( res.azResult==0 ){
72782      db->errCode = SQLITE_NOMEM;
72783      return SQLITE_NOMEM;
72784   }
72785   res.azResult[0] = 0;
72786   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
72787   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
72788   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
72789   if( (rc&0xff)==SQLITE_ABORT ){
72790     sqlite3_free_table(&res.azResult[1]);
72791     if( res.zErrMsg ){
72792       if( pzErrMsg ){
72793         sqlite3_free(*pzErrMsg);
72794         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
72795       }
72796       sqlite3_free(res.zErrMsg);
72797     }
72798     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
72799     return res.rc;
72800   }
72801   sqlite3_free(res.zErrMsg);
72802   if( rc!=SQLITE_OK ){
72803     sqlite3_free_table(&res.azResult[1]);
72804     return rc;
72805   }
72806   if( res.nAlloc>res.nData ){
72807     char **azNew;
72808     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*(res.nData+1) );
72809     if( azNew==0 ){
72810       sqlite3_free_table(&res.azResult[1]);
72811       db->errCode = SQLITE_NOMEM;
72812       return SQLITE_NOMEM;
72813     }
72814     res.nAlloc = res.nData+1;
72815     res.azResult = azNew;
72816   }
72817   *pazResult = &res.azResult[1];
72818   if( pnColumn ) *pnColumn = res.nColumn;
72819   if( pnRow ) *pnRow = res.nRow;
72820   return rc;
72821 }
72822
72823 /*
72824 ** This routine frees the space the sqlite3_get_table() malloced.
72825 */
72826 SQLITE_API void sqlite3_free_table(
72827   char **azResult            /* Result returned from from sqlite3_get_table() */
72828 ){
72829   if( azResult ){
72830     int i, n;
72831     azResult--;
72832     assert( azResult!=0 );
72833     n = SQLITE_PTR_TO_INT(azResult[0]);
72834     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
72835     sqlite3_free(azResult);
72836   }
72837 }
72838
72839 #endif /* SQLITE_OMIT_GET_TABLE */
72840
72841 /************** End of table.c ***********************************************/
72842 /************** Begin file trigger.c *****************************************/
72843 /*
72844 **
72845 ** The author disclaims copyright to this source code.  In place of
72846 ** a legal notice, here is a blessing:
72847 **
72848 **    May you do good and not evil.
72849 **    May you find forgiveness for yourself and forgive others.
72850 **    May you share freely, never taking more than you give.
72851 **
72852 *************************************************************************
72853 **
72854 **
72855 ** $Id: trigger.c,v 1.129 2008/08/20 16:35:10 drh Exp $
72856 */
72857
72858 #ifndef SQLITE_OMIT_TRIGGER
72859 /*
72860 ** Delete a linked list of TriggerStep structures.
72861 */
72862 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
72863   while( pTriggerStep ){
72864     TriggerStep * pTmp = pTriggerStep;
72865     pTriggerStep = pTriggerStep->pNext;
72866
72867     if( pTmp->target.dyn ) sqlite3DbFree(db, (char*)pTmp->target.z);
72868     sqlite3ExprDelete(db, pTmp->pWhere);
72869     sqlite3ExprListDelete(db, pTmp->pExprList);
72870     sqlite3SelectDelete(db, pTmp->pSelect);
72871     sqlite3IdListDelete(db, pTmp->pIdList);
72872
72873     sqlite3DbFree(db, pTmp);
72874   }
72875 }
72876
72877 /*
72878 ** This is called by the parser when it sees a CREATE TRIGGER statement
72879 ** up to the point of the BEGIN before the trigger actions.  A Trigger
72880 ** structure is generated based on the information available and stored
72881 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
72882 ** sqlite3FinishTrigger() function is called to complete the trigger
72883 ** construction process.
72884 */
72885 SQLITE_PRIVATE void sqlite3BeginTrigger(
72886   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
72887   Token *pName1,      /* The name of the trigger */
72888   Token *pName2,      /* The name of the trigger */
72889   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
72890   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
72891   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
72892   SrcList *pTableName,/* The name of the table/view the trigger applies to */
72893   Expr *pWhen,        /* WHEN clause */
72894   int isTemp,         /* True if the TEMPORARY keyword is present */
72895   int noErr           /* Suppress errors if the trigger already exists */
72896 ){
72897   Trigger *pTrigger = 0;
72898   Table *pTab;
72899   char *zName = 0;        /* Name of the trigger */
72900   sqlite3 *db = pParse->db;
72901   int iDb;                /* The database to store the trigger in */
72902   Token *pName;           /* The unqualified db name */
72903   DbFixer sFix;
72904   int iTabDb;
72905
72906   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
72907   assert( pName2!=0 );
72908   if( isTemp ){
72909     /* If TEMP was specified, then the trigger name may not be qualified. */
72910     if( pName2->n>0 ){
72911       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
72912       goto trigger_cleanup;
72913     }
72914     iDb = 1;
72915     pName = pName1;
72916   }else{
72917     /* Figure out the db that the the trigger will be created in */
72918     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
72919     if( iDb<0 ){
72920       goto trigger_cleanup;
72921     }
72922   }
72923
72924   /* If the trigger name was unqualified, and the table is a temp table,
72925   ** then set iDb to 1 to create the trigger in the temporary database.
72926   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
72927   ** exist, the error is caught by the block below.
72928   */
72929   if( !pTableName || db->mallocFailed ){
72930     goto trigger_cleanup;
72931   }
72932   pTab = sqlite3SrcListLookup(pParse, pTableName);
72933   if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
72934     iDb = 1;
72935   }
72936
72937   /* Ensure the table name matches database name and that the table exists */
72938   if( db->mallocFailed ) goto trigger_cleanup;
72939   assert( pTableName->nSrc==1 );
72940   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) && 
72941       sqlite3FixSrcList(&sFix, pTableName) ){
72942     goto trigger_cleanup;
72943   }
72944   pTab = sqlite3SrcListLookup(pParse, pTableName);
72945   if( !pTab ){
72946     /* The table does not exist. */
72947     goto trigger_cleanup;
72948   }
72949   if( IsVirtual(pTab) ){
72950     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
72951     goto trigger_cleanup;
72952   }
72953
72954   /* Check that the trigger name is not reserved and that no trigger of the
72955   ** specified name exists */
72956   zName = sqlite3NameFromToken(db, pName);
72957   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
72958     goto trigger_cleanup;
72959   }
72960   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash), zName,strlen(zName)) ){
72961     if( !noErr ){
72962       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
72963     }
72964     goto trigger_cleanup;
72965   }
72966
72967   /* Do not create a trigger on a system table */
72968   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
72969     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
72970     pParse->nErr++;
72971     goto trigger_cleanup;
72972   }
72973
72974   /* INSTEAD of triggers are only for views and views only support INSTEAD
72975   ** of triggers.
72976   */
72977   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
72978     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
72979         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
72980     goto trigger_cleanup;
72981   }
72982   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
72983     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
72984         " trigger on table: %S", pTableName, 0);
72985     goto trigger_cleanup;
72986   }
72987   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
72988
72989 #ifndef SQLITE_OMIT_AUTHORIZATION
72990   {
72991     int code = SQLITE_CREATE_TRIGGER;
72992     const char *zDb = db->aDb[iTabDb].zName;
72993     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
72994     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
72995     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
72996       goto trigger_cleanup;
72997     }
72998     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
72999       goto trigger_cleanup;
73000     }
73001   }
73002 #endif
73003
73004   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
73005   ** cannot appear on views.  So we might as well translate every
73006   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
73007   ** elsewhere.
73008   */
73009   if (tr_tm == TK_INSTEAD){
73010     tr_tm = TK_BEFORE;
73011   }
73012
73013   /* Build the Trigger object */
73014   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
73015   if( pTrigger==0 ) goto trigger_cleanup;
73016   pTrigger->name = zName;
73017   zName = 0;
73018   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
73019   pTrigger->pSchema = db->aDb[iDb].pSchema;
73020   pTrigger->pTabSchema = pTab->pSchema;
73021   pTrigger->op = op;
73022   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
73023   pTrigger->pWhen = sqlite3ExprDup(db, pWhen);
73024   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
73025   sqlite3TokenCopy(db, &pTrigger->nameToken,pName);
73026   assert( pParse->pNewTrigger==0 );
73027   pParse->pNewTrigger = pTrigger;
73028
73029 trigger_cleanup:
73030   sqlite3DbFree(db, zName);
73031   sqlite3SrcListDelete(db, pTableName);
73032   sqlite3IdListDelete(db, pColumns);
73033   sqlite3ExprDelete(db, pWhen);
73034   if( !pParse->pNewTrigger ){
73035     sqlite3DeleteTrigger(db, pTrigger);
73036   }else{
73037     assert( pParse->pNewTrigger==pTrigger );
73038   }
73039 }
73040
73041 /*
73042 ** This routine is called after all of the trigger actions have been parsed
73043 ** in order to complete the process of building the trigger.
73044 */
73045 SQLITE_PRIVATE void sqlite3FinishTrigger(
73046   Parse *pParse,          /* Parser context */
73047   TriggerStep *pStepList, /* The triggered program */
73048   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
73049 ){
73050   Trigger *pTrig = 0;     /* The trigger whose construction is finishing up */
73051   sqlite3 *db = pParse->db;  /* The database */
73052   DbFixer sFix;
73053   int iDb;                   /* Database containing the trigger */
73054
73055   pTrig = pParse->pNewTrigger;
73056   pParse->pNewTrigger = 0;
73057   if( pParse->nErr || !pTrig ) goto triggerfinish_cleanup;
73058   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
73059   pTrig->step_list = pStepList;
73060   while( pStepList ){
73061     pStepList->pTrig = pTrig;
73062     pStepList = pStepList->pNext;
73063   }
73064   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &pTrig->nameToken) 
73065           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
73066     goto triggerfinish_cleanup;
73067   }
73068
73069   /* if we are not initializing, and this trigger is not on a TEMP table, 
73070   ** build the sqlite_master entry
73071   */
73072   if( !db->init.busy ){
73073     Vdbe *v;
73074     char *z;
73075
73076     /* Make an entry in the sqlite_master table */
73077     v = sqlite3GetVdbe(pParse);
73078     if( v==0 ) goto triggerfinish_cleanup;
73079     sqlite3BeginWriteOperation(pParse, 0, iDb);
73080     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
73081     sqlite3NestedParse(pParse,
73082        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
73083        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pTrig->name,
73084        pTrig->table, z);
73085     sqlite3DbFree(db, z);
73086     sqlite3ChangeCookie(pParse, iDb);
73087     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
73088         db, "type='trigger' AND name='%q'", pTrig->name), P4_DYNAMIC
73089     );
73090   }
73091
73092   if( db->init.busy ){
73093     int n;
73094     Table *pTab;
73095     Trigger *pDel;
73096     pDel = sqlite3HashInsert(&db->aDb[iDb].pSchema->trigHash, 
73097                      pTrig->name, strlen(pTrig->name), pTrig);
73098     if( pDel ){
73099       assert( pDel==pTrig );
73100       db->mallocFailed = 1;
73101       goto triggerfinish_cleanup;
73102     }
73103     n = strlen(pTrig->table) + 1;
73104     pTab = sqlite3HashFind(&pTrig->pTabSchema->tblHash, pTrig->table, n);
73105     assert( pTab!=0 );
73106     pTrig->pNext = pTab->pTrigger;
73107     pTab->pTrigger = pTrig;
73108     pTrig = 0;
73109   }
73110
73111 triggerfinish_cleanup:
73112   sqlite3DeleteTrigger(db, pTrig);
73113   assert( !pParse->pNewTrigger );
73114   sqlite3DeleteTriggerStep(db, pStepList);
73115 }
73116
73117 /*
73118 ** Make a copy of all components of the given trigger step.  This has
73119 ** the effect of copying all Expr.token.z values into memory obtained
73120 ** from sqlite3_malloc().  As initially created, the Expr.token.z values
73121 ** all point to the input string that was fed to the parser.  But that
73122 ** string is ephemeral - it will go away as soon as the sqlite3_exec()
73123 ** call that started the parser exits.  This routine makes a persistent
73124 ** copy of all the Expr.token.z strings so that the TriggerStep structure
73125 ** will be valid even after the sqlite3_exec() call returns.
73126 */
73127 static void sqlitePersistTriggerStep(sqlite3 *db, TriggerStep *p){
73128   if( p->target.z ){
73129     p->target.z = (u8*)sqlite3DbStrNDup(db, (char*)p->target.z, p->target.n);
73130     p->target.dyn = 1;
73131   }
73132   if( p->pSelect ){
73133     Select *pNew = sqlite3SelectDup(db, p->pSelect);
73134     sqlite3SelectDelete(db, p->pSelect);
73135     p->pSelect = pNew;
73136   }
73137   if( p->pWhere ){
73138     Expr *pNew = sqlite3ExprDup(db, p->pWhere);
73139     sqlite3ExprDelete(db, p->pWhere);
73140     p->pWhere = pNew;
73141   }
73142   if( p->pExprList ){
73143     ExprList *pNew = sqlite3ExprListDup(db, p->pExprList);
73144     sqlite3ExprListDelete(db, p->pExprList);
73145     p->pExprList = pNew;
73146   }
73147   if( p->pIdList ){
73148     IdList *pNew = sqlite3IdListDup(db, p->pIdList);
73149     sqlite3IdListDelete(db, p->pIdList);
73150     p->pIdList = pNew;
73151   }
73152 }
73153
73154 /*
73155 ** Turn a SELECT statement (that the pSelect parameter points to) into
73156 ** a trigger step.  Return a pointer to a TriggerStep structure.
73157 **
73158 ** The parser calls this routine when it finds a SELECT statement in
73159 ** body of a TRIGGER.  
73160 */
73161 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
73162   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
73163   if( pTriggerStep==0 ) {
73164     sqlite3SelectDelete(db, pSelect);
73165     return 0;
73166   }
73167
73168   pTriggerStep->op = TK_SELECT;
73169   pTriggerStep->pSelect = pSelect;
73170   pTriggerStep->orconf = OE_Default;
73171   sqlitePersistTriggerStep(db, pTriggerStep);
73172
73173   return pTriggerStep;
73174 }
73175
73176 /*
73177 ** Build a trigger step out of an INSERT statement.  Return a pointer
73178 ** to the new trigger step.
73179 **
73180 ** The parser calls this routine when it sees an INSERT inside the
73181 ** body of a trigger.
73182 */
73183 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
73184   sqlite3 *db,        /* The database connection */
73185   Token *pTableName,  /* Name of the table into which we insert */
73186   IdList *pColumn,    /* List of columns in pTableName to insert into */
73187   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
73188   Select *pSelect,    /* A SELECT statement that supplies values */
73189   int orconf          /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
73190 ){
73191   TriggerStep *pTriggerStep;
73192
73193   assert(pEList == 0 || pSelect == 0);
73194   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
73195
73196   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
73197   if( pTriggerStep ){
73198     pTriggerStep->op = TK_INSERT;
73199     pTriggerStep->pSelect = pSelect;
73200     pTriggerStep->target  = *pTableName;
73201     pTriggerStep->pIdList = pColumn;
73202     pTriggerStep->pExprList = pEList;
73203     pTriggerStep->orconf = orconf;
73204     sqlitePersistTriggerStep(db, pTriggerStep);
73205   }else{
73206     sqlite3IdListDelete(db, pColumn);
73207     sqlite3ExprListDelete(db, pEList);
73208     sqlite3SelectDelete(db, pSelect);
73209   }
73210
73211   return pTriggerStep;
73212 }
73213
73214 /*
73215 ** Construct a trigger step that implements an UPDATE statement and return
73216 ** a pointer to that trigger step.  The parser calls this routine when it
73217 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
73218 */
73219 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
73220   sqlite3 *db,         /* The database connection */
73221   Token *pTableName,   /* Name of the table to be updated */
73222   ExprList *pEList,    /* The SET clause: list of column and new values */
73223   Expr *pWhere,        /* The WHERE clause */
73224   int orconf           /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
73225 ){
73226   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
73227   if( pTriggerStep==0 ){
73228      sqlite3ExprListDelete(db, pEList);
73229      sqlite3ExprDelete(db, pWhere);
73230      return 0;
73231   }
73232
73233   pTriggerStep->op = TK_UPDATE;
73234   pTriggerStep->target  = *pTableName;
73235   pTriggerStep->pExprList = pEList;
73236   pTriggerStep->pWhere = pWhere;
73237   pTriggerStep->orconf = orconf;
73238   sqlitePersistTriggerStep(db, pTriggerStep);
73239
73240   return pTriggerStep;
73241 }
73242
73243 /*
73244 ** Construct a trigger step that implements a DELETE statement and return
73245 ** a pointer to that trigger step.  The parser calls this routine when it
73246 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
73247 */
73248 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
73249   sqlite3 *db,            /* Database connection */
73250   Token *pTableName,      /* The table from which rows are deleted */
73251   Expr *pWhere            /* The WHERE clause */
73252 ){
73253   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
73254   if( pTriggerStep==0 ){
73255     sqlite3ExprDelete(db, pWhere);
73256     return 0;
73257   }
73258
73259   pTriggerStep->op = TK_DELETE;
73260   pTriggerStep->target  = *pTableName;
73261   pTriggerStep->pWhere = pWhere;
73262   pTriggerStep->orconf = OE_Default;
73263   sqlitePersistTriggerStep(db, pTriggerStep);
73264
73265   return pTriggerStep;
73266 }
73267
73268 /* 
73269 ** Recursively delete a Trigger structure
73270 */
73271 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
73272   if( pTrigger==0 ) return;
73273   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
73274   sqlite3DbFree(db, pTrigger->name);
73275   sqlite3DbFree(db, pTrigger->table);
73276   sqlite3ExprDelete(db, pTrigger->pWhen);
73277   sqlite3IdListDelete(db, pTrigger->pColumns);
73278   if( pTrigger->nameToken.dyn ) sqlite3DbFree(db, (char*)pTrigger->nameToken.z);
73279   sqlite3DbFree(db, pTrigger);
73280 }
73281
73282 /*
73283 ** This function is called to drop a trigger from the database schema. 
73284 **
73285 ** This may be called directly from the parser and therefore identifies
73286 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
73287 ** same job as this routine except it takes a pointer to the trigger
73288 ** instead of the trigger name.
73289 **/
73290 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
73291   Trigger *pTrigger = 0;
73292   int i;
73293   const char *zDb;
73294   const char *zName;
73295   int nName;
73296   sqlite3 *db = pParse->db;
73297
73298   if( db->mallocFailed ) goto drop_trigger_cleanup;
73299   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
73300     goto drop_trigger_cleanup;
73301   }
73302
73303   assert( pName->nSrc==1 );
73304   zDb = pName->a[0].zDatabase;
73305   zName = pName->a[0].zName;
73306   nName = strlen(zName);
73307   for(i=OMIT_TEMPDB; i<db->nDb; i++){
73308     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
73309     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
73310     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
73311     if( pTrigger ) break;
73312   }
73313   if( !pTrigger ){
73314     if( !noErr ){
73315       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
73316     }
73317     goto drop_trigger_cleanup;
73318   }
73319   sqlite3DropTriggerPtr(pParse, pTrigger);
73320
73321 drop_trigger_cleanup:
73322   sqlite3SrcListDelete(db, pName);
73323 }
73324
73325 /*
73326 ** Return a pointer to the Table structure for the table that a trigger
73327 ** is set on.
73328 */
73329 static Table *tableOfTrigger(Trigger *pTrigger){
73330   int n = strlen(pTrigger->table) + 1;
73331   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
73332 }
73333
73334
73335 /*
73336 ** Drop a trigger given a pointer to that trigger. 
73337 */
73338 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
73339   Table   *pTable;
73340   Vdbe *v;
73341   sqlite3 *db = pParse->db;
73342   int iDb;
73343
73344   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
73345   assert( iDb>=0 && iDb<db->nDb );
73346   pTable = tableOfTrigger(pTrigger);
73347   assert( pTable );
73348   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
73349 #ifndef SQLITE_OMIT_AUTHORIZATION
73350   {
73351     int code = SQLITE_DROP_TRIGGER;
73352     const char *zDb = db->aDb[iDb].zName;
73353     const char *zTab = SCHEMA_TABLE(iDb);
73354     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
73355     if( sqlite3AuthCheck(pParse, code, pTrigger->name, pTable->zName, zDb) ||
73356       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
73357       return;
73358     }
73359   }
73360 #endif
73361
73362   /* Generate code to destroy the database record of the trigger.
73363   */
73364   assert( pTable!=0 );
73365   if( (v = sqlite3GetVdbe(pParse))!=0 ){
73366     int base;
73367     static const VdbeOpList dropTrigger[] = {
73368       { OP_Rewind,     0, ADDR(9),  0},
73369       { OP_String8,    0, 1,        0}, /* 1 */
73370       { OP_Column,     0, 1,        2},
73371       { OP_Ne,         2, ADDR(8),  1},
73372       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
73373       { OP_Column,     0, 0,        2},
73374       { OP_Ne,         2, ADDR(8),  1},
73375       { OP_Delete,     0, 0,        0},
73376       { OP_Next,       0, ADDR(1),  0}, /* 8 */
73377     };
73378
73379     sqlite3BeginWriteOperation(pParse, 0, iDb);
73380     sqlite3OpenMasterTable(pParse, iDb);
73381     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
73382     sqlite3VdbeChangeP4(v, base+1, pTrigger->name, 0);
73383     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
73384     sqlite3ChangeCookie(pParse, iDb);
73385     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
73386     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->name, 0);
73387   }
73388 }
73389
73390 /*
73391 ** Remove a trigger from the hash tables of the sqlite* pointer.
73392 */
73393 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
73394   Trigger *pTrigger;
73395   int nName = strlen(zName);
73396   pTrigger = sqlite3HashInsert(&(db->aDb[iDb].pSchema->trigHash),
73397                                zName, nName, 0);
73398   if( pTrigger ){
73399     Table *pTable = tableOfTrigger(pTrigger);
73400     assert( pTable!=0 );
73401     if( pTable->pTrigger == pTrigger ){
73402       pTable->pTrigger = pTrigger->pNext;
73403     }else{
73404       Trigger *cc = pTable->pTrigger;
73405       while( cc ){ 
73406         if( cc->pNext == pTrigger ){
73407           cc->pNext = cc->pNext->pNext;
73408           break;
73409         }
73410         cc = cc->pNext;
73411       }
73412       assert(cc);
73413     }
73414     sqlite3DeleteTrigger(db, pTrigger);
73415     db->flags |= SQLITE_InternChanges;
73416   }
73417 }
73418
73419 /*
73420 ** pEList is the SET clause of an UPDATE statement.  Each entry
73421 ** in pEList is of the format <id>=<expr>.  If any of the entries
73422 ** in pEList have an <id> which matches an identifier in pIdList,
73423 ** then return TRUE.  If pIdList==NULL, then it is considered a
73424 ** wildcard that matches anything.  Likewise if pEList==NULL then
73425 ** it matches anything so always return true.  Return false only
73426 ** if there is no match.
73427 */
73428 static int checkColumnOverLap(IdList *pIdList, ExprList *pEList){
73429   int e;
73430   if( !pIdList || !pEList ) return 1;
73431   for(e=0; e<pEList->nExpr; e++){
73432     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
73433   }
73434   return 0; 
73435 }
73436
73437 /*
73438 ** Return a bit vector to indicate what kind of triggers exist for operation
73439 ** "op" on table pTab.  If pChanges is not NULL then it is a list of columns
73440 ** that are being updated.  Triggers only match if the ON clause of the
73441 ** trigger definition overlaps the set of columns being updated.
73442 **
73443 ** The returned bit vector is some combination of TRIGGER_BEFORE and
73444 ** TRIGGER_AFTER.
73445 */
73446 SQLITE_PRIVATE int sqlite3TriggersExist(
73447   Parse *pParse,          /* Used to check for recursive triggers */
73448   Table *pTab,            /* The table the contains the triggers */
73449   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
73450   ExprList *pChanges      /* Columns that change in an UPDATE statement */
73451 ){
73452   Trigger *pTrigger;
73453   int mask = 0;
73454
73455   pTrigger = IsVirtual(pTab) ? 0 : pTab->pTrigger;
73456   while( pTrigger ){
73457     if( pTrigger->op==op && checkColumnOverLap(pTrigger->pColumns, pChanges) ){
73458       mask |= pTrigger->tr_tm;
73459     }
73460     pTrigger = pTrigger->pNext;
73461   }
73462   return mask;
73463 }
73464
73465 /*
73466 ** Convert the pStep->target token into a SrcList and return a pointer
73467 ** to that SrcList.
73468 **
73469 ** This routine adds a specific database name, if needed, to the target when
73470 ** forming the SrcList.  This prevents a trigger in one database from
73471 ** referring to a target in another database.  An exception is when the
73472 ** trigger is in TEMP in which case it can refer to any other database it
73473 ** wants.
73474 */
73475 static SrcList *targetSrcList(
73476   Parse *pParse,       /* The parsing context */
73477   TriggerStep *pStep   /* The trigger containing the target token */
73478 ){
73479   Token sDb;           /* Dummy database name token */
73480   int iDb;             /* Index of the database to use */
73481   SrcList *pSrc;       /* SrcList to be returned */
73482
73483   iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
73484   if( iDb==0 || iDb>=2 ){
73485     assert( iDb<pParse->db->nDb );
73486     sDb.z = (u8*)pParse->db->aDb[iDb].zName;
73487     sDb.n = strlen((char*)sDb.z);
73488     pSrc = sqlite3SrcListAppend(pParse->db, 0, &sDb, &pStep->target);
73489   } else {
73490     pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
73491   }
73492   return pSrc;
73493 }
73494
73495 /*
73496 ** Generate VDBE code for zero or more statements inside the body of a
73497 ** trigger.  
73498 */
73499 static int codeTriggerProgram(
73500   Parse *pParse,            /* The parser context */
73501   TriggerStep *pStepList,   /* List of statements inside the trigger body */
73502   int orconfin              /* Conflict algorithm. (OE_Abort, etc) */  
73503 ){
73504   TriggerStep * pTriggerStep = pStepList;
73505   int orconf;
73506   Vdbe *v = pParse->pVdbe;
73507   sqlite3 *db = pParse->db;
73508
73509   assert( pTriggerStep!=0 );
73510   assert( v!=0 );
73511   sqlite3VdbeAddOp2(v, OP_ContextPush, 0, 0);
73512   VdbeComment((v, "begin trigger %s", pStepList->pTrig->name));
73513   while( pTriggerStep ){
73514     orconf = (orconfin == OE_Default)?pTriggerStep->orconf:orconfin;
73515     pParse->trigStack->orconf = orconf;
73516     switch( pTriggerStep->op ){
73517       case TK_SELECT: {
73518         Select *ss = sqlite3SelectDup(db, pTriggerStep->pSelect);
73519         if( ss ){
73520           SelectDest dest;
73521
73522           sqlite3SelectDestInit(&dest, SRT_Discard, 0);
73523           sqlite3Select(pParse, ss, &dest);
73524           sqlite3SelectDelete(db, ss);
73525         }
73526         break;
73527       }
73528       case TK_UPDATE: {
73529         SrcList *pSrc;
73530         pSrc = targetSrcList(pParse, pTriggerStep);
73531         sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
73532         sqlite3Update(pParse, pSrc,
73533                 sqlite3ExprListDup(db, pTriggerStep->pExprList), 
73534                 sqlite3ExprDup(db, pTriggerStep->pWhere), orconf);
73535         sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
73536         break;
73537       }
73538       case TK_INSERT: {
73539         SrcList *pSrc;
73540         pSrc = targetSrcList(pParse, pTriggerStep);
73541         sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
73542         sqlite3Insert(pParse, pSrc,
73543           sqlite3ExprListDup(db, pTriggerStep->pExprList), 
73544           sqlite3SelectDup(db, pTriggerStep->pSelect), 
73545           sqlite3IdListDup(db, pTriggerStep->pIdList), orconf);
73546         sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
73547         break;
73548       }
73549       case TK_DELETE: {
73550         SrcList *pSrc;
73551         sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
73552         pSrc = targetSrcList(pParse, pTriggerStep);
73553         sqlite3DeleteFrom(pParse, pSrc, 
73554                           sqlite3ExprDup(db, pTriggerStep->pWhere));
73555         sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
73556         break;
73557       }
73558       default:
73559         assert(0);
73560     } 
73561     pTriggerStep = pTriggerStep->pNext;
73562   }
73563   sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0);
73564   VdbeComment((v, "end trigger %s", pStepList->pTrig->name));
73565
73566   return 0;
73567 }
73568
73569 /*
73570 ** This is called to code FOR EACH ROW triggers.
73571 **
73572 ** When the code that this function generates is executed, the following 
73573 ** must be true:
73574 **
73575 ** 1. No cursors may be open in the main database.  (But newIdx and oldIdx
73576 **    can be indices of cursors in temporary tables.  See below.)
73577 **
73578 ** 2. If the triggers being coded are ON INSERT or ON UPDATE triggers, then
73579 **    a temporary vdbe cursor (index newIdx) must be open and pointing at
73580 **    a row containing values to be substituted for new.* expressions in the
73581 **    trigger program(s).
73582 **
73583 ** 3. If the triggers being coded are ON DELETE or ON UPDATE triggers, then
73584 **    a temporary vdbe cursor (index oldIdx) must be open and pointing at
73585 **    a row containing values to be substituted for old.* expressions in the
73586 **    trigger program(s).
73587 **
73588 ** If they are not NULL, the piOldColMask and piNewColMask output variables
73589 ** are set to values that describe the columns used by the trigger program
73590 ** in the OLD.* and NEW.* tables respectively. If column N of the 
73591 ** pseudo-table is read at least once, the corresponding bit of the output
73592 ** mask is set. If a column with an index greater than 32 is read, the
73593 ** output mask is set to the special value 0xffffffff.
73594 **
73595 */
73596 SQLITE_PRIVATE int sqlite3CodeRowTrigger(
73597   Parse *pParse,       /* Parse context */
73598   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
73599   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
73600   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
73601   Table *pTab,         /* The table to code triggers from */
73602   int newIdx,          /* The indice of the "new" row to access */
73603   int oldIdx,          /* The indice of the "old" row to access */
73604   int orconf,          /* ON CONFLICT policy */
73605   int ignoreJump,      /* Instruction to jump to for RAISE(IGNORE) */
73606   u32 *piOldColMask,   /* OUT: Mask of columns used from the OLD.* table */
73607   u32 *piNewColMask    /* OUT: Mask of columns used from the NEW.* table */
73608 ){
73609   Trigger *p;
73610   sqlite3 *db = pParse->db;
73611   TriggerStack trigStackEntry;
73612
73613   trigStackEntry.oldColMask = 0;
73614   trigStackEntry.newColMask = 0;
73615
73616   assert(op == TK_UPDATE || op == TK_INSERT || op == TK_DELETE);
73617   assert(tr_tm == TRIGGER_BEFORE || tr_tm == TRIGGER_AFTER );
73618
73619   assert(newIdx != -1 || oldIdx != -1);
73620
73621   for(p=pTab->pTrigger; p; p=p->pNext){
73622     int fire_this = 0;
73623
73624     /* Determine whether we should code this trigger */
73625     if( 
73626       p->op==op && 
73627       p->tr_tm==tr_tm && 
73628       (p->pSchema==p->pTabSchema || p->pSchema==db->aDb[1].pSchema) &&
73629       (op!=TK_UPDATE||!p->pColumns||checkColumnOverLap(p->pColumns,pChanges))
73630     ){
73631       TriggerStack *pS;      /* Pointer to trigger-stack entry */
73632       for(pS=pParse->trigStack; pS && p!=pS->pTrigger; pS=pS->pNext){}
73633       if( !pS ){
73634         fire_this = 1;
73635       }
73636 #if 0    /* Give no warning for recursive triggers.  Just do not do them */
73637       else{
73638         sqlite3ErrorMsg(pParse, "recursive triggers not supported (%s)",
73639             p->name);
73640         return SQLITE_ERROR;
73641       }
73642 #endif
73643     }
73644  
73645     if( fire_this ){
73646       int endTrigger;
73647       Expr * whenExpr;
73648       AuthContext sContext;
73649       NameContext sNC;
73650
73651 #ifndef SQLITE_OMIT_TRACE
73652       sqlite3VdbeAddOp4(pParse->pVdbe, OP_Trace, 0, 0, 0,
73653                         sqlite3MPrintf(db, "-- TRIGGER %s", p->name),
73654                         P4_DYNAMIC);
73655 #endif
73656       memset(&sNC, 0, sizeof(sNC));
73657       sNC.pParse = pParse;
73658
73659       /* Push an entry on to the trigger stack */
73660       trigStackEntry.pTrigger = p;
73661       trigStackEntry.newIdx = newIdx;
73662       trigStackEntry.oldIdx = oldIdx;
73663       trigStackEntry.pTab = pTab;
73664       trigStackEntry.pNext = pParse->trigStack;
73665       trigStackEntry.ignoreJump = ignoreJump;
73666       pParse->trigStack = &trigStackEntry;
73667       sqlite3AuthContextPush(pParse, &sContext, p->name);
73668
73669       /* code the WHEN clause */
73670       endTrigger = sqlite3VdbeMakeLabel(pParse->pVdbe);
73671       whenExpr = sqlite3ExprDup(db, p->pWhen);
73672       if( db->mallocFailed || sqlite3ResolveExprNames(&sNC, whenExpr) ){
73673         pParse->trigStack = trigStackEntry.pNext;
73674         sqlite3ExprDelete(db, whenExpr);
73675         return 1;
73676       }
73677       sqlite3ExprIfFalse(pParse, whenExpr, endTrigger, SQLITE_JUMPIFNULL);
73678       sqlite3ExprDelete(db, whenExpr);
73679
73680       codeTriggerProgram(pParse, p->step_list, orconf); 
73681
73682       /* Pop the entry off the trigger stack */
73683       pParse->trigStack = trigStackEntry.pNext;
73684       sqlite3AuthContextPop(&sContext);
73685
73686       sqlite3VdbeResolveLabel(pParse->pVdbe, endTrigger);
73687     }
73688   }
73689   if( piOldColMask ) *piOldColMask |= trigStackEntry.oldColMask;
73690   if( piNewColMask ) *piNewColMask |= trigStackEntry.newColMask;
73691   return 0;
73692 }
73693 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
73694
73695 /************** End of trigger.c *********************************************/
73696 /************** Begin file update.c ******************************************/
73697 /*
73698 ** 2001 September 15
73699 **
73700 ** The author disclaims copyright to this source code.  In place of
73701 ** a legal notice, here is a blessing:
73702 **
73703 **    May you do good and not evil.
73704 **    May you find forgiveness for yourself and forgive others.
73705 **    May you share freely, never taking more than you give.
73706 **
73707 *************************************************************************
73708 ** This file contains C code routines that are called by the parser
73709 ** to handle UPDATE statements.
73710 **
73711 ** $Id: update.c,v 1.184 2008/09/01 21:59:43 shane Exp $
73712 */
73713
73714 #ifndef SQLITE_OMIT_VIRTUALTABLE
73715 /* Forward declaration */
73716 static void updateVirtualTable(
73717   Parse *pParse,       /* The parsing context */
73718   SrcList *pSrc,       /* The virtual table to be modified */
73719   Table *pTab,         /* The virtual table */
73720   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
73721   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
73722   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
73723   Expr *pWhere         /* WHERE clause of the UPDATE statement */
73724 );
73725 #endif /* SQLITE_OMIT_VIRTUALTABLE */
73726
73727 /*
73728 ** The most recently coded instruction was an OP_Column to retrieve the
73729 ** i-th column of table pTab. This routine sets the P4 parameter of the 
73730 ** OP_Column to the default value, if any.
73731 **
73732 ** The default value of a column is specified by a DEFAULT clause in the 
73733 ** column definition. This was either supplied by the user when the table
73734 ** was created, or added later to the table definition by an ALTER TABLE
73735 ** command. If the latter, then the row-records in the table btree on disk
73736 ** may not contain a value for the column and the default value, taken
73737 ** from the P4 parameter of the OP_Column instruction, is returned instead.
73738 ** If the former, then all row-records are guaranteed to include a value
73739 ** for the column and the P4 value is not required.
73740 **
73741 ** Column definitions created by an ALTER TABLE command may only have 
73742 ** literal default values specified: a number, null or a string. (If a more
73743 ** complicated default expression value was provided, it is evaluated 
73744 ** when the ALTER TABLE is executed and one of the literal values written
73745 ** into the sqlite_master table.)
73746 **
73747 ** Therefore, the P4 parameter is only required if the default value for
73748 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
73749 ** function is capable of transforming these types of expressions into
73750 ** sqlite3_value objects.
73751 */
73752 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i){
73753   if( pTab && !pTab->pSelect ){
73754     sqlite3_value *pValue;
73755     u8 enc = ENC(sqlite3VdbeDb(v));
73756     Column *pCol = &pTab->aCol[i];
73757     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
73758     assert( i<pTab->nCol );
73759     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, 
73760                          pCol->affinity, &pValue);
73761     if( pValue ){
73762       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
73763     }
73764   }
73765 }
73766
73767 /*
73768 ** Process an UPDATE statement.
73769 **
73770 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
73771 **          \_______/ \________/     \______/       \________________/
73772 *            onError   pTabList      pChanges             pWhere
73773 */
73774 SQLITE_PRIVATE void sqlite3Update(
73775   Parse *pParse,         /* The parser context */
73776   SrcList *pTabList,     /* The table in which we should change things */
73777   ExprList *pChanges,    /* Things to be changed */
73778   Expr *pWhere,          /* The WHERE clause.  May be null */
73779   int onError            /* How to handle constraint errors */
73780 ){
73781   int i, j;              /* Loop counters */
73782   Table *pTab;           /* The table to be updated */
73783   int addr = 0;          /* VDBE instruction address of the start of the loop */
73784   WhereInfo *pWInfo;     /* Information about the WHERE clause */
73785   Vdbe *v;               /* The virtual database engine */
73786   Index *pIdx;           /* For looping over indices */
73787   int nIdx;              /* Number of indices that need updating */
73788   int iCur;              /* VDBE Cursor number of pTab */
73789   sqlite3 *db;           /* The database structure */
73790   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
73791   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
73792                          ** an expression for the i-th column of the table.
73793                          ** aXRef[i]==-1 if the i-th column is not changed. */
73794   int chngRowid;         /* True if the record number is being changed */
73795   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
73796   int openAll = 0;       /* True if all indices need to be opened */
73797   AuthContext sContext;  /* The authorization context */
73798   NameContext sNC;       /* The name-context to resolve expressions in */
73799   int iDb;               /* Database containing the table being updated */
73800   int j1;                /* Addresses of jump instructions */
73801   int okOnePass;         /* True for one-pass algorithm without the FIFO */
73802
73803 #ifndef SQLITE_OMIT_TRIGGER
73804   int isView;                  /* Trying to update a view */
73805   int triggers_exist = 0;      /* True if any row triggers exist */
73806 #endif
73807   int iBeginAfterTrigger;      /* Address of after trigger program */
73808   int iEndAfterTrigger;        /* Exit of after trigger program */
73809   int iBeginBeforeTrigger;     /* Address of before trigger program */
73810   int iEndBeforeTrigger;       /* Exit of before trigger program */
73811   u32 old_col_mask = 0;        /* Mask of OLD.* columns in use */
73812   u32 new_col_mask = 0;        /* Mask of NEW.* columns in use */
73813
73814   int newIdx      = -1;  /* index of trigger "new" temp table       */
73815   int oldIdx      = -1;  /* index of trigger "old" temp table       */
73816
73817   /* Register Allocations */
73818   int regRowCount = 0;   /* A count of rows changed */
73819   int regOldRowid;       /* The old rowid */
73820   int regNewRowid;       /* The new rowid */
73821   int regData;           /* New data for the row */
73822
73823   sContext.pParse = 0;
73824   db = pParse->db;
73825   if( pParse->nErr || db->mallocFailed ){
73826     goto update_cleanup;
73827   }
73828   assert( pTabList->nSrc==1 );
73829
73830   /* Locate the table which we want to update. 
73831   */
73832   pTab = sqlite3SrcListLookup(pParse, pTabList);
73833   if( pTab==0 ) goto update_cleanup;
73834   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
73835
73836   /* Figure out if we have any triggers and if the table being
73837   ** updated is a view
73838   */
73839 #ifndef SQLITE_OMIT_TRIGGER
73840   triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges);
73841   isView = pTab->pSelect!=0;
73842 #else
73843 # define triggers_exist 0
73844 # define isView 0
73845 #endif
73846 #ifdef SQLITE_OMIT_VIEW
73847 # undef isView
73848 # define isView 0
73849 #endif
73850
73851   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
73852     goto update_cleanup;
73853   }
73854   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
73855     goto update_cleanup;
73856   }
73857   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
73858   if( aXRef==0 ) goto update_cleanup;
73859   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
73860
73861   /* If there are FOR EACH ROW triggers, allocate cursors for the
73862   ** special OLD and NEW tables
73863   */
73864   if( triggers_exist ){
73865     newIdx = pParse->nTab++;
73866     oldIdx = pParse->nTab++;
73867   }
73868
73869   /* Allocate a cursors for the main database table and for all indices.
73870   ** The index cursors might not be used, but if they are used they
73871   ** need to occur right after the database cursor.  So go ahead and
73872   ** allocate enough space, just in case.
73873   */
73874   pTabList->a[0].iCursor = iCur = pParse->nTab++;
73875   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
73876     pParse->nTab++;
73877   }
73878
73879   /* Initialize the name-context */
73880   memset(&sNC, 0, sizeof(sNC));
73881   sNC.pParse = pParse;
73882   sNC.pSrcList = pTabList;
73883
73884   /* Resolve the column names in all the expressions of the
73885   ** of the UPDATE statement.  Also find the column index
73886   ** for each column to be updated in the pChanges array.  For each
73887   ** column to be updated, make sure we have authorization to change
73888   ** that column.
73889   */
73890   chngRowid = 0;
73891   for(i=0; i<pChanges->nExpr; i++){
73892     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
73893       goto update_cleanup;
73894     }
73895     for(j=0; j<pTab->nCol; j++){
73896       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
73897         if( j==pTab->iPKey ){
73898           chngRowid = 1;
73899           pRowidExpr = pChanges->a[i].pExpr;
73900         }
73901         aXRef[j] = i;
73902         break;
73903       }
73904     }
73905     if( j>=pTab->nCol ){
73906       if( sqlite3IsRowid(pChanges->a[i].zName) ){
73907         chngRowid = 1;
73908         pRowidExpr = pChanges->a[i].pExpr;
73909       }else{
73910         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
73911         goto update_cleanup;
73912       }
73913     }
73914 #ifndef SQLITE_OMIT_AUTHORIZATION
73915     {
73916       int rc;
73917       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
73918                            pTab->aCol[j].zName, db->aDb[iDb].zName);
73919       if( rc==SQLITE_DENY ){
73920         goto update_cleanup;
73921       }else if( rc==SQLITE_IGNORE ){
73922         aXRef[j] = -1;
73923       }
73924     }
73925 #endif
73926   }
73927
73928   /* Allocate memory for the array aRegIdx[].  There is one entry in the
73929   ** array for each index associated with table being updated.  Fill in
73930   ** the value with a register number for indices that are to be used
73931   ** and with zero for unused indices.
73932   */
73933   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
73934   if( nIdx>0 ){
73935     aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
73936     if( aRegIdx==0 ) goto update_cleanup;
73937   }
73938   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
73939     int reg;
73940     if( chngRowid ){
73941       reg = ++pParse->nMem;
73942     }else{
73943       reg = 0;
73944       for(i=0; i<pIdx->nColumn; i++){
73945         if( aXRef[pIdx->aiColumn[i]]>=0 ){
73946           reg = ++pParse->nMem;
73947           break;
73948         }
73949       }
73950     }
73951     aRegIdx[j] = reg;
73952   }
73953
73954   /* Allocate a block of register used to store the change record
73955   ** sent to sqlite3GenerateConstraintChecks().  There are either
73956   ** one or two registers for holding the rowid.  One rowid register
73957   ** is used if chngRowid is false and two are used if chngRowid is
73958   ** true.  Following these are pTab->nCol register holding column
73959   ** data.
73960   */
73961   regOldRowid = regNewRowid = pParse->nMem + 1;
73962   pParse->nMem += pTab->nCol + 1;
73963   if( chngRowid ){
73964     regNewRowid++;
73965     pParse->nMem++;
73966   }
73967   regData = regNewRowid+1;
73968  
73969
73970   /* Begin generating code.
73971   */
73972   v = sqlite3GetVdbe(pParse);
73973   if( v==0 ) goto update_cleanup;
73974   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
73975   sqlite3BeginWriteOperation(pParse, 1, iDb);
73976
73977 #ifndef SQLITE_OMIT_VIRTUALTABLE
73978   /* Virtual tables must be handled separately */
73979   if( IsVirtual(pTab) ){
73980     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
73981                        pWhere);
73982     pWhere = 0;
73983     pTabList = 0;
73984     goto update_cleanup;
73985   }
73986 #endif
73987
73988   /* Start the view context
73989   */
73990   if( isView ){
73991     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
73992   }
73993
73994   /* Generate the code for triggers.
73995   */
73996   if( triggers_exist ){
73997     int iGoto;
73998
73999     /* Create pseudo-tables for NEW and OLD
74000     */
74001     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
74002     sqlite3VdbeAddOp2(v, OP_OpenPseudo, oldIdx, 0);
74003     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
74004     sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0);
74005
74006     iGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
74007     addr = sqlite3VdbeMakeLabel(v);
74008     iBeginBeforeTrigger = sqlite3VdbeCurrentAddr(v);
74009     if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_BEFORE, pTab,
74010           newIdx, oldIdx, onError, addr, &old_col_mask, &new_col_mask) ){
74011       goto update_cleanup;
74012     }
74013     iEndBeforeTrigger = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
74014     iBeginAfterTrigger = sqlite3VdbeCurrentAddr(v);
74015     if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_AFTER, pTab, 
74016           newIdx, oldIdx, onError, addr, &old_col_mask, &new_col_mask) ){
74017       goto update_cleanup;
74018     }
74019     iEndAfterTrigger = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
74020     sqlite3VdbeJumpHere(v, iGoto);
74021   }
74022
74023   /* If we are trying to update a view, realize that view into
74024   ** a ephemeral table.
74025   */
74026 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
74027   if( isView ){
74028     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
74029   }
74030 #endif
74031
74032   /* Resolve the column names in all the expressions in the
74033   ** WHERE clause.
74034   */
74035   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
74036     goto update_cleanup;
74037   }
74038
74039   /* Begin the database scan
74040   */
74041   sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
74042   pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0,
74043                              WHERE_ONEPASS_DESIRED);
74044   if( pWInfo==0 ) goto update_cleanup;
74045   okOnePass = pWInfo->okOnePass;
74046
74047   /* Remember the rowid of every item to be updated.
74048   */
74049   sqlite3VdbeAddOp2(v, IsVirtual(pTab)?OP_VRowid:OP_Rowid, iCur, regOldRowid);
74050   if( !okOnePass ) sqlite3VdbeAddOp2(v, OP_FifoWrite, regOldRowid, 0);
74051
74052   /* End the database scan loop.
74053   */
74054   sqlite3WhereEnd(pWInfo);
74055
74056   /* Initialize the count of updated rows
74057   */
74058   if( db->flags & SQLITE_CountRows && !pParse->trigStack ){
74059     regRowCount = ++pParse->nMem;
74060     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
74061   }
74062
74063   if( !isView && !IsVirtual(pTab) ){
74064     /* 
74065     ** Open every index that needs updating.  Note that if any
74066     ** index could potentially invoke a REPLACE conflict resolution 
74067     ** action, then we need to open all indices because we might need
74068     ** to be deleting some records.
74069     */
74070     if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); 
74071     if( onError==OE_Replace ){
74072       openAll = 1;
74073     }else{
74074       openAll = 0;
74075       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
74076         if( pIdx->onError==OE_Replace ){
74077           openAll = 1;
74078           break;
74079         }
74080       }
74081     }
74082     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
74083       if( openAll || aRegIdx[i]>0 ){
74084         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
74085         sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
74086                        (char*)pKey, P4_KEYINFO_HANDOFF);
74087         assert( pParse->nTab>iCur+i+1 );
74088       }
74089     }
74090   }
74091   
74092   /* Jump back to this point if a trigger encounters an IGNORE constraint. */
74093   if( triggers_exist ){
74094     sqlite3VdbeResolveLabel(v, addr);
74095   }
74096
74097   /* Top of the update loop */
74098   if( okOnePass ){
74099     int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
74100     addr = sqlite3VdbeAddOp0(v, OP_Goto);
74101     sqlite3VdbeJumpHere(v, a1);
74102   }else{
74103     addr = sqlite3VdbeAddOp2(v, OP_FifoRead, regOldRowid, 0);
74104   }
74105
74106   if( triggers_exist ){
74107     int regRowid;
74108     int regRow;
74109     int regCols;
74110
74111     /* Make cursor iCur point to the record that is being updated.
74112     */
74113     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
74114
74115     /* Generate the OLD table
74116     */
74117     regRowid = sqlite3GetTempReg(pParse);
74118     regRow = sqlite3GetTempReg(pParse);
74119     sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regRowid);
74120     if( !old_col_mask ){
74121       sqlite3VdbeAddOp2(v, OP_Null, 0, regRow);
74122     }else{
74123       sqlite3VdbeAddOp2(v, OP_RowData, iCur, regRow);
74124     }
74125     sqlite3VdbeAddOp3(v, OP_Insert, oldIdx, regRow, regRowid);
74126
74127     /* Generate the NEW table
74128     */
74129     if( chngRowid ){
74130       sqlite3ExprCodeAndCache(pParse, pRowidExpr, regRowid);
74131     }else{
74132       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regRowid);
74133     }
74134     regCols = sqlite3GetTempRange(pParse, pTab->nCol);
74135     for(i=0; i<pTab->nCol; i++){
74136       if( i==pTab->iPKey ){
74137         sqlite3VdbeAddOp2(v, OP_Null, 0, regCols+i);
74138         continue;
74139       }
74140       j = aXRef[i];
74141       if( new_col_mask&((u32)1<<i) || new_col_mask==0xffffffff ){
74142         if( j<0 ){
74143           sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regCols+i);
74144           sqlite3ColumnDefault(v, pTab, i);
74145         }else{
74146           sqlite3ExprCodeAndCache(pParse, pChanges->a[j].pExpr, regCols+i);
74147         }
74148       }else{
74149         sqlite3VdbeAddOp2(v, OP_Null, 0, regCols+i);
74150       }
74151     }
74152     sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRow);
74153     if( !isView ){
74154       sqlite3TableAffinityStr(v, pTab);
74155       sqlite3ExprCacheAffinityChange(pParse, regCols, pTab->nCol);
74156     }
74157     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol);
74158     /* if( pParse->nErr ) goto update_cleanup; */
74159     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRow, regRowid);
74160     sqlite3ReleaseTempReg(pParse, regRowid);
74161     sqlite3ReleaseTempReg(pParse, regRow);
74162
74163     sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginBeforeTrigger);
74164     sqlite3VdbeJumpHere(v, iEndBeforeTrigger);
74165   }
74166
74167   if( !isView && !IsVirtual(pTab) ){
74168     /* Loop over every record that needs updating.  We have to load
74169     ** the old data for each record to be updated because some columns
74170     ** might not change and we will need to copy the old value.
74171     ** Also, the old data is needed to delete the old index entries.
74172     ** So make the cursor point at the old record.
74173     */
74174     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
74175
74176     /* If the record number will change, push the record number as it
74177     ** will be after the update. (The old record number is currently
74178     ** on top of the stack.)
74179     */
74180     if( chngRowid ){
74181       sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
74182       sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
74183     }
74184
74185     /* Compute new data for this record.  
74186     */
74187     for(i=0; i<pTab->nCol; i++){
74188       if( i==pTab->iPKey ){
74189         sqlite3VdbeAddOp2(v, OP_Null, 0, regData+i);
74190         continue;
74191       }
74192       j = aXRef[i];
74193       if( j<0 ){
74194         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regData+i);
74195         sqlite3ColumnDefault(v, pTab, i);
74196       }else{
74197         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regData+i);
74198       }
74199     }
74200
74201     /* Do constraint checks
74202     */
74203     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
74204                                     aRegIdx, chngRowid, 1,
74205                                     onError, addr);
74206
74207     /* Delete the old indices for the current record.
74208     */
74209     j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
74210     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
74211
74212     /* If changing the record number, delete the old record.
74213     */
74214     if( chngRowid ){
74215       sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
74216     }
74217     sqlite3VdbeJumpHere(v, j1);
74218
74219     /* Create the new index entries and the new record.
74220     */
74221     sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, 
74222                              aRegIdx, chngRowid, 1, -1, 0);
74223   }
74224
74225   /* Increment the row counter 
74226   */
74227   if( db->flags & SQLITE_CountRows && !pParse->trigStack){
74228     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
74229   }
74230
74231   /* If there are triggers, close all the cursors after each iteration
74232   ** through the loop.  The fire the after triggers.
74233   */
74234   if( triggers_exist ){
74235     sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginAfterTrigger);
74236     sqlite3VdbeJumpHere(v, iEndAfterTrigger);
74237   }
74238
74239   /* Repeat the above with the next record to be updated, until
74240   ** all record selected by the WHERE clause have been updated.
74241   */
74242   sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
74243   sqlite3VdbeJumpHere(v, addr);
74244
74245   /* Close all tables */
74246   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
74247     if( openAll || aRegIdx[i]>0 ){
74248       sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
74249     }
74250   }
74251   sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
74252   if( triggers_exist ){
74253     sqlite3VdbeAddOp2(v, OP_Close, newIdx, 0);
74254     sqlite3VdbeAddOp2(v, OP_Close, oldIdx, 0);
74255   }
74256
74257   /*
74258   ** Return the number of rows that were changed. If this routine is 
74259   ** generating code because of a call to sqlite3NestedParse(), do not
74260   ** invoke the callback function.
74261   */
74262   if( db->flags & SQLITE_CountRows && !pParse->trigStack && pParse->nested==0 ){
74263     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
74264     sqlite3VdbeSetNumCols(v, 1);
74265     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", P4_STATIC);
74266   }
74267
74268 update_cleanup:
74269   sqlite3AuthContextPop(&sContext);
74270   sqlite3DbFree(db, aRegIdx);
74271   sqlite3DbFree(db, aXRef);
74272   sqlite3SrcListDelete(db, pTabList);
74273   sqlite3ExprListDelete(db, pChanges);
74274   sqlite3ExprDelete(db, pWhere);
74275   return;
74276 }
74277
74278 #ifndef SQLITE_OMIT_VIRTUALTABLE
74279 /*
74280 ** Generate code for an UPDATE of a virtual table.
74281 **
74282 ** The strategy is that we create an ephemerial table that contains
74283 ** for each row to be changed:
74284 **
74285 **   (A)  The original rowid of that row.
74286 **   (B)  The revised rowid for the row. (note1)
74287 **   (C)  The content of every column in the row.
74288 **
74289 ** Then we loop over this ephemeral table and for each row in
74290 ** the ephermeral table call VUpdate.
74291 **
74292 ** When finished, drop the ephemeral table.
74293 **
74294 ** (note1) Actually, if we know in advance that (A) is always the same
74295 ** as (B) we only store (A), then duplicate (A) when pulling
74296 ** it out of the ephemeral table before calling VUpdate.
74297 */
74298 static void updateVirtualTable(
74299   Parse *pParse,       /* The parsing context */
74300   SrcList *pSrc,       /* The virtual table to be modified */
74301   Table *pTab,         /* The virtual table */
74302   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
74303   Expr *pRowid,        /* Expression used to recompute the rowid */
74304   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
74305   Expr *pWhere         /* WHERE clause of the UPDATE statement */
74306 ){
74307   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
74308   ExprList *pEList = 0;     /* The result set of the SELECT statement */
74309   Select *pSelect = 0;      /* The SELECT statement */
74310   Expr *pExpr;              /* Temporary expression */
74311   int ephemTab;             /* Table holding the result of the SELECT */
74312   int i;                    /* Loop counter */
74313   int addr;                 /* Address of top of loop */
74314   int iReg;                 /* First register in set passed to OP_VUpdate */
74315   sqlite3 *db = pParse->db; /* Database connection */
74316   const char *pVtab = (const char*)pTab->pVtab;
74317   SelectDest dest;
74318
74319   /* Construct the SELECT statement that will find the new values for
74320   ** all updated rows. 
74321   */
74322   pEList = sqlite3ExprListAppend(pParse, 0, 
74323                                  sqlite3CreateIdExpr(pParse, "_rowid_"), 0);
74324   if( pRowid ){
74325     pEList = sqlite3ExprListAppend(pParse, pEList,
74326                                    sqlite3ExprDup(db, pRowid), 0);
74327   }
74328   assert( pTab->iPKey<0 );
74329   for(i=0; i<pTab->nCol; i++){
74330     if( aXRef[i]>=0 ){
74331       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr);
74332     }else{
74333       pExpr = sqlite3CreateIdExpr(pParse, pTab->aCol[i].zName);
74334     }
74335     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr, 0);
74336   }
74337   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
74338   
74339   /* Create the ephemeral table into which the update results will
74340   ** be stored.
74341   */
74342   assert( v );
74343   ephemTab = pParse->nTab++;
74344   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
74345
74346   /* fill the ephemeral table 
74347   */
74348   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
74349   sqlite3Select(pParse, pSelect, &dest);
74350
74351   /* Generate code to scan the ephemeral table and call VUpdate. */
74352   iReg = ++pParse->nMem;
74353   pParse->nMem += pTab->nCol+1;
74354   sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
74355   addr = sqlite3VdbeCurrentAddr(v);
74356   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
74357   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
74358   for(i=0; i<pTab->nCol; i++){
74359     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
74360   }
74361   sqlite3VtabMakeWritable(pParse, pTab);
74362   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVtab, P4_VTAB);
74363   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr);
74364   sqlite3VdbeJumpHere(v, addr-1);
74365   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
74366
74367   /* Cleanup */
74368   sqlite3SelectDelete(db, pSelect);  
74369 }
74370 #endif /* SQLITE_OMIT_VIRTUALTABLE */
74371
74372 /* Make sure "isView" gets undefined in case this file becomes part of
74373 ** the amalgamation - so that subsequent files do not see isView as a
74374 ** macro. */
74375 #undef isView
74376
74377 /************** End of update.c **********************************************/
74378 /************** Begin file vacuum.c ******************************************/
74379 /*
74380 ** 2003 April 6
74381 **
74382 ** The author disclaims copyright to this source code.  In place of
74383 ** a legal notice, here is a blessing:
74384 **
74385 **    May you do good and not evil.
74386 **    May you find forgiveness for yourself and forgive others.
74387 **    May you share freely, never taking more than you give.
74388 **
74389 *************************************************************************
74390 ** This file contains code used to implement the VACUUM command.
74391 **
74392 ** Most of the code in this file may be omitted by defining the
74393 ** SQLITE_OMIT_VACUUM macro.
74394 **
74395 ** $Id: vacuum.c,v 1.83 2008/08/26 21:07:27 drh Exp $
74396 */
74397
74398 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
74399 /*
74400 ** Execute zSql on database db. Return an error code.
74401 */
74402 static int execSql(sqlite3 *db, const char *zSql){
74403   sqlite3_stmt *pStmt;
74404   if( !zSql ){
74405     return SQLITE_NOMEM;
74406   }
74407   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
74408     return sqlite3_errcode(db);
74409   }
74410   while( SQLITE_ROW==sqlite3_step(pStmt) ){}
74411   return sqlite3_finalize(pStmt);
74412 }
74413
74414 /*
74415 ** Execute zSql on database db. The statement returns exactly
74416 ** one column. Execute this as SQL on the same database.
74417 */
74418 static int execExecSql(sqlite3 *db, const char *zSql){
74419   sqlite3_stmt *pStmt;
74420   int rc;
74421
74422   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
74423   if( rc!=SQLITE_OK ) return rc;
74424
74425   while( SQLITE_ROW==sqlite3_step(pStmt) ){
74426     rc = execSql(db, (char*)sqlite3_column_text(pStmt, 0));
74427     if( rc!=SQLITE_OK ){
74428       sqlite3_finalize(pStmt);
74429       return rc;
74430     }
74431   }
74432
74433   return sqlite3_finalize(pStmt);
74434 }
74435
74436 /*
74437 ** The non-standard VACUUM command is used to clean up the database,
74438 ** collapse free space, etc.  It is modelled after the VACUUM command
74439 ** in PostgreSQL.
74440 **
74441 ** In version 1.0.x of SQLite, the VACUUM command would call
74442 ** gdbm_reorganize() on all the database tables.  But beginning
74443 ** with 2.0.0, SQLite no longer uses GDBM so this command has
74444 ** become a no-op.
74445 */
74446 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
74447   Vdbe *v = sqlite3GetVdbe(pParse);
74448   if( v ){
74449     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
74450   }
74451   return;
74452 }
74453
74454 /*
74455 ** This routine implements the OP_Vacuum opcode of the VDBE.
74456 */
74457 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
74458   int rc = SQLITE_OK;     /* Return code from service routines */
74459   Btree *pMain;           /* The database being vacuumed */
74460   Pager *pMainPager;      /* Pager for database being vacuumed */
74461   Btree *pTemp;           /* The temporary database we vacuum into */
74462   char *zSql = 0;         /* SQL statements */
74463   int saved_flags;        /* Saved value of the db->flags */
74464   int saved_nChange;      /* Saved value of db->nChange */
74465   int saved_nTotalChange; /* Saved value of db->nTotalChange */
74466   Db *pDb = 0;            /* Database to detach at end of vacuum */
74467   int isMemDb;            /* True is vacuuming a :memory: database */
74468   int nRes;
74469
74470   /* Save the current value of the write-schema flag before setting it. */
74471   saved_flags = db->flags;
74472   saved_nChange = db->nChange;
74473   saved_nTotalChange = db->nTotalChange;
74474   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
74475
74476   if( !db->autoCommit ){
74477     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
74478     rc = SQLITE_ERROR;
74479     goto end_of_vacuum;
74480   }
74481   pMain = db->aDb[0].pBt;
74482   pMainPager = sqlite3BtreePager(pMain);
74483   isMemDb = sqlite3PagerFile(pMainPager)->pMethods==0;
74484
74485   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
74486   ** can be set to 'off' for this file, as it is not recovered if a crash
74487   ** occurs anyway. The integrity of the database is maintained by a
74488   ** (possibly synchronous) transaction opened on the main database before
74489   ** sqlite3BtreeCopyFile() is called.
74490   **
74491   ** An optimisation would be to use a non-journaled pager.
74492   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
74493   ** that actually made the VACUUM run slower.  Very little journalling
74494   ** actually occurs when doing a vacuum since the vacuum_db is initially
74495   ** empty.  Only the journal header is written.  Apparently it takes more
74496   ** time to parse and run the PRAGMA to turn journalling off than it does
74497   ** to write the journal header file.
74498   */
74499   zSql = "ATTACH '' AS vacuum_db;";
74500   rc = execSql(db, zSql);
74501   if( rc!=SQLITE_OK ) goto end_of_vacuum;
74502   pDb = &db->aDb[db->nDb-1];
74503   assert( strcmp(db->aDb[db->nDb-1].zName,"vacuum_db")==0 );
74504   pTemp = db->aDb[db->nDb-1].pBt;
74505
74506   nRes = sqlite3BtreeGetReserve(pMain);
74507
74508   /* A VACUUM cannot change the pagesize of an encrypted database. */
74509 #ifdef SQLITE_HAS_CODEC
74510   if( db->nextPagesize ){
74511     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
74512     int nKey;
74513     char *zKey;
74514     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
74515     if( nKey ) db->nextPagesize = 0;
74516   }
74517 #endif
74518
74519   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes)
74520    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes))
74521    || db->mallocFailed 
74522   ){
74523     rc = SQLITE_NOMEM;
74524     goto end_of_vacuum;
74525   }
74526   rc = execSql(db, "PRAGMA vacuum_db.synchronous=OFF");
74527   if( rc!=SQLITE_OK ){
74528     goto end_of_vacuum;
74529   }
74530
74531 #ifndef SQLITE_OMIT_AUTOVACUUM
74532   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
74533                                            sqlite3BtreeGetAutoVacuum(pMain));
74534 #endif
74535
74536   /* Begin a transaction */
74537   rc = execSql(db, "BEGIN EXCLUSIVE;");
74538   if( rc!=SQLITE_OK ) goto end_of_vacuum;
74539
74540   /* Query the schema of the main database. Create a mirror schema
74541   ** in the temporary database.
74542   */
74543   rc = execExecSql(db, 
74544       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
74545       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
74546       "   AND rootpage>0"
74547   );
74548   if( rc!=SQLITE_OK ) goto end_of_vacuum;
74549   rc = execExecSql(db, 
74550       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
74551       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
74552   if( rc!=SQLITE_OK ) goto end_of_vacuum;
74553   rc = execExecSql(db, 
74554       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
74555       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
74556   if( rc!=SQLITE_OK ) goto end_of_vacuum;
74557
74558   /* Loop through the tables in the main database. For each, do
74559   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM xxx;" to copy
74560   ** the contents to the temporary database.
74561   */
74562   rc = execExecSql(db, 
74563       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
74564       "|| ' SELECT * FROM ' || quote(name) || ';'"
74565       "FROM sqlite_master "
74566       "WHERE type = 'table' AND name!='sqlite_sequence' "
74567       "  AND rootpage>0"
74568
74569   );
74570   if( rc!=SQLITE_OK ) goto end_of_vacuum;
74571
74572   /* Copy over the sequence table
74573   */
74574   rc = execExecSql(db, 
74575       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
74576       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
74577   );
74578   if( rc!=SQLITE_OK ) goto end_of_vacuum;
74579   rc = execExecSql(db, 
74580       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
74581       "|| ' SELECT * FROM ' || quote(name) || ';' "
74582       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
74583   );
74584   if( rc!=SQLITE_OK ) goto end_of_vacuum;
74585
74586
74587   /* Copy the triggers, views, and virtual tables from the main database
74588   ** over to the temporary database.  None of these objects has any
74589   ** associated storage, so all we have to do is copy their entries
74590   ** from the SQLITE_MASTER table.
74591   */
74592   rc = execSql(db,
74593       "INSERT INTO vacuum_db.sqlite_master "
74594       "  SELECT type, name, tbl_name, rootpage, sql"
74595       "    FROM sqlite_master"
74596       "   WHERE type='view' OR type='trigger'"
74597       "      OR (type='table' AND rootpage=0)"
74598   );
74599   if( rc ) goto end_of_vacuum;
74600
74601   /* At this point, unless the main db was completely empty, there is now a
74602   ** transaction open on the vacuum database, but not on the main database.
74603   ** Open a btree level transaction on the main database. This allows a
74604   ** call to sqlite3BtreeCopyFile(). The main database btree level
74605   ** transaction is then committed, so the SQL level never knows it was
74606   ** opened for writing. This way, the SQL transaction used to create the
74607   ** temporary database never needs to be committed.
74608   */
74609   if( rc==SQLITE_OK ){
74610     u32 meta;
74611     int i;
74612
74613     /* This array determines which meta meta values are preserved in the
74614     ** vacuum.  Even entries are the meta value number and odd entries
74615     ** are an increment to apply to the meta value after the vacuum.
74616     ** The increment is used to increase the schema cookie so that other
74617     ** connections to the same database will know to reread the schema.
74618     */
74619     static const unsigned char aCopy[] = {
74620        1, 1,    /* Add one to the old schema cookie */
74621        3, 0,    /* Preserve the default page cache size */
74622        5, 0,    /* Preserve the default text encoding */
74623        6, 0,    /* Preserve the user version */
74624     };
74625
74626     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
74627     assert( 1==sqlite3BtreeIsInTrans(pMain) );
74628
74629     /* Copy Btree meta values */
74630     for(i=0; i<sizeof(aCopy)/sizeof(aCopy[0]); i+=2){
74631       rc = sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
74632       if( rc!=SQLITE_OK ) goto end_of_vacuum;
74633       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
74634       if( rc!=SQLITE_OK ) goto end_of_vacuum;
74635     }
74636
74637     rc = sqlite3BtreeCopyFile(pMain, pTemp);
74638     if( rc!=SQLITE_OK ) goto end_of_vacuum;
74639     rc = sqlite3BtreeCommit(pTemp);
74640     if( rc!=SQLITE_OK ) goto end_of_vacuum;
74641 #ifndef SQLITE_OMIT_AUTOVACUUM
74642     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
74643 #endif
74644     rc = sqlite3BtreeCommit(pMain);
74645   }
74646
74647   if( rc==SQLITE_OK ){
74648     rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes);
74649   }
74650
74651 end_of_vacuum:
74652   /* Restore the original value of db->flags */
74653   db->flags = saved_flags;
74654   db->nChange = saved_nChange;
74655   db->nTotalChange = saved_nTotalChange;
74656
74657   /* Currently there is an SQL level transaction open on the vacuum
74658   ** database. No locks are held on any other files (since the main file
74659   ** was committed at the btree level). So it safe to end the transaction
74660   ** by manually setting the autoCommit flag to true and detaching the
74661   ** vacuum database. The vacuum_db journal file is deleted when the pager
74662   ** is closed by the DETACH.
74663   */
74664   db->autoCommit = 1;
74665
74666   if( pDb ){
74667     sqlite3BtreeClose(pDb->pBt);
74668     pDb->pBt = 0;
74669     pDb->pSchema = 0;
74670   }
74671
74672   sqlite3ResetInternalSchema(db, 0);
74673
74674   return rc;
74675 }
74676 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
74677
74678 /************** End of vacuum.c **********************************************/
74679 /************** Begin file vtab.c ********************************************/
74680 /*
74681 ** 2006 June 10
74682 **
74683 ** The author disclaims copyright to this source code.  In place of
74684 ** a legal notice, here is a blessing:
74685 **
74686 **    May you do good and not evil.
74687 **    May you find forgiveness for yourself and forgive others.
74688 **    May you share freely, never taking more than you give.
74689 **
74690 *************************************************************************
74691 ** This file contains code used to help implement virtual tables.
74692 **
74693 ** $Id: vtab.c,v 1.76 2008/08/20 16:35:10 drh Exp $
74694 */
74695 #ifndef SQLITE_OMIT_VIRTUALTABLE
74696
74697 static int createModule(
74698   sqlite3 *db,                    /* Database in which module is registered */
74699   const char *zName,              /* Name assigned to this module */
74700   const sqlite3_module *pModule,  /* The definition of the module */
74701   void *pAux,                     /* Context pointer for xCreate/xConnect */
74702   void (*xDestroy)(void *)        /* Module destructor function */
74703 ) {
74704   int rc, nName;
74705   Module *pMod;
74706
74707   sqlite3_mutex_enter(db->mutex);
74708   nName = strlen(zName);
74709   pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
74710   if( pMod ){
74711     Module *pDel;
74712     char *zCopy = (char *)(&pMod[1]);
74713     memcpy(zCopy, zName, nName+1);
74714     pMod->zName = zCopy;
74715     pMod->pModule = pModule;
74716     pMod->pAux = pAux;
74717     pMod->xDestroy = xDestroy;
74718     pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
74719     if( pDel && pDel->xDestroy ){
74720       pDel->xDestroy(pDel->pAux);
74721     }
74722     sqlite3DbFree(db, pDel);
74723     if( pDel==pMod ){
74724       db->mallocFailed = 1;
74725     }
74726     sqlite3ResetInternalSchema(db, 0);
74727   }
74728   rc = sqlite3ApiExit(db, SQLITE_OK);
74729   sqlite3_mutex_leave(db->mutex);
74730   return rc;
74731 }
74732
74733
74734 /*
74735 ** External API function used to create a new virtual-table module.
74736 */
74737 SQLITE_API int sqlite3_create_module(
74738   sqlite3 *db,                    /* Database in which module is registered */
74739   const char *zName,              /* Name assigned to this module */
74740   const sqlite3_module *pModule,  /* The definition of the module */
74741   void *pAux                      /* Context pointer for xCreate/xConnect */
74742 ){
74743   return createModule(db, zName, pModule, pAux, 0);
74744 }
74745
74746 /*
74747 ** External API function used to create a new virtual-table module.
74748 */
74749 SQLITE_API int sqlite3_create_module_v2(
74750   sqlite3 *db,                    /* Database in which module is registered */
74751   const char *zName,              /* Name assigned to this module */
74752   const sqlite3_module *pModule,  /* The definition of the module */
74753   void *pAux,                     /* Context pointer for xCreate/xConnect */
74754   void (*xDestroy)(void *)        /* Module destructor function */
74755 ){
74756   return createModule(db, zName, pModule, pAux, xDestroy);
74757 }
74758
74759 /*
74760 ** Lock the virtual table so that it cannot be disconnected.
74761 ** Locks nest.  Every lock should have a corresponding unlock.
74762 ** If an unlock is omitted, resources leaks will occur.  
74763 **
74764 ** If a disconnect is attempted while a virtual table is locked,
74765 ** the disconnect is deferred until all locks have been removed.
74766 */
74767 SQLITE_PRIVATE void sqlite3VtabLock(sqlite3_vtab *pVtab){
74768   pVtab->nRef++;
74769 }
74770
74771 /*
74772 ** Unlock a virtual table.  When the last lock is removed,
74773 ** disconnect the virtual table.
74774 */
74775 SQLITE_PRIVATE void sqlite3VtabUnlock(sqlite3 *db, sqlite3_vtab *pVtab){
74776   pVtab->nRef--;
74777   assert(db);
74778   assert( sqlite3SafetyCheckOk(db) );
74779   if( pVtab->nRef==0 ){
74780     if( db->magic==SQLITE_MAGIC_BUSY ){
74781       (void)sqlite3SafetyOff(db);
74782       pVtab->pModule->xDisconnect(pVtab);
74783       (void)sqlite3SafetyOn(db);
74784     } else {
74785       pVtab->pModule->xDisconnect(pVtab);
74786     }
74787   }
74788 }
74789
74790 /*
74791 ** Clear any and all virtual-table information from the Table record.
74792 ** This routine is called, for example, just before deleting the Table
74793 ** record.
74794 */
74795 SQLITE_PRIVATE void sqlite3VtabClear(Table *p){
74796   sqlite3_vtab *pVtab = p->pVtab;
74797   sqlite3 *db = p->db;
74798   if( pVtab ){
74799     assert( p->pMod && p->pMod->pModule );
74800     sqlite3VtabUnlock(db, pVtab);
74801     p->pVtab = 0;
74802   }
74803   if( p->azModuleArg ){
74804     int i;
74805     for(i=0; i<p->nModuleArg; i++){
74806       sqlite3DbFree(db, p->azModuleArg[i]);
74807     }
74808     sqlite3DbFree(db, p->azModuleArg);
74809   }
74810 }
74811
74812 /*
74813 ** Add a new module argument to pTable->azModuleArg[].
74814 ** The string is not copied - the pointer is stored.  The
74815 ** string will be freed automatically when the table is
74816 ** deleted.
74817 */
74818 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
74819   int i = pTable->nModuleArg++;
74820   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
74821   char **azModuleArg;
74822   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
74823   if( azModuleArg==0 ){
74824     int j;
74825     for(j=0; j<i; j++){
74826       sqlite3DbFree(db, pTable->azModuleArg[j]);
74827     }
74828     sqlite3DbFree(db, zArg);
74829     sqlite3DbFree(db, pTable->azModuleArg);
74830     pTable->nModuleArg = 0;
74831   }else{
74832     azModuleArg[i] = zArg;
74833     azModuleArg[i+1] = 0;
74834   }
74835   pTable->azModuleArg = azModuleArg;
74836 }
74837
74838 /*
74839 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
74840 ** statement.  The module name has been parsed, but the optional list
74841 ** of parameters that follow the module name are still pending.
74842 */
74843 SQLITE_PRIVATE void sqlite3VtabBeginParse(
74844   Parse *pParse,        /* Parsing context */
74845   Token *pName1,        /* Name of new table, or database name */
74846   Token *pName2,        /* Name of new table or NULL */
74847   Token *pModuleName    /* Name of the module for the virtual table */
74848 ){
74849   int iDb;              /* The database the table is being created in */
74850   Table *pTable;        /* The new virtual table */
74851   sqlite3 *db;          /* Database connection */
74852
74853   if( pParse->db->flags & SQLITE_SharedCache ){
74854     sqlite3ErrorMsg(pParse, "Cannot use virtual tables in shared-cache mode");
74855     return;
74856   }
74857
74858   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
74859   pTable = pParse->pNewTable;
74860   if( pTable==0 || pParse->nErr ) return;
74861   assert( 0==pTable->pIndex );
74862
74863   db = pParse->db;
74864   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
74865   assert( iDb>=0 );
74866
74867   pTable->tabFlags |= TF_Virtual;
74868   pTable->nModuleArg = 0;
74869   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
74870   addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
74871   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
74872   pParse->sNameToken.n = pModuleName->z + pModuleName->n - pName1->z;
74873
74874 #ifndef SQLITE_OMIT_AUTHORIZATION
74875   /* Creating a virtual table invokes the authorization callback twice.
74876   ** The first invocation, to obtain permission to INSERT a row into the
74877   ** sqlite_master table, has already been made by sqlite3StartTable().
74878   ** The second call, to obtain permission to create the table, is made now.
74879   */
74880   if( pTable->azModuleArg ){
74881     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
74882             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
74883   }
74884 #endif
74885 }
74886
74887 /*
74888 ** This routine takes the module argument that has been accumulating
74889 ** in pParse->zArg[] and appends it to the list of arguments on the
74890 ** virtual table currently under construction in pParse->pTable.
74891 */
74892 static void addArgumentToVtab(Parse *pParse){
74893   if( pParse->sArg.z && pParse->pNewTable ){
74894     const char *z = (const char*)pParse->sArg.z;
74895     int n = pParse->sArg.n;
74896     sqlite3 *db = pParse->db;
74897     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
74898   }
74899 }
74900
74901 /*
74902 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
74903 ** has been completely parsed.
74904 */
74905 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
74906   Table *pTab;        /* The table being constructed */
74907   sqlite3 *db;        /* The database connection */
74908   char *zModule;      /* The module name of the table: USING modulename */
74909   Module *pMod = 0;
74910
74911   addArgumentToVtab(pParse);
74912   pParse->sArg.z = 0;
74913
74914   /* Lookup the module name. */
74915   pTab = pParse->pNewTable;
74916   if( pTab==0 ) return;
74917   db = pParse->db;
74918   if( pTab->nModuleArg<1 ) return;
74919   zModule = pTab->azModuleArg[0];
74920   pMod = (Module *)sqlite3HashFind(&db->aModule, zModule, strlen(zModule));
74921   pTab->pMod = pMod;
74922   
74923   /* If the CREATE VIRTUAL TABLE statement is being entered for the
74924   ** first time (in other words if the virtual table is actually being
74925   ** created now instead of just being read out of sqlite_master) then
74926   ** do additional initialization work and store the statement text
74927   ** in the sqlite_master table.
74928   */
74929   if( !db->init.busy ){
74930     char *zStmt;
74931     char *zWhere;
74932     int iDb;
74933     Vdbe *v;
74934
74935     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
74936     if( pEnd ){
74937       pParse->sNameToken.n = pEnd->z - pParse->sNameToken.z + pEnd->n;
74938     }
74939     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
74940
74941     /* A slot for the record has already been allocated in the 
74942     ** SQLITE_MASTER table.  We just need to update that slot with all
74943     ** the information we've collected.  
74944     **
74945     ** The VM register number pParse->regRowid holds the rowid of an
74946     ** entry in the sqlite_master table tht was created for this vtab
74947     ** by sqlite3StartTable().
74948     */
74949     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
74950     sqlite3NestedParse(pParse,
74951       "UPDATE %Q.%s "
74952          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
74953        "WHERE rowid=#%d",
74954       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
74955       pTab->zName,
74956       pTab->zName,
74957       zStmt,
74958       pParse->regRowid
74959     );
74960     sqlite3DbFree(db, zStmt);
74961     v = sqlite3GetVdbe(pParse);
74962     sqlite3ChangeCookie(pParse, iDb);
74963
74964     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
74965     zWhere = sqlite3MPrintf(db, "name='%q'", pTab->zName);
74966     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 1, 0, zWhere, P4_DYNAMIC);
74967     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, 
74968                          pTab->zName, strlen(pTab->zName) + 1);
74969   }
74970
74971   /* If we are rereading the sqlite_master table create the in-memory
74972   ** record of the table. If the module has already been registered,
74973   ** also call the xConnect method here.
74974   */
74975   else {
74976     Table *pOld;
74977     Schema *pSchema = pTab->pSchema;
74978     const char *zName = pTab->zName;
74979     int nName = strlen(zName) + 1;
74980     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
74981     if( pOld ){
74982       db->mallocFailed = 1;
74983       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
74984       return;
74985     }
74986     pSchema->db = pParse->db;
74987     pParse->pNewTable = 0;
74988   }
74989 }
74990
74991 /*
74992 ** The parser calls this routine when it sees the first token
74993 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
74994 */
74995 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
74996   addArgumentToVtab(pParse);
74997   pParse->sArg.z = 0;
74998   pParse->sArg.n = 0;
74999 }
75000
75001 /*
75002 ** The parser calls this routine for each token after the first token
75003 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
75004 */
75005 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
75006   Token *pArg = &pParse->sArg;
75007   if( pArg->z==0 ){
75008     pArg->z = p->z;
75009     pArg->n = p->n;
75010   }else{
75011     assert(pArg->z < p->z);
75012     pArg->n = (p->z + p->n - pArg->z);
75013   }
75014 }
75015
75016 /*
75017 ** Invoke a virtual table constructor (either xCreate or xConnect). The
75018 ** pointer to the function to invoke is passed as the fourth parameter
75019 ** to this procedure.
75020 */
75021 static int vtabCallConstructor(
75022   sqlite3 *db, 
75023   Table *pTab,
75024   Module *pMod,
75025   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
75026   char **pzErr
75027 ){
75028   int rc;
75029   int rc2;
75030   sqlite3_vtab *pVtab = 0;
75031   const char *const*azArg = (const char *const*)pTab->azModuleArg;
75032   int nArg = pTab->nModuleArg;
75033   char *zErr = 0;
75034   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
75035
75036   if( !zModuleName ){
75037     return SQLITE_NOMEM;
75038   }
75039
75040   assert( !db->pVTab );
75041   assert( xConstruct );
75042
75043   db->pVTab = pTab;
75044   rc = sqlite3SafetyOff(db);
75045   assert( rc==SQLITE_OK );
75046   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVtab, &zErr);
75047   rc2 = sqlite3SafetyOn(db);
75048   if( rc==SQLITE_OK && pVtab ){
75049     pVtab->pModule = pMod->pModule;
75050     pVtab->nRef = 1;
75051     pTab->pVtab = pVtab;
75052   }
75053
75054   if( SQLITE_OK!=rc ){
75055     if( zErr==0 ){
75056       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
75057     }else {
75058       *pzErr = sqlite3MPrintf(db, "%s", zErr);
75059       sqlite3DbFree(db, zErr);
75060     }
75061   }else if( db->pVTab ){
75062     const char *zFormat = "vtable constructor did not declare schema: %s";
75063     *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
75064     rc = SQLITE_ERROR;
75065   } 
75066   if( rc==SQLITE_OK ){
75067     rc = rc2;
75068   }
75069   db->pVTab = 0;
75070   sqlite3DbFree(db, zModuleName);
75071
75072   /* If everything went according to plan, loop through the columns
75073   ** of the table to see if any of them contain the token "hidden".
75074   ** If so, set the Column.isHidden flag and remove the token from
75075   ** the type string.
75076   */
75077   if( rc==SQLITE_OK ){
75078     int iCol;
75079     for(iCol=0; iCol<pTab->nCol; iCol++){
75080       char *zType = pTab->aCol[iCol].zType;
75081       int nType;
75082       int i = 0;
75083       if( !zType ) continue;
75084       nType = strlen(zType);
75085       if( sqlite3StrNICmp("hidden", zType, 6) || (zType[6] && zType[6]!=' ') ){
75086         for(i=0; i<nType; i++){
75087           if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
75088            && (zType[i+7]=='\0' || zType[i+7]==' ')
75089           ){
75090             i++;
75091             break;
75092           }
75093         }
75094       }
75095       if( i<nType ){
75096         int j;
75097         int nDel = 6 + (zType[i+6] ? 1 : 0);
75098         for(j=i; (j+nDel)<=nType; j++){
75099           zType[j] = zType[j+nDel];
75100         }
75101         if( zType[i]=='\0' && i>0 ){
75102           assert(zType[i-1]==' ');
75103           zType[i-1] = '\0';
75104         }
75105         pTab->aCol[iCol].isHidden = 1;
75106       }
75107     }
75108   }
75109   return rc;
75110 }
75111
75112 /*
75113 ** This function is invoked by the parser to call the xConnect() method
75114 ** of the virtual table pTab. If an error occurs, an error code is returned 
75115 ** and an error left in pParse.
75116 **
75117 ** This call is a no-op if table pTab is not a virtual table.
75118 */
75119 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
75120   Module *pMod;
75121   int rc = SQLITE_OK;
75122
75123   if( !pTab || (pTab->tabFlags & TF_Virtual)==0 || pTab->pVtab ){
75124     return SQLITE_OK;
75125   }
75126
75127   pMod = pTab->pMod;
75128   if( !pMod ){
75129     const char *zModule = pTab->azModuleArg[0];
75130     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
75131     rc = SQLITE_ERROR;
75132   } else {
75133     char *zErr = 0;
75134     sqlite3 *db = pParse->db;
75135     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
75136     if( rc!=SQLITE_OK ){
75137       sqlite3ErrorMsg(pParse, "%s", zErr);
75138     }
75139     sqlite3DbFree(db, zErr);
75140   }
75141
75142   return rc;
75143 }
75144
75145 /*
75146 ** Add the virtual table pVtab to the array sqlite3.aVTrans[].
75147 */
75148 static int addToVTrans(sqlite3 *db, sqlite3_vtab *pVtab){
75149   const int ARRAY_INCR = 5;
75150
75151   /* Grow the sqlite3.aVTrans array if required */
75152   if( (db->nVTrans%ARRAY_INCR)==0 ){
75153     sqlite3_vtab **aVTrans;
75154     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
75155     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
75156     if( !aVTrans ){
75157       return SQLITE_NOMEM;
75158     }
75159     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
75160     db->aVTrans = aVTrans;
75161   }
75162
75163   /* Add pVtab to the end of sqlite3.aVTrans */
75164   db->aVTrans[db->nVTrans++] = pVtab;
75165   sqlite3VtabLock(pVtab);
75166   return SQLITE_OK;
75167 }
75168
75169 /*
75170 ** This function is invoked by the vdbe to call the xCreate method
75171 ** of the virtual table named zTab in database iDb. 
75172 **
75173 ** If an error occurs, *pzErr is set to point an an English language
75174 ** description of the error and an SQLITE_XXX error code is returned.
75175 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
75176 */
75177 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
75178   int rc = SQLITE_OK;
75179   Table *pTab;
75180   Module *pMod;
75181   const char *zModule;
75182
75183   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
75184   assert(pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVtab);
75185   pMod = pTab->pMod;
75186   zModule = pTab->azModuleArg[0];
75187
75188   /* If the module has been registered and includes a Create method, 
75189   ** invoke it now. If the module has not been registered, return an 
75190   ** error. Otherwise, do nothing.
75191   */
75192   if( !pMod ){
75193     *pzErr = sqlite3MPrintf(db, "no such module: %s", zModule);
75194     rc = SQLITE_ERROR;
75195   }else{
75196     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
75197   }
75198
75199   if( rc==SQLITE_OK && pTab->pVtab ){
75200       rc = addToVTrans(db, pTab->pVtab);
75201   }
75202
75203   return rc;
75204 }
75205
75206 /*
75207 ** This function is used to set the schema of a virtual table.  It is only
75208 ** valid to call this function from within the xCreate() or xConnect() of a
75209 ** virtual table module.
75210 */
75211 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
75212   Parse sParse;
75213
75214   int rc = SQLITE_OK;
75215   Table *pTab;
75216   char *zErr = 0;
75217
75218   sqlite3_mutex_enter(db->mutex);
75219   pTab = db->pVTab;
75220   if( !pTab ){
75221     sqlite3Error(db, SQLITE_MISUSE, 0);
75222     sqlite3_mutex_leave(db->mutex);
75223     return SQLITE_MISUSE;
75224   }
75225   assert((pTab->tabFlags & TF_Virtual)!=0 && pTab->nCol==0 && pTab->aCol==0);
75226
75227   memset(&sParse, 0, sizeof(Parse));
75228   sParse.declareVtab = 1;
75229   sParse.db = db;
75230
75231   if( 
75232       SQLITE_OK == sqlite3RunParser(&sParse, zCreateTable, &zErr) && 
75233       sParse.pNewTable && 
75234       !sParse.pNewTable->pSelect && 
75235       (sParse.pNewTable->tabFlags & TF_Virtual)==0
75236   ){
75237     pTab->aCol = sParse.pNewTable->aCol;
75238     pTab->nCol = sParse.pNewTable->nCol;
75239     sParse.pNewTable->nCol = 0;
75240     sParse.pNewTable->aCol = 0;
75241     db->pVTab = 0;
75242   } else {
75243     sqlite3Error(db, SQLITE_ERROR, zErr);
75244     sqlite3DbFree(db, zErr);
75245     rc = SQLITE_ERROR;
75246   }
75247   sParse.declareVtab = 0;
75248
75249   sqlite3_finalize((sqlite3_stmt*)sParse.pVdbe);
75250   sqlite3DeleteTable(sParse.pNewTable);
75251   sParse.pNewTable = 0;
75252
75253   assert( (rc&0xff)==rc );
75254   rc = sqlite3ApiExit(db, rc);
75255   sqlite3_mutex_leave(db->mutex);
75256   return rc;
75257 }
75258
75259 /*
75260 ** This function is invoked by the vdbe to call the xDestroy method
75261 ** of the virtual table named zTab in database iDb. This occurs
75262 ** when a DROP TABLE is mentioned.
75263 **
75264 ** This call is a no-op if zTab is not a virtual table.
75265 */
75266 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab)
75267 {
75268   int rc = SQLITE_OK;
75269   Table *pTab;
75270
75271   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
75272   assert(pTab);
75273   if( pTab->pVtab ){
75274     int (*xDestroy)(sqlite3_vtab *pVTab) = pTab->pMod->pModule->xDestroy;
75275     rc = sqlite3SafetyOff(db);
75276     assert( rc==SQLITE_OK );
75277     if( xDestroy ){
75278       rc = xDestroy(pTab->pVtab);
75279     }
75280     (void)sqlite3SafetyOn(db);
75281     if( rc==SQLITE_OK ){
75282       int i;
75283       for(i=0; i<db->nVTrans; i++){
75284         if( db->aVTrans[i]==pTab->pVtab ){
75285           db->aVTrans[i] = db->aVTrans[--db->nVTrans];
75286           break;
75287         }
75288       }
75289       pTab->pVtab = 0;
75290     }
75291   }
75292
75293   return rc;
75294 }
75295
75296 /*
75297 ** This function invokes either the xRollback or xCommit method
75298 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
75299 ** called is identified by the second argument, "offset", which is
75300 ** the offset of the method to call in the sqlite3_module structure.
75301 **
75302 ** The array is cleared after invoking the callbacks. 
75303 */
75304 static void callFinaliser(sqlite3 *db, int offset){
75305   int i;
75306   if( db->aVTrans ){
75307     for(i=0; i<db->nVTrans && db->aVTrans[i]; i++){
75308       sqlite3_vtab *pVtab = db->aVTrans[i];
75309       int (*x)(sqlite3_vtab *);
75310       x = *(int (**)(sqlite3_vtab *))((char *)pVtab->pModule + offset);
75311       if( x ) x(pVtab);
75312       sqlite3VtabUnlock(db, pVtab);
75313     }
75314     sqlite3DbFree(db, db->aVTrans);
75315     db->nVTrans = 0;
75316     db->aVTrans = 0;
75317   }
75318 }
75319
75320 /*
75321 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
75322 ** array. Return the error code for the first error that occurs, or
75323 ** SQLITE_OK if all xSync operations are successful.
75324 **
75325 ** Set *pzErrmsg to point to a buffer that should be released using 
75326 ** sqlite3DbFree() containing an error message, if one is available.
75327 */
75328 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
75329   int i;
75330   int rc = SQLITE_OK;
75331   int rcsafety;
75332   sqlite3_vtab **aVTrans = db->aVTrans;
75333
75334   rc = sqlite3SafetyOff(db);
75335   db->aVTrans = 0;
75336   for(i=0; rc==SQLITE_OK && i<db->nVTrans && aVTrans[i]; i++){
75337     sqlite3_vtab *pVtab = aVTrans[i];
75338     int (*x)(sqlite3_vtab *);
75339     x = pVtab->pModule->xSync;
75340     if( x ){
75341       rc = x(pVtab);
75342       sqlite3DbFree(db, *pzErrmsg);
75343       *pzErrmsg = pVtab->zErrMsg;
75344       pVtab->zErrMsg = 0;
75345     }
75346   }
75347   db->aVTrans = aVTrans;
75348   rcsafety = sqlite3SafetyOn(db);
75349
75350   if( rc==SQLITE_OK ){
75351     rc = rcsafety;
75352   }
75353   return rc;
75354 }
75355
75356 /*
75357 ** Invoke the xRollback method of all virtual tables in the 
75358 ** sqlite3.aVTrans array. Then clear the array itself.
75359 */
75360 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
75361   callFinaliser(db, offsetof(sqlite3_module,xRollback));
75362   return SQLITE_OK;
75363 }
75364
75365 /*
75366 ** Invoke the xCommit method of all virtual tables in the 
75367 ** sqlite3.aVTrans array. Then clear the array itself.
75368 */
75369 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
75370   callFinaliser(db, offsetof(sqlite3_module,xCommit));
75371   return SQLITE_OK;
75372 }
75373
75374 /*
75375 ** If the virtual table pVtab supports the transaction interface
75376 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
75377 ** not currently open, invoke the xBegin method now.
75378 **
75379 ** If the xBegin call is successful, place the sqlite3_vtab pointer
75380 ** in the sqlite3.aVTrans array.
75381 */
75382 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, sqlite3_vtab *pVtab){
75383   int rc = SQLITE_OK;
75384   const sqlite3_module *pModule;
75385
75386   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
75387   ** than zero, then this function is being called from within a
75388   ** virtual module xSync() callback. It is illegal to write to 
75389   ** virtual module tables in this case, so return SQLITE_LOCKED.
75390   */
75391   if( 0==db->aVTrans && db->nVTrans>0 ){
75392     return SQLITE_LOCKED;
75393   }
75394   if( !pVtab ){
75395     return SQLITE_OK;
75396   } 
75397   pModule = pVtab->pModule;
75398
75399   if( pModule->xBegin ){
75400     int i;
75401
75402
75403     /* If pVtab is already in the aVTrans array, return early */
75404     for(i=0; (i<db->nVTrans) && 0!=db->aVTrans[i]; i++){
75405       if( db->aVTrans[i]==pVtab ){
75406         return SQLITE_OK;
75407       }
75408     }
75409
75410     /* Invoke the xBegin method */
75411     rc = pModule->xBegin(pVtab);
75412     if( rc==SQLITE_OK ){
75413       rc = addToVTrans(db, pVtab);
75414     }
75415   }
75416   return rc;
75417 }
75418
75419 /*
75420 ** The first parameter (pDef) is a function implementation.  The
75421 ** second parameter (pExpr) is the first argument to this function.
75422 ** If pExpr is a column in a virtual table, then let the virtual
75423 ** table implementation have an opportunity to overload the function.
75424 **
75425 ** This routine is used to allow virtual table implementations to
75426 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
75427 **
75428 ** Return either the pDef argument (indicating no change) or a 
75429 ** new FuncDef structure that is marked as ephemeral using the
75430 ** SQLITE_FUNC_EPHEM flag.
75431 */
75432 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
75433   sqlite3 *db,    /* Database connection for reporting malloc problems */
75434   FuncDef *pDef,  /* Function to possibly overload */
75435   int nArg,       /* Number of arguments to the function */
75436   Expr *pExpr     /* First argument to the function */
75437 ){
75438   Table *pTab;
75439   sqlite3_vtab *pVtab;
75440   sqlite3_module *pMod;
75441   void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
75442   void *pArg;
75443   FuncDef *pNew;
75444   int rc = 0;
75445   char *zLowerName;
75446   unsigned char *z;
75447
75448
75449   /* Check to see the left operand is a column in a virtual table */
75450   if( pExpr==0 ) return pDef;
75451   if( pExpr->op!=TK_COLUMN ) return pDef;
75452   pTab = pExpr->pTab;
75453   if( pTab==0 ) return pDef;
75454   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
75455   pVtab = pTab->pVtab;
75456   assert( pVtab!=0 );
75457   assert( pVtab->pModule!=0 );
75458   pMod = (sqlite3_module *)pVtab->pModule;
75459   if( pMod->xFindFunction==0 ) return pDef;
75460  
75461   /* Call the xFindFunction method on the virtual table implementation
75462   ** to see if the implementation wants to overload this function 
75463   */
75464   zLowerName = sqlite3DbStrDup(db, pDef->zName);
75465   if( zLowerName ){
75466     for(z=(unsigned char*)zLowerName; *z; z++){
75467       *z = sqlite3UpperToLower[*z];
75468     }
75469     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
75470     sqlite3DbFree(db, zLowerName);
75471     if( pVtab->zErrMsg ){
75472       sqlite3Error(db, rc, "%s", pVtab->zErrMsg);
75473       sqlite3DbFree(db, pVtab->zErrMsg);
75474       pVtab->zErrMsg = 0;
75475     }
75476   }
75477   if( rc==0 ){
75478     return pDef;
75479   }
75480
75481   /* Create a new ephemeral function definition for the overloaded
75482   ** function */
75483   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) + strlen(pDef->zName) );
75484   if( pNew==0 ){
75485     return pDef;
75486   }
75487   *pNew = *pDef;
75488   pNew->zName = (char *)&pNew[1];
75489   memcpy(pNew->zName, pDef->zName, strlen(pDef->zName)+1);
75490   pNew->xFunc = xFunc;
75491   pNew->pUserData = pArg;
75492   pNew->flags |= SQLITE_FUNC_EPHEM;
75493   return pNew;
75494 }
75495
75496 /*
75497 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
75498 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
75499 ** array if it is missing.  If pTab is already in the array, this routine
75500 ** is a no-op.
75501 */
75502 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
75503   int i, n;
75504   assert( IsVirtual(pTab) );
75505   for(i=0; i<pParse->nVtabLock; i++){
75506     if( pTab==pParse->apVtabLock[i] ) return;
75507   }
75508   n = (pParse->nVtabLock+1)*sizeof(pParse->apVtabLock[0]);
75509   pParse->apVtabLock = sqlite3_realloc(pParse->apVtabLock, n);
75510   if( pParse->apVtabLock ){
75511     pParse->apVtabLock[pParse->nVtabLock++] = pTab;
75512   }else{
75513     pParse->db->mallocFailed = 1;
75514   }
75515 }
75516
75517 #endif /* SQLITE_OMIT_VIRTUALTABLE */
75518
75519 /************** End of vtab.c ************************************************/
75520 /************** Begin file where.c *******************************************/
75521 /*
75522 ** 2001 September 15
75523 **
75524 ** The author disclaims copyright to this source code.  In place of
75525 ** a legal notice, here is a blessing:
75526 **
75527 **    May you do good and not evil.
75528 **    May you find forgiveness for yourself and forgive others.
75529 **    May you share freely, never taking more than you give.
75530 **
75531 *************************************************************************
75532 ** This module contains C code that generates VDBE code used to process
75533 ** the WHERE clause of SQL statements.  This module is responsible for
75534 ** generating the code that loops through a table looking for applicable
75535 ** rows.  Indices are selected and used to speed the search when doing
75536 ** so is applicable.  Because this module is responsible for selecting
75537 ** indices, you might also think of this module as the "query optimizer".
75538 **
75539 ** $Id: where.c,v 1.322 2008/09/06 14:19:11 danielk1977 Exp $
75540 */
75541
75542 /*
75543 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
75544 */
75545 #define BMS  (sizeof(Bitmask)*8)
75546
75547 /*
75548 ** Trace output macros
75549 */
75550 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
75551 SQLITE_PRIVATE int sqlite3WhereTrace = 0;
75552 #endif
75553 #if 0
75554 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
75555 #else
75556 # define WHERETRACE(X)
75557 #endif
75558
75559 /* Forward reference
75560 */
75561 typedef struct WhereClause WhereClause;
75562 typedef struct ExprMaskSet ExprMaskSet;
75563
75564 /*
75565 ** The query generator uses an array of instances of this structure to
75566 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
75567 ** clause subexpression is separated from the others by an AND operator.
75568 **
75569 ** All WhereTerms are collected into a single WhereClause structure.  
75570 ** The following identity holds:
75571 **
75572 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
75573 **
75574 ** When a term is of the form:
75575 **
75576 **              X <op> <expr>
75577 **
75578 ** where X is a column name and <op> is one of certain operators,
75579 ** then WhereTerm.leftCursor and WhereTerm.leftColumn record the
75580 ** cursor number and column number for X.  WhereTerm.operator records
75581 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
75582 ** use of a bitmask encoding for the operator allows us to search
75583 ** quickly for terms that match any of several different operators.
75584 **
75585 ** prereqRight and prereqAll record sets of cursor numbers,
75586 ** but they do so indirectly.  A single ExprMaskSet structure translates
75587 ** cursor number into bits and the translated bit is stored in the prereq
75588 ** fields.  The translation is used in order to maximize the number of
75589 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
75590 ** spread out over the non-negative integers.  For example, the cursor
75591 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The ExprMaskSet
75592 ** translates these sparse cursor numbers into consecutive integers
75593 ** beginning with 0 in order to make the best possible use of the available
75594 ** bits in the Bitmask.  So, in the example above, the cursor numbers
75595 ** would be mapped into integers 0 through 7.
75596 */
75597 typedef struct WhereTerm WhereTerm;
75598 struct WhereTerm {
75599   Expr *pExpr;            /* Pointer to the subexpression */
75600   i16 iParent;            /* Disable pWC->a[iParent] when this term disabled */
75601   i16 leftCursor;         /* Cursor number of X in "X <op> <expr>" */
75602   i16 leftColumn;         /* Column number of X in "X <op> <expr>" */
75603   u16 eOperator;          /* A WO_xx value describing <op> */
75604   u8 flags;               /* Bit flags.  See below */
75605   u8 nChild;              /* Number of children that must disable us */
75606   WhereClause *pWC;       /* The clause this term is part of */
75607   Bitmask prereqRight;    /* Bitmask of tables used by pRight */
75608   Bitmask prereqAll;      /* Bitmask of tables referenced by p */
75609 };
75610
75611 /*
75612 ** Allowed values of WhereTerm.flags
75613 */
75614 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
75615 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
75616 #define TERM_CODED      0x04   /* This term is already coded */
75617 #define TERM_COPIED     0x08   /* Has a child */
75618 #define TERM_OR_OK      0x10   /* Used during OR-clause processing */
75619
75620 /*
75621 ** An instance of the following structure holds all information about a
75622 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
75623 */
75624 struct WhereClause {
75625   Parse *pParse;           /* The parser context */
75626   ExprMaskSet *pMaskSet;   /* Mapping of table indices to bitmasks */
75627   int nTerm;               /* Number of terms */
75628   int nSlot;               /* Number of entries in a[] */
75629   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
75630   WhereTerm aStatic[10];   /* Initial static space for a[] */
75631 };
75632
75633 /*
75634 ** An instance of the following structure keeps track of a mapping
75635 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
75636 **
75637 ** The VDBE cursor numbers are small integers contained in 
75638 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
75639 ** clause, the cursor numbers might not begin with 0 and they might
75640 ** contain gaps in the numbering sequence.  But we want to make maximum
75641 ** use of the bits in our bitmasks.  This structure provides a mapping
75642 ** from the sparse cursor numbers into consecutive integers beginning
75643 ** with 0.
75644 **
75645 ** If ExprMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
75646 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
75647 **
75648 ** For example, if the WHERE clause expression used these VDBE
75649 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  ExprMaskSet structure
75650 ** would map those cursor numbers into bits 0 through 5.
75651 **
75652 ** Note that the mapping is not necessarily ordered.  In the example
75653 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
75654 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
75655 ** does not really matter.  What is important is that sparse cursor
75656 ** numbers all get mapped into bit numbers that begin with 0 and contain
75657 ** no gaps.
75658 */
75659 struct ExprMaskSet {
75660   int n;                        /* Number of assigned cursor values */
75661   int ix[sizeof(Bitmask)*8];    /* Cursor assigned to each bit */
75662 };
75663
75664
75665 /*
75666 ** Bitmasks for the operators that indices are able to exploit.  An
75667 ** OR-ed combination of these values can be used when searching for
75668 ** terms in the where clause.
75669 */
75670 #define WO_IN     1
75671 #define WO_EQ     2
75672 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
75673 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
75674 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
75675 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
75676 #define WO_MATCH  64
75677 #define WO_ISNULL 128
75678
75679 /*
75680 ** Value for flags returned by bestIndex().  
75681 **
75682 ** The least significant byte is reserved as a mask for WO_ values above.
75683 ** The WhereLevel.flags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
75684 ** But if the table is the right table of a left join, WhereLevel.flags
75685 ** is set to WO_IN|WO_EQ.  The WhereLevel.flags field can then be used as
75686 ** the "op" parameter to findTerm when we are resolving equality constraints.
75687 ** ISNULL constraints will then not be used on the right table of a left
75688 ** join.  Tickets #2177 and #2189.
75689 */
75690 #define WHERE_ROWID_EQ     0x000100   /* rowid=EXPR or rowid IN (...) */
75691 #define WHERE_ROWID_RANGE  0x000200   /* rowid<EXPR and/or rowid>EXPR */
75692 #define WHERE_COLUMN_EQ    0x001000   /* x=EXPR or x IN (...) */
75693 #define WHERE_COLUMN_RANGE 0x002000   /* x<EXPR and/or x>EXPR */
75694 #define WHERE_COLUMN_IN    0x004000   /* x IN (...) */
75695 #define WHERE_TOP_LIMIT    0x010000   /* x<EXPR or x<=EXPR constraint */
75696 #define WHERE_BTM_LIMIT    0x020000   /* x>EXPR or x>=EXPR constraint */
75697 #define WHERE_IDX_ONLY     0x080000   /* Use index only - omit table */
75698 #define WHERE_ORDERBY      0x100000   /* Output will appear in correct order */
75699 #define WHERE_REVERSE      0x200000   /* Scan in reverse order */
75700 #define WHERE_UNIQUE       0x400000   /* Selects no more than one row */
75701 #define WHERE_VIRTUALTABLE 0x800000   /* Use virtual-table processing */
75702
75703 /*
75704 ** Initialize a preallocated WhereClause structure.
75705 */
75706 static void whereClauseInit(
75707   WhereClause *pWC,        /* The WhereClause to be initialized */
75708   Parse *pParse,           /* The parsing context */
75709   ExprMaskSet *pMaskSet    /* Mapping from table indices to bitmasks */
75710 ){
75711   pWC->pParse = pParse;
75712   pWC->pMaskSet = pMaskSet;
75713   pWC->nTerm = 0;
75714   pWC->nSlot = ArraySize(pWC->aStatic);
75715   pWC->a = pWC->aStatic;
75716 }
75717
75718 /*
75719 ** Deallocate a WhereClause structure.  The WhereClause structure
75720 ** itself is not freed.  This routine is the inverse of whereClauseInit().
75721 */
75722 static void whereClauseClear(WhereClause *pWC){
75723   int i;
75724   WhereTerm *a;
75725   sqlite3 *db = pWC->pParse->db;
75726   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
75727     if( a->flags & TERM_DYNAMIC ){
75728       sqlite3ExprDelete(db, a->pExpr);
75729     }
75730   }
75731   if( pWC->a!=pWC->aStatic ){
75732     sqlite3DbFree(db, pWC->a);
75733   }
75734 }
75735
75736 /*
75737 ** Add a new entries to the WhereClause structure.  Increase the allocated
75738 ** space as necessary.
75739 **
75740 ** If the flags argument includes TERM_DYNAMIC, then responsibility
75741 ** for freeing the expression p is assumed by the WhereClause object.
75742 **
75743 ** WARNING:  This routine might reallocate the space used to store
75744 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
75745 ** calling this routine.  Such pointers may be reinitialized by referencing
75746 ** the pWC->a[] array.
75747 */
75748 static int whereClauseInsert(WhereClause *pWC, Expr *p, int flags){
75749   WhereTerm *pTerm;
75750   int idx;
75751   if( pWC->nTerm>=pWC->nSlot ){
75752     WhereTerm *pOld = pWC->a;
75753     sqlite3 *db = pWC->pParse->db;
75754     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
75755     if( pWC->a==0 ){
75756       if( flags & TERM_DYNAMIC ){
75757         sqlite3ExprDelete(db, p);
75758       }
75759       pWC->a = pOld;
75760       return 0;
75761     }
75762     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
75763     if( pOld!=pWC->aStatic ){
75764       sqlite3DbFree(db, pOld);
75765     }
75766     pWC->nSlot *= 2;
75767   }
75768   pTerm = &pWC->a[idx = pWC->nTerm];
75769   pWC->nTerm++;
75770   pTerm->pExpr = p;
75771   pTerm->flags = flags;
75772   pTerm->pWC = pWC;
75773   pTerm->iParent = -1;
75774   return idx;
75775 }
75776
75777 /*
75778 ** This routine identifies subexpressions in the WHERE clause where
75779 ** each subexpression is separated by the AND operator or some other
75780 ** operator specified in the op parameter.  The WhereClause structure
75781 ** is filled with pointers to subexpressions.  For example:
75782 **
75783 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
75784 **           \________/     \_______________/     \________________/
75785 **            slot[0]            slot[1]               slot[2]
75786 **
75787 ** The original WHERE clause in pExpr is unaltered.  All this routine
75788 ** does is make slot[] entries point to substructure within pExpr.
75789 **
75790 ** In the previous sentence and in the diagram, "slot[]" refers to
75791 ** the WhereClause.a[] array.  This array grows as needed to contain
75792 ** all terms of the WHERE clause.
75793 */
75794 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
75795   if( pExpr==0 ) return;
75796   if( pExpr->op!=op ){
75797     whereClauseInsert(pWC, pExpr, 0);
75798   }else{
75799     whereSplit(pWC, pExpr->pLeft, op);
75800     whereSplit(pWC, pExpr->pRight, op);
75801   }
75802 }
75803
75804 /*
75805 ** Initialize an expression mask set
75806 */
75807 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
75808
75809 /*
75810 ** Return the bitmask for the given cursor number.  Return 0 if
75811 ** iCursor is not in the set.
75812 */
75813 static Bitmask getMask(ExprMaskSet *pMaskSet, int iCursor){
75814   int i;
75815   for(i=0; i<pMaskSet->n; i++){
75816     if( pMaskSet->ix[i]==iCursor ){
75817       return ((Bitmask)1)<<i;
75818     }
75819   }
75820   return 0;
75821 }
75822
75823 /*
75824 ** Create a new mask for cursor iCursor.
75825 **
75826 ** There is one cursor per table in the FROM clause.  The number of
75827 ** tables in the FROM clause is limited by a test early in the
75828 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
75829 ** array will never overflow.
75830 */
75831 static void createMask(ExprMaskSet *pMaskSet, int iCursor){
75832   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
75833   pMaskSet->ix[pMaskSet->n++] = iCursor;
75834 }
75835
75836 /*
75837 ** This routine walks (recursively) an expression tree and generates
75838 ** a bitmask indicating which tables are used in that expression
75839 ** tree.
75840 **
75841 ** In order for this routine to work, the calling function must have
75842 ** previously invoked sqlite3ResolveExprNames() on the expression.  See
75843 ** the header comment on that routine for additional information.
75844 ** The sqlite3ResolveExprNames() routines looks for column names and
75845 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
75846 ** the VDBE cursor number of the table.  This routine just has to
75847 ** translate the cursor numbers into bitmask values and OR all
75848 ** the bitmasks together.
75849 */
75850 static Bitmask exprListTableUsage(ExprMaskSet*, ExprList*);
75851 static Bitmask exprSelectTableUsage(ExprMaskSet*, Select*);
75852 static Bitmask exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
75853   Bitmask mask = 0;
75854   if( p==0 ) return 0;
75855   if( p->op==TK_COLUMN ){
75856     mask = getMask(pMaskSet, p->iTable);
75857     return mask;
75858   }
75859   mask = exprTableUsage(pMaskSet, p->pRight);
75860   mask |= exprTableUsage(pMaskSet, p->pLeft);
75861   mask |= exprListTableUsage(pMaskSet, p->pList);
75862   mask |= exprSelectTableUsage(pMaskSet, p->pSelect);
75863   return mask;
75864 }
75865 static Bitmask exprListTableUsage(ExprMaskSet *pMaskSet, ExprList *pList){
75866   int i;
75867   Bitmask mask = 0;
75868   if( pList ){
75869     for(i=0; i<pList->nExpr; i++){
75870       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
75871     }
75872   }
75873   return mask;
75874 }
75875 static Bitmask exprSelectTableUsage(ExprMaskSet *pMaskSet, Select *pS){
75876   Bitmask mask = 0;
75877   while( pS ){
75878     mask |= exprListTableUsage(pMaskSet, pS->pEList);
75879     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
75880     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
75881     mask |= exprTableUsage(pMaskSet, pS->pWhere);
75882     mask |= exprTableUsage(pMaskSet, pS->pHaving);
75883     pS = pS->pPrior;
75884   }
75885   return mask;
75886 }
75887
75888 /*
75889 ** Return TRUE if the given operator is one of the operators that is
75890 ** allowed for an indexable WHERE clause term.  The allowed operators are
75891 ** "=", "<", ">", "<=", ">=", and "IN".
75892 */
75893 static int allowedOp(int op){
75894   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
75895   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
75896   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
75897   assert( TK_GE==TK_EQ+4 );
75898   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
75899 }
75900
75901 /*
75902 ** Swap two objects of type T.
75903 */
75904 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
75905
75906 /*
75907 ** Commute a comparison operator.  Expressions of the form "X op Y"
75908 ** are converted into "Y op X".
75909 **
75910 ** If a collation sequence is associated with either the left or right
75911 ** side of the comparison, it remains associated with the same side after
75912 ** the commutation. So "Y collate NOCASE op X" becomes 
75913 ** "X collate NOCASE op Y". This is because any collation sequence on
75914 ** the left hand side of a comparison overrides any collation sequence 
75915 ** attached to the right. For the same reason the EP_ExpCollate flag
75916 ** is not commuted.
75917 */
75918 static void exprCommute(Parse *pParse, Expr *pExpr){
75919   u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
75920   u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
75921   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
75922   pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
75923   pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
75924   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
75925   pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
75926   pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
75927   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
75928   if( pExpr->op>=TK_GT ){
75929     assert( TK_LT==TK_GT+2 );
75930     assert( TK_GE==TK_LE+2 );
75931     assert( TK_GT>TK_EQ );
75932     assert( TK_GT<TK_LE );
75933     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
75934     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
75935   }
75936 }
75937
75938 /*
75939 ** Translate from TK_xx operator to WO_xx bitmask.
75940 */
75941 static int operatorMask(int op){
75942   int c;
75943   assert( allowedOp(op) );
75944   if( op==TK_IN ){
75945     c = WO_IN;
75946   }else if( op==TK_ISNULL ){
75947     c = WO_ISNULL;
75948   }else{
75949     c = WO_EQ<<(op-TK_EQ);
75950   }
75951   assert( op!=TK_ISNULL || c==WO_ISNULL );
75952   assert( op!=TK_IN || c==WO_IN );
75953   assert( op!=TK_EQ || c==WO_EQ );
75954   assert( op!=TK_LT || c==WO_LT );
75955   assert( op!=TK_LE || c==WO_LE );
75956   assert( op!=TK_GT || c==WO_GT );
75957   assert( op!=TK_GE || c==WO_GE );
75958   return c;
75959 }
75960
75961 /*
75962 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
75963 ** where X is a reference to the iColumn of table iCur and <op> is one of
75964 ** the WO_xx operator codes specified by the op parameter.
75965 ** Return a pointer to the term.  Return 0 if not found.
75966 */
75967 static WhereTerm *findTerm(
75968   WhereClause *pWC,     /* The WHERE clause to be searched */
75969   int iCur,             /* Cursor number of LHS */
75970   int iColumn,          /* Column number of LHS */
75971   Bitmask notReady,     /* RHS must not overlap with this mask */
75972   u16 op,               /* Mask of WO_xx values describing operator */
75973   Index *pIdx           /* Must be compatible with this index, if not NULL */
75974 ){
75975   WhereTerm *pTerm;
75976   int k;
75977   assert( iCur>=0 );
75978   for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
75979     if( pTerm->leftCursor==iCur
75980        && (pTerm->prereqRight & notReady)==0
75981        && pTerm->leftColumn==iColumn
75982        && (pTerm->eOperator & op)!=0
75983     ){
75984       if( pIdx && pTerm->eOperator!=WO_ISNULL ){
75985         Expr *pX = pTerm->pExpr;
75986         CollSeq *pColl;
75987         char idxaff;
75988         int j;
75989         Parse *pParse = pWC->pParse;
75990
75991         idxaff = pIdx->pTable->aCol[iColumn].affinity;
75992         if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
75993
75994         /* Figure out the collation sequence required from an index for
75995         ** it to be useful for optimising expression pX. Store this
75996         ** value in variable pColl.
75997         */
75998         assert(pX->pLeft);
75999         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
76000         if( !pColl ){
76001           pColl = pParse->db->pDfltColl;
76002         }
76003
76004         for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
76005           if( NEVER(j>=pIdx->nColumn) ) return 0;
76006         }
76007         if( sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
76008       }
76009       return pTerm;
76010     }
76011   }
76012   return 0;
76013 }
76014
76015 /* Forward reference */
76016 static void exprAnalyze(SrcList*, WhereClause*, int);
76017
76018 /*
76019 ** Call exprAnalyze on all terms in a WHERE clause.  
76020 **
76021 **
76022 */
76023 static void exprAnalyzeAll(
76024   SrcList *pTabList,       /* the FROM clause */
76025   WhereClause *pWC         /* the WHERE clause to be analyzed */
76026 ){
76027   int i;
76028   for(i=pWC->nTerm-1; i>=0; i--){
76029     exprAnalyze(pTabList, pWC, i);
76030   }
76031 }
76032
76033 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
76034 /*
76035 ** Check to see if the given expression is a LIKE or GLOB operator that
76036 ** can be optimized using inequality constraints.  Return TRUE if it is
76037 ** so and false if not.
76038 **
76039 ** In order for the operator to be optimizible, the RHS must be a string
76040 ** literal that does not begin with a wildcard.  
76041 */
76042 static int isLikeOrGlob(
76043   Parse *pParse,    /* Parsing and code generating context */
76044   Expr *pExpr,      /* Test this expression */
76045   int *pnPattern,   /* Number of non-wildcard prefix characters */
76046   int *pisComplete, /* True if the only wildcard is % in the last character */
76047   int *pnoCase      /* True if uppercase is equivalent to lowercase */
76048 ){
76049   const char *z;
76050   Expr *pRight, *pLeft;
76051   ExprList *pList;
76052   int c, cnt;
76053   char wc[3];
76054   CollSeq *pColl;
76055   sqlite3 *db = pParse->db;
76056
76057   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
76058     return 0;
76059   }
76060 #ifdef SQLITE_EBCDIC
76061   if( *pnoCase ) return 0;
76062 #endif
76063   pList = pExpr->pList;
76064   pRight = pList->a[0].pExpr;
76065   if( pRight->op!=TK_STRING
76066    && (pRight->op!=TK_REGISTER || pRight->iColumn!=TK_STRING) ){
76067     return 0;
76068   }
76069   pLeft = pList->a[1].pExpr;
76070   if( pLeft->op!=TK_COLUMN ){
76071     return 0;
76072   }
76073   pColl = sqlite3ExprCollSeq(pParse, pLeft);
76074   assert( pColl!=0 || pLeft->iColumn==-1 );
76075   if( pColl==0 ){
76076     /* No collation is defined for the ROWID.  Use the default. */
76077     pColl = db->pDfltColl;
76078   }
76079   if( (pColl->type!=SQLITE_COLL_BINARY || *pnoCase) &&
76080       (pColl->type!=SQLITE_COLL_NOCASE || !*pnoCase) ){
76081     return 0;
76082   }
76083   sqlite3DequoteExpr(db, pRight);
76084   z = (char *)pRight->token.z;
76085   cnt = 0;
76086   if( z ){
76087     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){ cnt++; }
76088   }
76089   if( cnt==0 || 255==(u8)z[cnt] ){
76090     return 0;
76091   }
76092   *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
76093   *pnPattern = cnt;
76094   return 1;
76095 }
76096 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
76097
76098
76099 #ifndef SQLITE_OMIT_VIRTUALTABLE
76100 /*
76101 ** Check to see if the given expression is of the form
76102 **
76103 **         column MATCH expr
76104 **
76105 ** If it is then return TRUE.  If not, return FALSE.
76106 */
76107 static int isMatchOfColumn(
76108   Expr *pExpr      /* Test this expression */
76109 ){
76110   ExprList *pList;
76111
76112   if( pExpr->op!=TK_FUNCTION ){
76113     return 0;
76114   }
76115   if( pExpr->token.n!=5 ||
76116        sqlite3StrNICmp((const char*)pExpr->token.z,"match",5)!=0 ){
76117     return 0;
76118   }
76119   pList = pExpr->pList;
76120   if( pList->nExpr!=2 ){
76121     return 0;
76122   }
76123   if( pList->a[1].pExpr->op != TK_COLUMN ){
76124     return 0;
76125   }
76126   return 1;
76127 }
76128 #endif /* SQLITE_OMIT_VIRTUALTABLE */
76129
76130 /*
76131 ** If the pBase expression originated in the ON or USING clause of
76132 ** a join, then transfer the appropriate markings over to derived.
76133 */
76134 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
76135   pDerived->flags |= pBase->flags & EP_FromJoin;
76136   pDerived->iRightJoinTable = pBase->iRightJoinTable;
76137 }
76138
76139 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
76140 /*
76141 ** Return TRUE if the given term of an OR clause can be converted
76142 ** into an IN clause.  The iCursor and iColumn define the left-hand
76143 ** side of the IN clause.
76144 **
76145 ** The context is that we have multiple OR-connected equality terms
76146 ** like this:
76147 **
76148 **           a=<expr1> OR  a=<expr2> OR b=<expr3>  OR ...
76149 **
76150 ** The pOrTerm input to this routine corresponds to a single term of
76151 ** this OR clause.  In order for the term to be a candidate for
76152 ** conversion to an IN operator, the following must be true:
76153 **
76154 **     *  The left-hand side of the term must be the column which
76155 **        is identified by iCursor and iColumn.
76156 **
76157 **     *  If the right-hand side is also a column, then the affinities
76158 **        of both right and left sides must be such that no type
76159 **        conversions are required on the right.  (Ticket #2249)
76160 **
76161 ** If both of these conditions are true, then return true.  Otherwise
76162 ** return false.
76163 */
76164 static int orTermIsOptCandidate(WhereTerm *pOrTerm, int iCursor, int iColumn){
76165   int affLeft, affRight;
76166   assert( pOrTerm->eOperator==WO_EQ );
76167   if( pOrTerm->leftCursor!=iCursor ){
76168     return 0;
76169   }
76170   if( pOrTerm->leftColumn!=iColumn ){
76171     return 0;
76172   }
76173   affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
76174   if( affRight==0 ){
76175     return 1;
76176   }
76177   affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
76178   if( affRight!=affLeft ){
76179     return 0;
76180   }
76181   return 1;
76182 }
76183
76184 /*
76185 ** Return true if the given term of an OR clause can be ignored during
76186 ** a check to make sure all OR terms are candidates for optimization.
76187 ** In other words, return true if a call to the orTermIsOptCandidate()
76188 ** above returned false but it is not necessary to disqualify the
76189 ** optimization.
76190 **
76191 ** Suppose the original OR phrase was this:
76192 **
76193 **           a=4  OR  a=11  OR  a=b
76194 **
76195 ** During analysis, the third term gets flipped around and duplicate
76196 ** so that we are left with this:
76197 **
76198 **           a=4  OR  a=11  OR  a=b  OR  b=a
76199 **
76200 ** Since the last two terms are duplicates, only one of them
76201 ** has to qualify in order for the whole phrase to qualify.  When
76202 ** this routine is called, we know that pOrTerm did not qualify.
76203 ** This routine merely checks to see if pOrTerm has a duplicate that
76204 ** might qualify.  If there is a duplicate that has not yet been
76205 ** disqualified, then return true.  If there are no duplicates, or
76206 ** the duplicate has also been disqualified, return false.
76207 */
76208 static int orTermHasOkDuplicate(WhereClause *pOr, WhereTerm *pOrTerm){
76209   if( pOrTerm->flags & TERM_COPIED ){
76210     /* This is the original term.  The duplicate is to the left had
76211     ** has not yet been analyzed and thus has not yet been disqualified. */
76212     return 1;
76213   }
76214   if( (pOrTerm->flags & TERM_VIRTUAL)!=0
76215      && (pOr->a[pOrTerm->iParent].flags & TERM_OR_OK)!=0 ){
76216     /* This is a duplicate term.  The original qualified so this one
76217     ** does not have to. */
76218     return 1;
76219   }
76220   /* This is either a singleton term or else it is a duplicate for
76221   ** which the original did not qualify.  Either way we are done for. */
76222   return 0;
76223 }
76224 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
76225
76226 /*
76227 ** The input to this routine is an WhereTerm structure with only the
76228 ** "pExpr" field filled in.  The job of this routine is to analyze the
76229 ** subexpression and populate all the other fields of the WhereTerm
76230 ** structure.
76231 **
76232 ** If the expression is of the form "<expr> <op> X" it gets commuted
76233 ** to the standard form of "X <op> <expr>".  If the expression is of
76234 ** the form "X <op> Y" where both X and Y are columns, then the original
76235 ** expression is unchanged and a new virtual expression of the form
76236 ** "Y <op> X" is added to the WHERE clause and analyzed separately.
76237 */
76238 static void exprAnalyze(
76239   SrcList *pSrc,            /* the FROM clause */
76240   WhereClause *pWC,         /* the WHERE clause */
76241   int idxTerm               /* Index of the term to be analyzed */
76242 ){
76243   WhereTerm *pTerm;
76244   ExprMaskSet *pMaskSet;
76245   Expr *pExpr;
76246   Bitmask prereqLeft;
76247   Bitmask prereqAll;
76248   Bitmask extraRight = 0;
76249   int nPattern;
76250   int isComplete;
76251   int noCase;
76252   int op;
76253   Parse *pParse = pWC->pParse;
76254   sqlite3 *db = pParse->db;
76255
76256   if( db->mallocFailed ){
76257     return;
76258   }
76259   pTerm = &pWC->a[idxTerm];
76260   pMaskSet = pWC->pMaskSet;
76261   pExpr = pTerm->pExpr;
76262   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
76263   op = pExpr->op;
76264   if( op==TK_IN ){
76265     assert( pExpr->pRight==0 );
76266     pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->pList)
76267                           | exprSelectTableUsage(pMaskSet, pExpr->pSelect);
76268   }else if( op==TK_ISNULL ){
76269     pTerm->prereqRight = 0;
76270   }else{
76271     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
76272   }
76273   prereqAll = exprTableUsage(pMaskSet, pExpr);
76274   if( ExprHasProperty(pExpr, EP_FromJoin) ){
76275     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
76276     prereqAll |= x;
76277     extraRight = x-1;  /* ON clause terms may not be used with an index
76278                        ** on left table of a LEFT JOIN.  Ticket #3015 */
76279   }
76280   pTerm->prereqAll = prereqAll;
76281   pTerm->leftCursor = -1;
76282   pTerm->iParent = -1;
76283   pTerm->eOperator = 0;
76284   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
76285     Expr *pLeft = pExpr->pLeft;
76286     Expr *pRight = pExpr->pRight;
76287     if( pLeft->op==TK_COLUMN ){
76288       pTerm->leftCursor = pLeft->iTable;
76289       pTerm->leftColumn = pLeft->iColumn;
76290       pTerm->eOperator = operatorMask(op);
76291     }
76292     if( pRight && pRight->op==TK_COLUMN ){
76293       WhereTerm *pNew;
76294       Expr *pDup;
76295       if( pTerm->leftCursor>=0 ){
76296         int idxNew;
76297         pDup = sqlite3ExprDup(db, pExpr);
76298         if( db->mallocFailed ){
76299           sqlite3ExprDelete(db, pDup);
76300           return;
76301         }
76302         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
76303         if( idxNew==0 ) return;
76304         pNew = &pWC->a[idxNew];
76305         pNew->iParent = idxTerm;
76306         pTerm = &pWC->a[idxTerm];
76307         pTerm->nChild = 1;
76308         pTerm->flags |= TERM_COPIED;
76309       }else{
76310         pDup = pExpr;
76311         pNew = pTerm;
76312       }
76313       exprCommute(pParse, pDup);
76314       pLeft = pDup->pLeft;
76315       pNew->leftCursor = pLeft->iTable;
76316       pNew->leftColumn = pLeft->iColumn;
76317       pNew->prereqRight = prereqLeft;
76318       pNew->prereqAll = prereqAll;
76319       pNew->eOperator = operatorMask(pDup->op);
76320     }
76321   }
76322
76323 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
76324   /* If a term is the BETWEEN operator, create two new virtual terms
76325   ** that define the range that the BETWEEN implements.
76326   */
76327   else if( pExpr->op==TK_BETWEEN ){
76328     ExprList *pList = pExpr->pList;
76329     int i;
76330     static const u8 ops[] = {TK_GE, TK_LE};
76331     assert( pList!=0 );
76332     assert( pList->nExpr==2 );
76333     for(i=0; i<2; i++){
76334       Expr *pNewExpr;
76335       int idxNew;
76336       pNewExpr = sqlite3Expr(db, ops[i], sqlite3ExprDup(db, pExpr->pLeft),
76337                              sqlite3ExprDup(db, pList->a[i].pExpr), 0);
76338       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
76339       exprAnalyze(pSrc, pWC, idxNew);
76340       pTerm = &pWC->a[idxTerm];
76341       pWC->a[idxNew].iParent = idxTerm;
76342     }
76343     pTerm->nChild = 2;
76344   }
76345 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
76346
76347 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
76348   /* Attempt to convert OR-connected terms into an IN operator so that
76349   ** they can make use of indices.  Example:
76350   **
76351   **      x = expr1  OR  expr2 = x  OR  x = expr3
76352   **
76353   ** is converted into
76354   **
76355   **      x IN (expr1,expr2,expr3)
76356   **
76357   ** This optimization must be omitted if OMIT_SUBQUERY is defined because
76358   ** the compiler for the the IN operator is part of sub-queries.
76359   */
76360   else if( pExpr->op==TK_OR ){
76361     int ok;
76362     int i, j;
76363     int iColumn, iCursor;
76364     WhereClause sOr;
76365     WhereTerm *pOrTerm;
76366
76367     assert( (pTerm->flags & TERM_DYNAMIC)==0 );
76368     whereClauseInit(&sOr, pWC->pParse, pMaskSet);
76369     whereSplit(&sOr, pExpr, TK_OR);
76370     exprAnalyzeAll(pSrc, &sOr);
76371     assert( sOr.nTerm>=2 );
76372     j = 0;
76373     if( db->mallocFailed ) goto or_not_possible;
76374     do{
76375       assert( j<sOr.nTerm );
76376       iColumn = sOr.a[j].leftColumn;
76377       iCursor = sOr.a[j].leftCursor;
76378       ok = iCursor>=0;
76379       for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0 && ok; i--, pOrTerm++){
76380         if( pOrTerm->eOperator!=WO_EQ ){
76381           goto or_not_possible;
76382         }
76383         if( orTermIsOptCandidate(pOrTerm, iCursor, iColumn) ){
76384           pOrTerm->flags |= TERM_OR_OK;
76385         }else if( orTermHasOkDuplicate(&sOr, pOrTerm) ){
76386           pOrTerm->flags &= ~TERM_OR_OK;
76387         }else{
76388           ok = 0;
76389         }
76390       }
76391     }while( !ok && (sOr.a[j++].flags & TERM_COPIED)!=0 && j<2 );
76392     if( ok ){
76393       ExprList *pList = 0;
76394       Expr *pNew, *pDup;
76395       Expr *pLeft = 0;
76396       for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0; i--, pOrTerm++){
76397         if( (pOrTerm->flags & TERM_OR_OK)==0 ) continue;
76398         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight);
76399         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup, 0);
76400         pLeft = pOrTerm->pExpr->pLeft;
76401       }
76402       assert( pLeft!=0 );
76403       pDup = sqlite3ExprDup(db, pLeft);
76404       pNew = sqlite3Expr(db, TK_IN, pDup, 0, 0);
76405       if( pNew ){
76406         int idxNew;
76407         transferJoinMarkings(pNew, pExpr);
76408         pNew->pList = pList;
76409         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
76410         exprAnalyze(pSrc, pWC, idxNew);
76411         pTerm = &pWC->a[idxTerm];
76412         pWC->a[idxNew].iParent = idxTerm;
76413         pTerm->nChild = 1;
76414       }else{
76415         sqlite3ExprListDelete(db, pList);
76416       }
76417     }
76418 or_not_possible:
76419     whereClauseClear(&sOr);
76420   }
76421 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
76422
76423 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
76424   /* Add constraints to reduce the search space on a LIKE or GLOB
76425   ** operator.
76426   **
76427   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
76428   **
76429   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
76430   **
76431   ** The last character of the prefix "abc" is incremented to form the
76432   ** termination condition "abd".
76433   */
76434   if( isLikeOrGlob(pParse, pExpr, &nPattern, &isComplete, &noCase) ){
76435     Expr *pLeft, *pRight;
76436     Expr *pStr1, *pStr2;
76437     Expr *pNewExpr1, *pNewExpr2;
76438     int idxNew1, idxNew2;
76439
76440     pLeft = pExpr->pList->a[1].pExpr;
76441     pRight = pExpr->pList->a[0].pExpr;
76442     pStr1 = sqlite3PExpr(pParse, TK_STRING, 0, 0, 0);
76443     if( pStr1 ){
76444       sqlite3TokenCopy(db, &pStr1->token, &pRight->token);
76445       pStr1->token.n = nPattern;
76446       pStr1->flags = EP_Dequoted;
76447     }
76448     pStr2 = sqlite3ExprDup(db, pStr1);
76449     if( !db->mallocFailed ){
76450       u8 c, *pC;
76451       assert( pStr2->token.dyn );
76452       pC = (u8*)&pStr2->token.z[nPattern-1];
76453       c = *pC;
76454       if( noCase ){
76455         if( c=='@' ) isComplete = 0;
76456         c = sqlite3UpperToLower[c];
76457       }
76458       *pC = c + 1;
76459     }
76460     pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprDup(db,pLeft), pStr1, 0);
76461     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
76462     exprAnalyze(pSrc, pWC, idxNew1);
76463     pNewExpr2 = sqlite3PExpr(pParse, TK_LT, sqlite3ExprDup(db,pLeft), pStr2, 0);
76464     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
76465     exprAnalyze(pSrc, pWC, idxNew2);
76466     pTerm = &pWC->a[idxTerm];
76467     if( isComplete ){
76468       pWC->a[idxNew1].iParent = idxTerm;
76469       pWC->a[idxNew2].iParent = idxTerm;
76470       pTerm->nChild = 2;
76471     }
76472   }
76473 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
76474
76475 #ifndef SQLITE_OMIT_VIRTUALTABLE
76476   /* Add a WO_MATCH auxiliary term to the constraint set if the
76477   ** current expression is of the form:  column MATCH expr.
76478   ** This information is used by the xBestIndex methods of
76479   ** virtual tables.  The native query optimizer does not attempt
76480   ** to do anything with MATCH functions.
76481   */
76482   if( isMatchOfColumn(pExpr) ){
76483     int idxNew;
76484     Expr *pRight, *pLeft;
76485     WhereTerm *pNewTerm;
76486     Bitmask prereqColumn, prereqExpr;
76487
76488     pRight = pExpr->pList->a[0].pExpr;
76489     pLeft = pExpr->pList->a[1].pExpr;
76490     prereqExpr = exprTableUsage(pMaskSet, pRight);
76491     prereqColumn = exprTableUsage(pMaskSet, pLeft);
76492     if( (prereqExpr & prereqColumn)==0 ){
76493       Expr *pNewExpr;
76494       pNewExpr = sqlite3Expr(db, TK_MATCH, 0, sqlite3ExprDup(db, pRight), 0);
76495       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
76496       pNewTerm = &pWC->a[idxNew];
76497       pNewTerm->prereqRight = prereqExpr;
76498       pNewTerm->leftCursor = pLeft->iTable;
76499       pNewTerm->leftColumn = pLeft->iColumn;
76500       pNewTerm->eOperator = WO_MATCH;
76501       pNewTerm->iParent = idxTerm;
76502       pTerm = &pWC->a[idxTerm];
76503       pTerm->nChild = 1;
76504       pTerm->flags |= TERM_COPIED;
76505       pNewTerm->prereqAll = pTerm->prereqAll;
76506     }
76507   }
76508 #endif /* SQLITE_OMIT_VIRTUALTABLE */
76509
76510   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
76511   ** an index for tables to the left of the join.
76512   */
76513   pTerm->prereqRight |= extraRight;
76514 }
76515
76516 /*
76517 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
76518 ** a reference to any table other than the iBase table.
76519 */
76520 static int referencesOtherTables(
76521   ExprList *pList,          /* Search expressions in ths list */
76522   ExprMaskSet *pMaskSet,    /* Mapping from tables to bitmaps */
76523   int iFirst,               /* Be searching with the iFirst-th expression */
76524   int iBase                 /* Ignore references to this table */
76525 ){
76526   Bitmask allowed = ~getMask(pMaskSet, iBase);
76527   while( iFirst<pList->nExpr ){
76528     if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
76529       return 1;
76530     }
76531   }
76532   return 0;
76533 }
76534
76535
76536 /*
76537 ** This routine decides if pIdx can be used to satisfy the ORDER BY
76538 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
76539 ** ORDER BY clause, this routine returns 0.
76540 **
76541 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
76542 ** left-most table in the FROM clause of that same SELECT statement and
76543 ** the table has a cursor number of "base".  pIdx is an index on pTab.
76544 **
76545 ** nEqCol is the number of columns of pIdx that are used as equality
76546 ** constraints.  Any of these columns may be missing from the ORDER BY
76547 ** clause and the match can still be a success.
76548 **
76549 ** All terms of the ORDER BY that match against the index must be either
76550 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
76551 ** index do not need to satisfy this constraint.)  The *pbRev value is
76552 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
76553 ** the ORDER BY clause is all ASC.
76554 */
76555 static int isSortingIndex(
76556   Parse *pParse,          /* Parsing context */
76557   ExprMaskSet *pMaskSet,  /* Mapping from table indices to bitmaps */
76558   Index *pIdx,            /* The index we are testing */
76559   int base,               /* Cursor number for the table to be sorted */
76560   ExprList *pOrderBy,     /* The ORDER BY clause */
76561   int nEqCol,             /* Number of index columns with == constraints */
76562   int *pbRev              /* Set to 1 if ORDER BY is DESC */
76563 ){
76564   int i, j;                       /* Loop counters */
76565   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
76566   int nTerm;                      /* Number of ORDER BY terms */
76567   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
76568   sqlite3 *db = pParse->db;
76569
76570   assert( pOrderBy!=0 );
76571   nTerm = pOrderBy->nExpr;
76572   assert( nTerm>0 );
76573
76574   /* Match terms of the ORDER BY clause against columns of
76575   ** the index.
76576   **
76577   ** Note that indices have pIdx->nColumn regular columns plus
76578   ** one additional column containing the rowid.  The rowid column
76579   ** of the index is also allowed to match against the ORDER BY
76580   ** clause.
76581   */
76582   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
76583     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
76584     CollSeq *pColl;    /* The collating sequence of pExpr */
76585     int termSortOrder; /* Sort order for this term */
76586     int iColumn;       /* The i-th column of the index.  -1 for rowid */
76587     int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
76588     const char *zColl; /* Name of the collating sequence for i-th index term */
76589
76590     pExpr = pTerm->pExpr;
76591     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
76592       /* Can not use an index sort on anything that is not a column in the
76593       ** left-most table of the FROM clause */
76594       break;
76595     }
76596     pColl = sqlite3ExprCollSeq(pParse, pExpr);
76597     if( !pColl ){
76598       pColl = db->pDfltColl;
76599     }
76600     if( i<pIdx->nColumn ){
76601       iColumn = pIdx->aiColumn[i];
76602       if( iColumn==pIdx->pTable->iPKey ){
76603         iColumn = -1;
76604       }
76605       iSortOrder = pIdx->aSortOrder[i];
76606       zColl = pIdx->azColl[i];
76607     }else{
76608       iColumn = -1;
76609       iSortOrder = 0;
76610       zColl = pColl->zName;
76611     }
76612     if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
76613       /* Term j of the ORDER BY clause does not match column i of the index */
76614       if( i<nEqCol ){
76615         /* If an index column that is constrained by == fails to match an
76616         ** ORDER BY term, that is OK.  Just ignore that column of the index
76617         */
76618         continue;
76619       }else if( i==pIdx->nColumn ){
76620         /* Index column i is the rowid.  All other terms match. */
76621         break;
76622       }else{
76623         /* If an index column fails to match and is not constrained by ==
76624         ** then the index cannot satisfy the ORDER BY constraint.
76625         */
76626         return 0;
76627       }
76628     }
76629     assert( pIdx->aSortOrder!=0 );
76630     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
76631     assert( iSortOrder==0 || iSortOrder==1 );
76632     termSortOrder = iSortOrder ^ pTerm->sortOrder;
76633     if( i>nEqCol ){
76634       if( termSortOrder!=sortOrder ){
76635         /* Indices can only be used if all ORDER BY terms past the
76636         ** equality constraints are all either DESC or ASC. */
76637         return 0;
76638       }
76639     }else{
76640       sortOrder = termSortOrder;
76641     }
76642     j++;
76643     pTerm++;
76644     if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
76645       /* If the indexed column is the primary key and everything matches
76646       ** so far and none of the ORDER BY terms to the right reference other
76647       ** tables in the join, then we are assured that the index can be used 
76648       ** to sort because the primary key is unique and so none of the other
76649       ** columns will make any difference
76650       */
76651       j = nTerm;
76652     }
76653   }
76654
76655   *pbRev = sortOrder!=0;
76656   if( j>=nTerm ){
76657     /* All terms of the ORDER BY clause are covered by this index so
76658     ** this index can be used for sorting. */
76659     return 1;
76660   }
76661   if( pIdx->onError!=OE_None && i==pIdx->nColumn
76662       && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
76663     /* All terms of this index match some prefix of the ORDER BY clause
76664     ** and the index is UNIQUE and no terms on the tail of the ORDER BY
76665     ** clause reference other tables in a join.  If this is all true then
76666     ** the order by clause is superfluous. */
76667     return 1;
76668   }
76669   return 0;
76670 }
76671
76672 /*
76673 ** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
76674 ** by sorting in order of ROWID.  Return true if so and set *pbRev to be
76675 ** true for reverse ROWID and false for forward ROWID order.
76676 */
76677 static int sortableByRowid(
76678   int base,               /* Cursor number for table to be sorted */
76679   ExprList *pOrderBy,     /* The ORDER BY clause */
76680   ExprMaskSet *pMaskSet,  /* Mapping from tables to bitmaps */
76681   int *pbRev              /* Set to 1 if ORDER BY is DESC */
76682 ){
76683   Expr *p;
76684
76685   assert( pOrderBy!=0 );
76686   assert( pOrderBy->nExpr>0 );
76687   p = pOrderBy->a[0].pExpr;
76688   if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1
76689     && !referencesOtherTables(pOrderBy, pMaskSet, 1, base) ){
76690     *pbRev = pOrderBy->a[0].sortOrder;
76691     return 1;
76692   }
76693   return 0;
76694 }
76695
76696 /*
76697 ** Prepare a crude estimate of the logarithm of the input value.
76698 ** The results need not be exact.  This is only used for estimating
76699 ** the total cost of performing operations with O(logN) or O(NlogN)
76700 ** complexity.  Because N is just a guess, it is no great tragedy if
76701 ** logN is a little off.
76702 */
76703 static double estLog(double N){
76704   double logN = 1;
76705   double x = 10;
76706   while( N>x ){
76707     logN += 1;
76708     x *= 10;
76709   }
76710   return logN;
76711 }
76712
76713 /*
76714 ** Two routines for printing the content of an sqlite3_index_info
76715 ** structure.  Used for testing and debugging only.  If neither
76716 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
76717 ** are no-ops.
76718 */
76719 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
76720 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
76721   int i;
76722   if( !sqlite3WhereTrace ) return;
76723   for(i=0; i<p->nConstraint; i++){
76724     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
76725        i,
76726        p->aConstraint[i].iColumn,
76727        p->aConstraint[i].iTermOffset,
76728        p->aConstraint[i].op,
76729        p->aConstraint[i].usable);
76730   }
76731   for(i=0; i<p->nOrderBy; i++){
76732     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
76733        i,
76734        p->aOrderBy[i].iColumn,
76735        p->aOrderBy[i].desc);
76736   }
76737 }
76738 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
76739   int i;
76740   if( !sqlite3WhereTrace ) return;
76741   for(i=0; i<p->nConstraint; i++){
76742     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
76743        i,
76744        p->aConstraintUsage[i].argvIndex,
76745        p->aConstraintUsage[i].omit);
76746   }
76747   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
76748   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
76749   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
76750   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
76751 }
76752 #else
76753 #define TRACE_IDX_INPUTS(A)
76754 #define TRACE_IDX_OUTPUTS(A)
76755 #endif
76756
76757 #ifndef SQLITE_OMIT_VIRTUALTABLE
76758 /*
76759 ** Compute the best index for a virtual table.
76760 **
76761 ** The best index is computed by the xBestIndex method of the virtual
76762 ** table module.  This routine is really just a wrapper that sets up
76763 ** the sqlite3_index_info structure that is used to communicate with
76764 ** xBestIndex.
76765 **
76766 ** In a join, this routine might be called multiple times for the
76767 ** same virtual table.  The sqlite3_index_info structure is created
76768 ** and initialized on the first invocation and reused on all subsequent
76769 ** invocations.  The sqlite3_index_info structure is also used when
76770 ** code is generated to access the virtual table.  The whereInfoDelete() 
76771 ** routine takes care of freeing the sqlite3_index_info structure after
76772 ** everybody has finished with it.
76773 */
76774 static double bestVirtualIndex(
76775   Parse *pParse,                 /* The parsing context */
76776   WhereClause *pWC,              /* The WHERE clause */
76777   struct SrcList_item *pSrc,     /* The FROM clause term to search */
76778   Bitmask notReady,              /* Mask of cursors that are not available */
76779   ExprList *pOrderBy,            /* The order by clause */
76780   int orderByUsable,             /* True if we can potential sort */
76781   sqlite3_index_info **ppIdxInfo /* Index information passed to xBestIndex */
76782 ){
76783   Table *pTab = pSrc->pTab;
76784   sqlite3_vtab *pVtab = pTab->pVtab;
76785   sqlite3_index_info *pIdxInfo;
76786   struct sqlite3_index_constraint *pIdxCons;
76787   struct sqlite3_index_orderby *pIdxOrderBy;
76788   struct sqlite3_index_constraint_usage *pUsage;
76789   WhereTerm *pTerm;
76790   int i, j;
76791   int nOrderBy;
76792   int rc;
76793
76794   /* If the sqlite3_index_info structure has not been previously
76795   ** allocated and initialized for this virtual table, then allocate
76796   ** and initialize it now
76797   */
76798   pIdxInfo = *ppIdxInfo;
76799   if( pIdxInfo==0 ){
76800     WhereTerm *pTerm;
76801     int nTerm;
76802     WHERETRACE(("Recomputing index info for %s...\n", pTab->zName));
76803
76804     /* Count the number of possible WHERE clause constraints referring
76805     ** to this virtual table */
76806     for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
76807       if( pTerm->leftCursor != pSrc->iCursor ) continue;
76808       assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
76809       testcase( pTerm->eOperator==WO_IN );
76810       testcase( pTerm->eOperator==WO_ISNULL );
76811       if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
76812       nTerm++;
76813     }
76814
76815     /* If the ORDER BY clause contains only columns in the current 
76816     ** virtual table then allocate space for the aOrderBy part of
76817     ** the sqlite3_index_info structure.
76818     */
76819     nOrderBy = 0;
76820     if( pOrderBy ){
76821       for(i=0; i<pOrderBy->nExpr; i++){
76822         Expr *pExpr = pOrderBy->a[i].pExpr;
76823         if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
76824       }
76825       if( i==pOrderBy->nExpr ){
76826         nOrderBy = pOrderBy->nExpr;
76827       }
76828     }
76829
76830     /* Allocate the sqlite3_index_info structure
76831     */
76832     pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
76833                              + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
76834                              + sizeof(*pIdxOrderBy)*nOrderBy );
76835     if( pIdxInfo==0 ){
76836       sqlite3ErrorMsg(pParse, "out of memory");
76837       return 0.0;
76838     }
76839     *ppIdxInfo = pIdxInfo;
76840
76841     /* Initialize the structure.  The sqlite3_index_info structure contains
76842     ** many fields that are declared "const" to prevent xBestIndex from
76843     ** changing them.  We have to do some funky casting in order to
76844     ** initialize those fields.
76845     */
76846     pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
76847     pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
76848     pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
76849     *(int*)&pIdxInfo->nConstraint = nTerm;
76850     *(int*)&pIdxInfo->nOrderBy = nOrderBy;
76851     *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
76852     *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
76853     *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
76854                                                                      pUsage;
76855
76856     for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
76857       if( pTerm->leftCursor != pSrc->iCursor ) continue;
76858       assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
76859       testcase( pTerm->eOperator==WO_IN );
76860       testcase( pTerm->eOperator==WO_ISNULL );
76861       if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
76862       pIdxCons[j].iColumn = pTerm->leftColumn;
76863       pIdxCons[j].iTermOffset = i;
76864       pIdxCons[j].op = pTerm->eOperator;
76865       /* The direct assignment in the previous line is possible only because
76866       ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
76867       ** following asserts verify this fact. */
76868       assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
76869       assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
76870       assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
76871       assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
76872       assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
76873       assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
76874       assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
76875       j++;
76876     }
76877     for(i=0; i<nOrderBy; i++){
76878       Expr *pExpr = pOrderBy->a[i].pExpr;
76879       pIdxOrderBy[i].iColumn = pExpr->iColumn;
76880       pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
76881     }
76882   }
76883
76884   /* At this point, the sqlite3_index_info structure that pIdxInfo points
76885   ** to will have been initialized, either during the current invocation or
76886   ** during some prior invocation.  Now we just have to customize the
76887   ** details of pIdxInfo for the current invocation and pass it to
76888   ** xBestIndex.
76889   */
76890
76891   /* The module name must be defined. Also, by this point there must
76892   ** be a pointer to an sqlite3_vtab structure. Otherwise
76893   ** sqlite3ViewGetColumnNames() would have picked up the error. 
76894   */
76895   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
76896   assert( pVtab );
76897 #if 0
76898   if( pTab->pVtab==0 ){
76899     sqlite3ErrorMsg(pParse, "undefined module %s for table %s",
76900         pTab->azModuleArg[0], pTab->zName);
76901     return 0.0;
76902   }
76903 #endif
76904
76905   /* Set the aConstraint[].usable fields and initialize all 
76906   ** output variables to zero.
76907   **
76908   ** aConstraint[].usable is true for constraints where the right-hand
76909   ** side contains only references to tables to the left of the current
76910   ** table.  In other words, if the constraint is of the form:
76911   **
76912   **           column = expr
76913   **
76914   ** and we are evaluating a join, then the constraint on column is 
76915   ** only valid if all tables referenced in expr occur to the left
76916   ** of the table containing column.
76917   **
76918   ** The aConstraints[] array contains entries for all constraints
76919   ** on the current table.  That way we only have to compute it once
76920   ** even though we might try to pick the best index multiple times.
76921   ** For each attempt at picking an index, the order of tables in the
76922   ** join might be different so we have to recompute the usable flag
76923   ** each time.
76924   */
76925   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
76926   pUsage = pIdxInfo->aConstraintUsage;
76927   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
76928     j = pIdxCons->iTermOffset;
76929     pTerm = &pWC->a[j];
76930     pIdxCons->usable =  (pTerm->prereqRight & notReady)==0;
76931   }
76932   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
76933   if( pIdxInfo->needToFreeIdxStr ){
76934     sqlite3_free(pIdxInfo->idxStr);
76935   }
76936   pIdxInfo->idxStr = 0;
76937   pIdxInfo->idxNum = 0;
76938   pIdxInfo->needToFreeIdxStr = 0;
76939   pIdxInfo->orderByConsumed = 0;
76940   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / 2.0;
76941   nOrderBy = pIdxInfo->nOrderBy;
76942   if( pIdxInfo->nOrderBy && !orderByUsable ){
76943     *(int*)&pIdxInfo->nOrderBy = 0;
76944   }
76945
76946   (void)sqlite3SafetyOff(pParse->db);
76947   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
76948   TRACE_IDX_INPUTS(pIdxInfo);
76949   rc = pVtab->pModule->xBestIndex(pVtab, pIdxInfo);
76950   TRACE_IDX_OUTPUTS(pIdxInfo);
76951   (void)sqlite3SafetyOn(pParse->db);
76952
76953   if( rc!=SQLITE_OK ){
76954     if( rc==SQLITE_NOMEM ){
76955       pParse->db->mallocFailed = 1;
76956     }else if( !pVtab->zErrMsg ){
76957       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
76958     }else{
76959       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
76960     }
76961   }
76962   sqlite3DbFree(pParse->db, pVtab->zErrMsg);
76963   pVtab->zErrMsg = 0;
76964
76965   for(i=0; i<pIdxInfo->nConstraint; i++){
76966     if( !pIdxInfo->aConstraint[i].usable && pUsage[i].argvIndex>0 ){
76967       sqlite3ErrorMsg(pParse, 
76968           "table %s: xBestIndex returned an invalid plan", pTab->zName);
76969       return 0.0;
76970     }
76971   }
76972
76973   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
76974   return pIdxInfo->estimatedCost;
76975 }
76976 #endif /* SQLITE_OMIT_VIRTUALTABLE */
76977
76978 /*
76979 ** Find the best index for accessing a particular table.  Return a pointer
76980 ** to the index, flags that describe how the index should be used, the
76981 ** number of equality constraints, and the "cost" for this index.
76982 **
76983 ** The lowest cost index wins.  The cost is an estimate of the amount of
76984 ** CPU and disk I/O need to process the request using the selected index.
76985 ** Factors that influence cost include:
76986 **
76987 **    *  The estimated number of rows that will be retrieved.  (The
76988 **       fewer the better.)
76989 **
76990 **    *  Whether or not sorting must occur.
76991 **
76992 **    *  Whether or not there must be separate lookups in the
76993 **       index and in the main table.
76994 **
76995 */
76996 static double bestIndex(
76997   Parse *pParse,              /* The parsing context */
76998   WhereClause *pWC,           /* The WHERE clause */
76999   struct SrcList_item *pSrc,  /* The FROM clause term to search */
77000   Bitmask notReady,           /* Mask of cursors that are not available */
77001   ExprList *pOrderBy,         /* The order by clause */
77002   Index **ppIndex,            /* Make *ppIndex point to the best index */
77003   int *pFlags,                /* Put flags describing this choice in *pFlags */
77004   int *pnEq                   /* Put the number of == or IN constraints here */
77005 ){
77006   WhereTerm *pTerm;
77007   Index *bestIdx = 0;         /* Index that gives the lowest cost */
77008   double lowestCost;          /* The cost of using bestIdx */
77009   int bestFlags = 0;          /* Flags associated with bestIdx */
77010   int bestNEq = 0;            /* Best value for nEq */
77011   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
77012   Index *pProbe;              /* An index we are evaluating */
77013   int rev;                    /* True to scan in reverse order */
77014   int flags;                  /* Flags associated with pProbe */
77015   int nEq;                    /* Number of == or IN constraints */
77016   int eqTermMask;             /* Mask of valid equality operators */
77017   double cost;                /* Cost of using pProbe */
77018
77019   WHERETRACE(("bestIndex: tbl=%s notReady=%llx\n", pSrc->pTab->zName, notReady));
77020   lowestCost = SQLITE_BIG_DBL;
77021   pProbe = pSrc->pTab->pIndex;
77022
77023   /* If the table has no indices and there are no terms in the where
77024   ** clause that refer to the ROWID, then we will never be able to do
77025   ** anything other than a full table scan on this table.  We might as
77026   ** well put it first in the join order.  That way, perhaps it can be
77027   ** referenced by other tables in the join.
77028   */
77029   if( pProbe==0 &&
77030      findTerm(pWC, iCur, -1, 0, WO_EQ|WO_IN|WO_LT|WO_LE|WO_GT|WO_GE,0)==0 &&
77031      (pOrderBy==0 || !sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev)) ){
77032     *pFlags = 0;
77033     *ppIndex = 0;
77034     *pnEq = 0;
77035     return 0.0;
77036   }
77037
77038   /* Check for a rowid=EXPR or rowid IN (...) constraints
77039   */
77040   pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
77041   if( pTerm ){
77042     Expr *pExpr;
77043     *ppIndex = 0;
77044     bestFlags = WHERE_ROWID_EQ;
77045     if( pTerm->eOperator & WO_EQ ){
77046       /* Rowid== is always the best pick.  Look no further.  Because only
77047       ** a single row is generated, output is always in sorted order */
77048       *pFlags = WHERE_ROWID_EQ | WHERE_UNIQUE;
77049       *pnEq = 1;
77050       WHERETRACE(("... best is rowid\n"));
77051       return 0.0;
77052     }else if( (pExpr = pTerm->pExpr)->pList!=0 ){
77053       /* Rowid IN (LIST): cost is NlogN where N is the number of list
77054       ** elements.  */
77055       lowestCost = pExpr->pList->nExpr;
77056       lowestCost *= estLog(lowestCost);
77057     }else{
77058       /* Rowid IN (SELECT): cost is NlogN where N is the number of rows
77059       ** in the result of the inner select.  We have no way to estimate
77060       ** that value so make a wild guess. */
77061       lowestCost = 200;
77062     }
77063     WHERETRACE(("... rowid IN cost: %.9g\n", lowestCost));
77064   }
77065
77066   /* Estimate the cost of a table scan.  If we do not know how many
77067   ** entries are in the table, use 1 million as a guess.
77068   */
77069   cost = pProbe ? pProbe->aiRowEst[0] : 1000000;
77070   WHERETRACE(("... table scan base cost: %.9g\n", cost));
77071   flags = WHERE_ROWID_RANGE;
77072
77073   /* Check for constraints on a range of rowids in a table scan.
77074   */
77075   pTerm = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE|WO_GT|WO_GE, 0);
77076   if( pTerm ){
77077     if( findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0) ){
77078       flags |= WHERE_TOP_LIMIT;
77079       cost /= 3;  /* Guess that rowid<EXPR eliminates two-thirds or rows */
77080     }
77081     if( findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0) ){
77082       flags |= WHERE_BTM_LIMIT;
77083       cost /= 3;  /* Guess that rowid>EXPR eliminates two-thirds of rows */
77084     }
77085     WHERETRACE(("... rowid range reduces cost to %.9g\n", cost));
77086   }else{
77087     flags = 0;
77088   }
77089
77090   /* If the table scan does not satisfy the ORDER BY clause, increase
77091   ** the cost by NlogN to cover the expense of sorting. */
77092   if( pOrderBy ){
77093     if( sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev) ){
77094       flags |= WHERE_ORDERBY|WHERE_ROWID_RANGE;
77095       if( rev ){
77096         flags |= WHERE_REVERSE;
77097       }
77098     }else{
77099       cost += cost*estLog(cost);
77100       WHERETRACE(("... sorting increases cost to %.9g\n", cost));
77101     }
77102   }
77103   if( cost<lowestCost ){
77104     lowestCost = cost;
77105     bestFlags = flags;
77106   }
77107
77108   /* If the pSrc table is the right table of a LEFT JOIN then we may not
77109   ** use an index to satisfy IS NULL constraints on that table.  This is
77110   ** because columns might end up being NULL if the table does not match -
77111   ** a circumstance which the index cannot help us discover.  Ticket #2177.
77112   */
77113   if( (pSrc->jointype & JT_LEFT)!=0 ){
77114     eqTermMask = WO_EQ|WO_IN;
77115   }else{
77116     eqTermMask = WO_EQ|WO_IN|WO_ISNULL;
77117   }
77118
77119   /* Look at each index.
77120   */
77121   for(; pProbe; pProbe=pProbe->pNext){
77122     int i;                       /* Loop counter */
77123     double inMultiplier = 1;
77124
77125     WHERETRACE(("... index %s:\n", pProbe->zName));
77126
77127     /* Count the number of columns in the index that are satisfied
77128     ** by x=EXPR constraints or x IN (...) constraints.
77129     */
77130     flags = 0;
77131     for(i=0; i<pProbe->nColumn; i++){
77132       int j = pProbe->aiColumn[i];
77133       pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pProbe);
77134       if( pTerm==0 ) break;
77135       flags |= WHERE_COLUMN_EQ;
77136       if( pTerm->eOperator & WO_IN ){
77137         Expr *pExpr = pTerm->pExpr;
77138         flags |= WHERE_COLUMN_IN;
77139         if( pExpr->pSelect!=0 ){
77140           inMultiplier *= 25;
77141         }else if( ALWAYS(pExpr->pList) ){
77142           inMultiplier *= pExpr->pList->nExpr + 1;
77143         }
77144       }
77145     }
77146     cost = pProbe->aiRowEst[i] * inMultiplier * estLog(inMultiplier);
77147     nEq = i;
77148     if( pProbe->onError!=OE_None && (flags & WHERE_COLUMN_IN)==0
77149          && nEq==pProbe->nColumn ){
77150       flags |= WHERE_UNIQUE;
77151     }
77152     WHERETRACE(("...... nEq=%d inMult=%.9g cost=%.9g\n",nEq,inMultiplier,cost));
77153
77154     /* Look for range constraints
77155     */
77156     if( nEq<pProbe->nColumn ){
77157       int j = pProbe->aiColumn[nEq];
77158       pTerm = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pProbe);
77159       if( pTerm ){
77160         flags |= WHERE_COLUMN_RANGE;
77161         if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pProbe) ){
77162           flags |= WHERE_TOP_LIMIT;
77163           cost /= 3;
77164         }
77165         if( findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pProbe) ){
77166           flags |= WHERE_BTM_LIMIT;
77167           cost /= 3;
77168         }
77169         WHERETRACE(("...... range reduces cost to %.9g\n", cost));
77170       }
77171     }
77172
77173     /* Add the additional cost of sorting if that is a factor.
77174     */
77175     if( pOrderBy ){
77176       if( (flags & WHERE_COLUMN_IN)==0 &&
77177            isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev) ){
77178         if( flags==0 ){
77179           flags = WHERE_COLUMN_RANGE;
77180         }
77181         flags |= WHERE_ORDERBY;
77182         if( rev ){
77183           flags |= WHERE_REVERSE;
77184         }
77185       }else{
77186         cost += cost*estLog(cost);
77187         WHERETRACE(("...... orderby increases cost to %.9g\n", cost));
77188       }
77189     }
77190
77191     /* Check to see if we can get away with using just the index without
77192     ** ever reading the table.  If that is the case, then halve the
77193     ** cost of this index.
77194     */
77195     if( flags && pSrc->colUsed < (((Bitmask)1)<<(BMS-1)) ){
77196       Bitmask m = pSrc->colUsed;
77197       int j;
77198       for(j=0; j<pProbe->nColumn; j++){
77199         int x = pProbe->aiColumn[j];
77200         if( x<BMS-1 ){
77201           m &= ~(((Bitmask)1)<<x);
77202         }
77203       }
77204       if( m==0 ){
77205         flags |= WHERE_IDX_ONLY;
77206         cost /= 2;
77207         WHERETRACE(("...... idx-only reduces cost to %.9g\n", cost));
77208       }
77209     }
77210
77211     /* If this index has achieved the lowest cost so far, then use it.
77212     */
77213     if( flags && cost < lowestCost ){
77214       bestIdx = pProbe;
77215       lowestCost = cost;
77216       bestFlags = flags;
77217       bestNEq = nEq;
77218     }
77219   }
77220
77221   /* Report the best result
77222   */
77223   *ppIndex = bestIdx;
77224   WHERETRACE(("best index is %s, cost=%.9g, flags=%x, nEq=%d\n",
77225         bestIdx ? bestIdx->zName : "(none)", lowestCost, bestFlags, bestNEq));
77226   *pFlags = bestFlags | eqTermMask;
77227   *pnEq = bestNEq;
77228   return lowestCost;
77229 }
77230
77231
77232 /*
77233 ** Disable a term in the WHERE clause.  Except, do not disable the term
77234 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
77235 ** or USING clause of that join.
77236 **
77237 ** Consider the term t2.z='ok' in the following queries:
77238 **
77239 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
77240 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
77241 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
77242 **
77243 ** The t2.z='ok' is disabled in the in (2) because it originates
77244 ** in the ON clause.  The term is disabled in (3) because it is not part
77245 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
77246 **
77247 ** Disabling a term causes that term to not be tested in the inner loop
77248 ** of the join.  Disabling is an optimization.  When terms are satisfied
77249 ** by indices, we disable them to prevent redundant tests in the inner
77250 ** loop.  We would get the correct results if nothing were ever disabled,
77251 ** but joins might run a little slower.  The trick is to disable as much
77252 ** as we can without disabling too much.  If we disabled in (1), we'd get
77253 ** the wrong answer.  See ticket #813.
77254 */
77255 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
77256   if( pTerm
77257       && ALWAYS((pTerm->flags & TERM_CODED)==0)
77258       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
77259   ){
77260     pTerm->flags |= TERM_CODED;
77261     if( pTerm->iParent>=0 ){
77262       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
77263       if( (--pOther->nChild)==0 ){
77264         disableTerm(pLevel, pOther);
77265       }
77266     }
77267   }
77268 }
77269
77270 /*
77271 ** Apply the affinities associated with the first n columns of index
77272 ** pIdx to the values in the n registers starting at base.
77273 */
77274 static void codeApplyAffinity(Parse *pParse, int base, int n, Index *pIdx){
77275   if( n>0 ){
77276     Vdbe *v = pParse->pVdbe;
77277     assert( v!=0 );
77278     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
77279     sqlite3IndexAffinityStr(v, pIdx);
77280     sqlite3ExprCacheAffinityChange(pParse, base, n);
77281   }
77282 }
77283
77284
77285 /*
77286 ** Generate code for a single equality term of the WHERE clause.  An equality
77287 ** term can be either X=expr or X IN (...).   pTerm is the term to be 
77288 ** coded.
77289 **
77290 ** The current value for the constraint is left in register iReg.
77291 **
77292 ** For a constraint of the form X=expr, the expression is evaluated and its
77293 ** result is left on the stack.  For constraints of the form X IN (...)
77294 ** this routine sets up a loop that will iterate over all values of X.
77295 */
77296 static int codeEqualityTerm(
77297   Parse *pParse,      /* The parsing context */
77298   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
77299   WhereLevel *pLevel, /* When level of the FROM clause we are working on */
77300   int iTarget         /* Attempt to leave results in this register */
77301 ){
77302   Expr *pX = pTerm->pExpr;
77303   Vdbe *v = pParse->pVdbe;
77304   int iReg;                  /* Register holding results */
77305
77306   if( iTarget<=0 ){
77307     iReg = iTarget = sqlite3GetTempReg(pParse);
77308   }
77309   if( pX->op==TK_EQ ){
77310     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
77311   }else if( pX->op==TK_ISNULL ){
77312     iReg = iTarget;
77313     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
77314 #ifndef SQLITE_OMIT_SUBQUERY
77315   }else{
77316     int eType;
77317     int iTab;
77318     struct InLoop *pIn;
77319
77320     assert( pX->op==TK_IN );
77321     iReg = iTarget;
77322     eType = sqlite3FindInIndex(pParse, pX, 0);
77323     iTab = pX->iTable;
77324     sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
77325     VdbeComment((v, "%.*s", pX->span.n, pX->span.z));
77326     if( pLevel->nIn==0 ){
77327       pLevel->nxt = sqlite3VdbeMakeLabel(v);
77328     }
77329     pLevel->nIn++;
77330     pLevel->aInLoop = sqlite3DbReallocOrFree(pParse->db, pLevel->aInLoop,
77331                                     sizeof(pLevel->aInLoop[0])*pLevel->nIn);
77332     pIn = pLevel->aInLoop;
77333     if( pIn ){
77334       pIn += pLevel->nIn - 1;
77335       pIn->iCur = iTab;
77336       if( eType==IN_INDEX_ROWID ){
77337         pIn->topAddr = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
77338       }else{
77339         pIn->topAddr = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
77340       }
77341       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
77342     }else{
77343       pLevel->nIn = 0;
77344     }
77345 #endif
77346   }
77347   disableTerm(pLevel, pTerm);
77348   return iReg;
77349 }
77350
77351 /*
77352 ** Generate code that will evaluate all == and IN constraints for an
77353 ** index.  The values for all constraints are left on the stack.
77354 **
77355 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
77356 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
77357 ** The index has as many as three equality constraints, but in this
77358 ** example, the third "c" value is an inequality.  So only two 
77359 ** constraints are coded.  This routine will generate code to evaluate
77360 ** a==5 and b IN (1,2,3).  The current values for a and b will be left
77361 ** on the stack - a is the deepest and b the shallowest.
77362 **
77363 ** In the example above nEq==2.  But this subroutine works for any value
77364 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
77365 ** The only thing it does is allocate the pLevel->iMem memory cell.
77366 **
77367 ** This routine always allocates at least one memory cell and puts
77368 ** the address of that memory cell in pLevel->iMem.  The code that
77369 ** calls this routine will use pLevel->iMem to store the termination
77370 ** key value of the loop.  If one or more IN operators appear, then
77371 ** this routine allocates an additional nEq memory cells for internal
77372 ** use.
77373 */
77374 static int codeAllEqualityTerms(
77375   Parse *pParse,        /* Parsing context */
77376   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
77377   WhereClause *pWC,     /* The WHERE clause */
77378   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
77379   int nExtraReg         /* Number of extra registers to allocate */
77380 ){
77381   int nEq = pLevel->nEq;        /* The number of == or IN constraints to code */
77382   Vdbe *v = pParse->pVdbe;      /* The virtual machine under construction */
77383   Index *pIdx = pLevel->pIdx;   /* The index being used for this loop */
77384   int iCur = pLevel->iTabCur;   /* The cursor of the table */
77385   WhereTerm *pTerm;             /* A single constraint term */
77386   int j;                        /* Loop counter */
77387   int regBase;                  /* Base register */
77388
77389   /* Figure out how many memory cells we will need then allocate them.
77390   ** We always need at least one used to store the loop terminator
77391   ** value.  If there are IN operators we'll need one for each == or
77392   ** IN constraint.
77393   */
77394   pLevel->iMem = pParse->nMem + 1;
77395   regBase = pParse->nMem + 2;
77396   pParse->nMem += pLevel->nEq + 2 + nExtraReg;
77397
77398   /* Evaluate the equality constraints
77399   */
77400   assert( pIdx->nColumn>=nEq );
77401   for(j=0; j<nEq; j++){
77402     int r1;
77403     int k = pIdx->aiColumn[j];
77404     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->flags, pIdx);
77405     if( NEVER(pTerm==0) ) break;
77406     assert( (pTerm->flags & TERM_CODED)==0 );
77407     r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
77408     if( r1!=regBase+j ){
77409       sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
77410     }
77411     testcase( pTerm->eOperator & WO_ISNULL );
77412     testcase( pTerm->eOperator & WO_IN );
77413     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
77414       sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->brk);
77415     }
77416   }
77417   return regBase;
77418 }
77419
77420 #if defined(SQLITE_TEST)
77421 /*
77422 ** The following variable holds a text description of query plan generated
77423 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
77424 ** overwrites the previous.  This information is used for testing and
77425 ** analysis only.
77426 */
77427 SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
77428 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
77429
77430 #endif /* SQLITE_TEST */
77431
77432
77433 /*
77434 ** Free a WhereInfo structure
77435 */
77436 static void whereInfoFree(WhereInfo *pWInfo){
77437   if( pWInfo ){
77438     int i;
77439     sqlite3 *db = pWInfo->pParse->db;
77440     for(i=0; i<pWInfo->nLevel; i++){
77441       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
77442       if( pInfo ){
77443         assert( pInfo->needToFreeIdxStr==0 );
77444         sqlite3DbFree(db, pInfo);
77445       }
77446     }
77447     sqlite3DbFree(db, pWInfo);
77448   }
77449 }
77450
77451
77452 /*
77453 ** Generate the beginning of the loop used for WHERE clause processing.
77454 ** The return value is a pointer to an opaque structure that contains
77455 ** information needed to terminate the loop.  Later, the calling routine
77456 ** should invoke sqlite3WhereEnd() with the return value of this function
77457 ** in order to complete the WHERE clause processing.
77458 **
77459 ** If an error occurs, this routine returns NULL.
77460 **
77461 ** The basic idea is to do a nested loop, one loop for each table in
77462 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
77463 ** same as a SELECT with only a single table in the FROM clause.)  For
77464 ** example, if the SQL is this:
77465 **
77466 **       SELECT * FROM t1, t2, t3 WHERE ...;
77467 **
77468 ** Then the code generated is conceptually like the following:
77469 **
77470 **      foreach row1 in t1 do       \    Code generated
77471 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
77472 **          foreach row3 in t3 do   /
77473 **            ...
77474 **          end                     \    Code generated
77475 **        end                        |-- by sqlite3WhereEnd()
77476 **      end                         /
77477 **
77478 ** Note that the loops might not be nested in the order in which they
77479 ** appear in the FROM clause if a different order is better able to make
77480 ** use of indices.  Note also that when the IN operator appears in
77481 ** the WHERE clause, it might result in additional nested loops for
77482 ** scanning through all values on the right-hand side of the IN.
77483 **
77484 ** There are Btree cursors associated with each table.  t1 uses cursor
77485 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
77486 ** And so forth.  This routine generates code to open those VDBE cursors
77487 ** and sqlite3WhereEnd() generates the code to close them.
77488 **
77489 ** The code that sqlite3WhereBegin() generates leaves the cursors named
77490 ** in pTabList pointing at their appropriate entries.  The [...] code
77491 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
77492 ** data from the various tables of the loop.
77493 **
77494 ** If the WHERE clause is empty, the foreach loops must each scan their
77495 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
77496 ** the tables have indices and there are terms in the WHERE clause that
77497 ** refer to those indices, a complete table scan can be avoided and the
77498 ** code will run much faster.  Most of the work of this routine is checking
77499 ** to see if there are indices that can be used to speed up the loop.
77500 **
77501 ** Terms of the WHERE clause are also used to limit which rows actually
77502 ** make it to the "..." in the middle of the loop.  After each "foreach",
77503 ** terms of the WHERE clause that use only terms in that loop and outer
77504 ** loops are evaluated and if false a jump is made around all subsequent
77505 ** inner loops (or around the "..." if the test occurs within the inner-
77506 ** most loop)
77507 **
77508 ** OUTER JOINS
77509 **
77510 ** An outer join of tables t1 and t2 is conceptally coded as follows:
77511 **
77512 **    foreach row1 in t1 do
77513 **      flag = 0
77514 **      foreach row2 in t2 do
77515 **        start:
77516 **          ...
77517 **          flag = 1
77518 **      end
77519 **      if flag==0 then
77520 **        move the row2 cursor to a null row
77521 **        goto start
77522 **      fi
77523 **    end
77524 **
77525 ** ORDER BY CLAUSE PROCESSING
77526 **
77527 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
77528 ** if there is one.  If there is no ORDER BY clause or if this routine
77529 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
77530 **
77531 ** If an index can be used so that the natural output order of the table
77532 ** scan is correct for the ORDER BY clause, then that index is used and
77533 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
77534 ** unnecessary sort of the result set if an index appropriate for the
77535 ** ORDER BY clause already exists.
77536 **
77537 ** If the where clause loops cannot be arranged to provide the correct
77538 ** output order, then the *ppOrderBy is unchanged.
77539 */
77540 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
77541   Parse *pParse,        /* The parser context */
77542   SrcList *pTabList,    /* A list of all tables to be scanned */
77543   Expr *pWhere,         /* The WHERE clause */
77544   ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
77545   u8 wflags             /* One of the WHERE_* flags defined in sqliteInt.h */
77546 ){
77547   int i;                     /* Loop counter */
77548   WhereInfo *pWInfo;         /* Will become the return value of this function */
77549   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
77550   int brk, cont = 0;         /* Addresses used during code generation */
77551   Bitmask notReady;          /* Cursors that are not yet positioned */
77552   WhereTerm *pTerm;          /* A single term in the WHERE clause */
77553   ExprMaskSet maskSet;       /* The expression mask set */
77554   WhereClause wc;            /* The WHERE clause is divided into these terms */
77555   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
77556   WhereLevel *pLevel;             /* A single level in the pWInfo list */
77557   int iFrom;                      /* First unused FROM clause element */
77558   int andFlags;              /* AND-ed combination of all wc.a[].flags */
77559   sqlite3 *db;               /* Database connection */
77560   ExprList *pOrderBy = 0;
77561
77562   /* The number of tables in the FROM clause is limited by the number of
77563   ** bits in a Bitmask 
77564   */
77565   if( pTabList->nSrc>BMS ){
77566     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
77567     return 0;
77568   }
77569
77570   if( ppOrderBy ){
77571     pOrderBy = *ppOrderBy;
77572   }
77573
77574   /* Split the WHERE clause into separate subexpressions where each
77575   ** subexpression is separated by an AND operator.
77576   */
77577   initMaskSet(&maskSet);
77578   whereClauseInit(&wc, pParse, &maskSet);
77579   sqlite3ExprCodeConstants(pParse, pWhere);
77580   whereSplit(&wc, pWhere, TK_AND);
77581     
77582   /* Allocate and initialize the WhereInfo structure that will become the
77583   ** return value.
77584   */
77585   db = pParse->db;
77586   pWInfo = sqlite3DbMallocZero(db,  
77587                       sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
77588   if( db->mallocFailed ){
77589     goto whereBeginNoMem;
77590   }
77591   pWInfo->nLevel = pTabList->nSrc;
77592   pWInfo->pParse = pParse;
77593   pWInfo->pTabList = pTabList;
77594   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
77595
77596   /* Special case: a WHERE clause that is constant.  Evaluate the
77597   ** expression and either jump over all of the code or fall thru.
77598   */
77599   if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
77600     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
77601     pWhere = 0;
77602   }
77603
77604   /* Assign a bit from the bitmask to every term in the FROM clause.
77605   **
77606   ** When assigning bitmask values to FROM clause cursors, it must be
77607   ** the case that if X is the bitmask for the N-th FROM clause term then
77608   ** the bitmask for all FROM clause terms to the left of the N-th term
77609   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
77610   ** its Expr.iRightJoinTable value to find the bitmask of the right table
77611   ** of the join.  Subtracting one from the right table bitmask gives a
77612   ** bitmask for all tables to the left of the join.  Knowing the bitmask
77613   ** for all tables to the left of a left join is important.  Ticket #3015.
77614   */
77615   for(i=0; i<pTabList->nSrc; i++){
77616     createMask(&maskSet, pTabList->a[i].iCursor);
77617   }
77618 #ifndef NDEBUG
77619   {
77620     Bitmask toTheLeft = 0;
77621     for(i=0; i<pTabList->nSrc; i++){
77622       Bitmask m = getMask(&maskSet, pTabList->a[i].iCursor);
77623       assert( (m-1)==toTheLeft );
77624       toTheLeft |= m;
77625     }
77626   }
77627 #endif
77628
77629   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
77630   ** add new virtual terms onto the end of the WHERE clause.  We do not
77631   ** want to analyze these virtual terms, so start analyzing at the end
77632   ** and work forward so that the added virtual terms are never processed.
77633   */
77634   exprAnalyzeAll(pTabList, &wc);
77635   if( db->mallocFailed ){
77636     goto whereBeginNoMem;
77637   }
77638
77639   /* Chose the best index to use for each table in the FROM clause.
77640   **
77641   ** This loop fills in the following fields:
77642   **
77643   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
77644   **   pWInfo->a[].flags     WHERE_xxx flags associated with pIdx
77645   **   pWInfo->a[].nEq       The number of == and IN constraints
77646   **   pWInfo->a[].iFrom     When term of the FROM clause is being coded
77647   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
77648   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
77649   **
77650   ** This loop also figures out the nesting order of tables in the FROM
77651   ** clause.
77652   */
77653   notReady = ~(Bitmask)0;
77654   pTabItem = pTabList->a;
77655   pLevel = pWInfo->a;
77656   andFlags = ~0;
77657   WHERETRACE(("*** Optimizer Start ***\n"));
77658   for(i=iFrom=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
77659     Index *pIdx;                /* Index for FROM table at pTabItem */
77660     int flags;                  /* Flags asssociated with pIdx */
77661     int nEq;                    /* Number of == or IN constraints */
77662     double cost;                /* The cost for pIdx */
77663     int j;                      /* For looping over FROM tables */
77664     Index *pBest = 0;           /* The best index seen so far */
77665     int bestFlags = 0;          /* Flags associated with pBest */
77666     int bestNEq = 0;            /* nEq associated with pBest */
77667     double lowestCost;          /* Cost of the pBest */
77668     int bestJ = 0;              /* The value of j */
77669     Bitmask m;                  /* Bitmask value for j or bestJ */
77670     int once = 0;               /* True when first table is seen */
77671     sqlite3_index_info *pIndex; /* Current virtual index */
77672
77673     lowestCost = SQLITE_BIG_DBL;
77674     for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
77675       int doNotReorder;  /* True if this table should not be reordered */
77676
77677       doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
77678       if( once && doNotReorder ) break;
77679       m = getMask(&maskSet, pTabItem->iCursor);
77680       if( (m & notReady)==0 ){
77681         if( j==iFrom ) iFrom++;
77682         continue;
77683       }
77684       assert( pTabItem->pTab );
77685 #ifndef SQLITE_OMIT_VIRTUALTABLE
77686       if( IsVirtual(pTabItem->pTab) ){
77687         sqlite3_index_info **ppIdxInfo = &pWInfo->a[j].pIdxInfo;
77688         cost = bestVirtualIndex(pParse, &wc, pTabItem, notReady,
77689                                 ppOrderBy ? *ppOrderBy : 0, i==0,
77690                                 ppIdxInfo);
77691         flags = WHERE_VIRTUALTABLE;
77692         pIndex = *ppIdxInfo;
77693         if( pIndex && pIndex->orderByConsumed ){
77694           flags = WHERE_VIRTUALTABLE | WHERE_ORDERBY;
77695         }
77696         pIdx = 0;
77697         nEq = 0;
77698         if( (SQLITE_BIG_DBL/2.0)<cost ){
77699           /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
77700           ** inital value of lowestCost in this loop. If it is, then
77701           ** the (cost<lowestCost) test below will never be true and
77702           ** pLevel->pBestIdx never set.
77703           */ 
77704           cost = (SQLITE_BIG_DBL/2.0);
77705         }
77706       }else 
77707 #endif
77708       {
77709         cost = bestIndex(pParse, &wc, pTabItem, notReady,
77710                          (i==0 && ppOrderBy) ? *ppOrderBy : 0,
77711                          &pIdx, &flags, &nEq);
77712         pIndex = 0;
77713       }
77714       if( cost<lowestCost ){
77715         once = 1;
77716         lowestCost = cost;
77717         pBest = pIdx;
77718         bestFlags = flags;
77719         bestNEq = nEq;
77720         bestJ = j;
77721         pLevel->pBestIdx = pIndex;
77722       }
77723       if( doNotReorder ) break;
77724     }
77725     WHERETRACE(("*** Optimizer selects table %d for loop %d\n", bestJ,
77726            pLevel-pWInfo->a));
77727     if( (bestFlags & WHERE_ORDERBY)!=0 ){
77728       *ppOrderBy = 0;
77729     }
77730     andFlags &= bestFlags;
77731     pLevel->flags = bestFlags;
77732     pLevel->pIdx = pBest;
77733     pLevel->nEq = bestNEq;
77734     pLevel->aInLoop = 0;
77735     pLevel->nIn = 0;
77736     if( pBest ){
77737       pLevel->iIdxCur = pParse->nTab++;
77738     }else{
77739       pLevel->iIdxCur = -1;
77740     }
77741     notReady &= ~getMask(&maskSet, pTabList->a[bestJ].iCursor);
77742     pLevel->iFrom = bestJ;
77743   }
77744   WHERETRACE(("*** Optimizer Finished ***\n"));
77745
77746   /* If the total query only selects a single row, then the ORDER BY
77747   ** clause is irrelevant.
77748   */
77749   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
77750     *ppOrderBy = 0;
77751   }
77752
77753   /* If the caller is an UPDATE or DELETE statement that is requesting
77754   ** to use a one-pass algorithm, determine if this is appropriate.
77755   ** The one-pass algorithm only works if the WHERE clause constraints
77756   ** the statement to update a single row.
77757   */
77758   assert( (wflags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
77759   if( (wflags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
77760     pWInfo->okOnePass = 1;
77761     pWInfo->a[0].flags &= ~WHERE_IDX_ONLY;
77762   }
77763
77764   /* Open all tables in the pTabList and any indices selected for
77765   ** searching those tables.
77766   */
77767   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
77768   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
77769     Table *pTab;     /* Table to open */
77770     Index *pIx;      /* Index used to access pTab (if any) */
77771     int iDb;         /* Index of database containing table/index */
77772     int iIdxCur = pLevel->iIdxCur;
77773
77774 #ifndef SQLITE_OMIT_EXPLAIN
77775     if( pParse->explain==2 ){
77776       char *zMsg;
77777       struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
77778       zMsg = sqlite3MPrintf(db, "TABLE %s", pItem->zName);
77779       if( pItem->zAlias ){
77780         zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
77781       }
77782       if( (pIx = pLevel->pIdx)!=0 ){
77783         zMsg = sqlite3MAppendf(db, zMsg, "%s WITH INDEX %s", zMsg, pIx->zName);
77784       }else if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
77785         zMsg = sqlite3MAppendf(db, zMsg, "%s USING PRIMARY KEY", zMsg);
77786       }
77787 #ifndef SQLITE_OMIT_VIRTUALTABLE
77788       else if( pLevel->pBestIdx ){
77789         sqlite3_index_info *pBestIdx = pLevel->pBestIdx;
77790         zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
77791                     pBestIdx->idxNum, pBestIdx->idxStr);
77792       }
77793 #endif
77794       if( pLevel->flags & WHERE_ORDERBY ){
77795         zMsg = sqlite3MAppendf(db, zMsg, "%s ORDER BY", zMsg);
77796       }
77797       sqlite3VdbeAddOp4(v, OP_Explain, i, pLevel->iFrom, 0, zMsg, P4_DYNAMIC);
77798     }
77799 #endif /* SQLITE_OMIT_EXPLAIN */
77800     pTabItem = &pTabList->a[pLevel->iFrom];
77801     pTab = pTabItem->pTab;
77802     iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
77803     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
77804 #ifndef SQLITE_OMIT_VIRTUALTABLE
77805     if( pLevel->pBestIdx ){
77806       int iCur = pTabItem->iCursor;
77807       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0,
77808                         (const char*)pTab->pVtab, P4_VTAB);
77809     }else
77810 #endif
77811     if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
77812       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
77813       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
77814       if( !pWInfo->okOnePass && pTab->nCol<(sizeof(Bitmask)*8) ){
77815         Bitmask b = pTabItem->colUsed;
77816         int n = 0;
77817         for(; b; b=b>>1, n++){}
77818         sqlite3VdbeChangeP2(v, sqlite3VdbeCurrentAddr(v)-2, n);
77819         assert( n<=pTab->nCol );
77820       }
77821     }else{
77822       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
77823     }
77824     pLevel->iTabCur = pTabItem->iCursor;
77825     if( (pIx = pLevel->pIdx)!=0 ){
77826       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
77827       assert( pIx->pSchema==pTab->pSchema );
77828       sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pIx->nColumn+1);
77829       sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
77830                         (char*)pKey, P4_KEYINFO_HANDOFF);
77831       VdbeComment((v, "%s", pIx->zName));
77832     }
77833     sqlite3CodeVerifySchema(pParse, iDb);
77834   }
77835   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
77836
77837   /* Generate the code to do the search.  Each iteration of the for
77838   ** loop below generates code for a single nested loop of the VM
77839   ** program.
77840   */
77841   notReady = ~(Bitmask)0;
77842   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
77843     int j;
77844     int iCur = pTabItem->iCursor;  /* The VDBE cursor for the table */
77845     Index *pIdx;       /* The index we will be using */
77846     int nxt;           /* Where to jump to continue with the next IN case */
77847     int iIdxCur;       /* The VDBE cursor for the index */
77848     int omitTable;     /* True if we use the index only */
77849     int bRev;          /* True if we need to scan in reverse order */
77850
77851     pTabItem = &pTabList->a[pLevel->iFrom];
77852     iCur = pTabItem->iCursor;
77853     pIdx = pLevel->pIdx;
77854     iIdxCur = pLevel->iIdxCur;
77855     bRev = (pLevel->flags & WHERE_REVERSE)!=0;
77856     omitTable = (pLevel->flags & WHERE_IDX_ONLY)!=0;
77857
77858     /* Create labels for the "break" and "continue" instructions
77859     ** for the current loop.  Jump to brk to break out of a loop.
77860     ** Jump to cont to go immediately to the next iteration of the
77861     ** loop.
77862     **
77863     ** When there is an IN operator, we also have a "nxt" label that
77864     ** means to continue with the next IN value combination.  When
77865     ** there are no IN operators in the constraints, the "nxt" label
77866     ** is the same as "brk".
77867     */
77868     brk = pLevel->brk = pLevel->nxt = sqlite3VdbeMakeLabel(v);
77869     cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
77870
77871     /* If this is the right table of a LEFT OUTER JOIN, allocate and
77872     ** initialize a memory cell that records if this table matches any
77873     ** row of the left table of the join.
77874     */
77875     if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
77876       pLevel->iLeftJoin = ++pParse->nMem;
77877       sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
77878       VdbeComment((v, "init LEFT JOIN no-match flag"));
77879     }
77880
77881 #ifndef SQLITE_OMIT_VIRTUALTABLE
77882     if( pLevel->pBestIdx ){
77883       /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
77884       **          to access the data.
77885       */
77886       int j;
77887       int iReg;   /* P3 Value for OP_VFilter */
77888       sqlite3_index_info *pBestIdx = pLevel->pBestIdx;
77889       int nConstraint = pBestIdx->nConstraint;
77890       struct sqlite3_index_constraint_usage *aUsage =
77891                                                   pBestIdx->aConstraintUsage;
77892       const struct sqlite3_index_constraint *aConstraint =
77893                                                   pBestIdx->aConstraint;
77894
77895       iReg = sqlite3GetTempRange(pParse, nConstraint+2);
77896       pParse->disableColCache++;
77897       for(j=1; j<=nConstraint; j++){
77898         int k;
77899         for(k=0; k<nConstraint; k++){
77900           if( aUsage[k].argvIndex==j ){
77901             int iTerm = aConstraint[k].iTermOffset;
77902             assert( pParse->disableColCache );
77903             sqlite3ExprCode(pParse, wc.a[iTerm].pExpr->pRight, iReg+j+1);
77904             break;
77905           }
77906         }
77907         if( k==nConstraint ) break;
77908       }
77909       assert( pParse->disableColCache );
77910       pParse->disableColCache--;
77911       sqlite3VdbeAddOp2(v, OP_Integer, pBestIdx->idxNum, iReg);
77912       sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
77913       sqlite3VdbeAddOp4(v, OP_VFilter, iCur, brk, iReg, pBestIdx->idxStr,
77914                         pBestIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
77915       sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
77916       pBestIdx->needToFreeIdxStr = 0;
77917       for(j=0; j<nConstraint; j++){
77918         if( aUsage[j].omit ){
77919           int iTerm = aConstraint[j].iTermOffset;
77920           disableTerm(pLevel, &wc.a[iTerm]);
77921         }
77922       }
77923       pLevel->op = OP_VNext;
77924       pLevel->p1 = iCur;
77925       pLevel->p2 = sqlite3VdbeCurrentAddr(v);
77926     }else
77927 #endif /* SQLITE_OMIT_VIRTUALTABLE */
77928
77929     if( pLevel->flags & WHERE_ROWID_EQ ){
77930       /* Case 1:  We can directly reference a single row using an
77931       **          equality comparison against the ROWID field.  Or
77932       **          we reference multiple rows using a "rowid IN (...)"
77933       **          construct.
77934       */
77935       int r1;
77936       pTerm = findTerm(&wc, iCur, -1, notReady, WO_EQ|WO_IN, 0);
77937       assert( pTerm!=0 );
77938       assert( pTerm->pExpr!=0 );
77939       assert( pTerm->leftCursor==iCur );
77940       assert( omitTable==0 );
77941       r1 = codeEqualityTerm(pParse, pTerm, pLevel, 0);
77942       nxt = pLevel->nxt;
77943       sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, nxt);
77944       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, nxt, r1);
77945       sqlite3ReleaseTempReg(pParse, r1);
77946       VdbeComment((v, "pk"));
77947       pLevel->op = OP_Noop;
77948     }else if( pLevel->flags & WHERE_ROWID_RANGE ){
77949       /* Case 2:  We have an inequality comparison against the ROWID field.
77950       */
77951       int testOp = OP_Noop;
77952       int start;
77953       WhereTerm *pStart, *pEnd;
77954
77955       assert( omitTable==0 );
77956       pStart = findTerm(&wc, iCur, -1, notReady, WO_GT|WO_GE, 0);
77957       pEnd = findTerm(&wc, iCur, -1, notReady, WO_LT|WO_LE, 0);
77958       if( bRev ){
77959         pTerm = pStart;
77960         pStart = pEnd;
77961         pEnd = pTerm;
77962       }
77963       if( pStart ){
77964         Expr *pX;
77965         int r1, regFree1;
77966         pX = pStart->pExpr;
77967         assert( pX!=0 );
77968         assert( pStart->leftCursor==iCur );
77969         r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &regFree1);
77970         sqlite3VdbeAddOp3(v, OP_ForceInt, r1, brk, 
77971                              pX->op==TK_LE || pX->op==TK_GT);
77972         sqlite3VdbeAddOp3(v, bRev ? OP_MoveLt : OP_MoveGe, iCur, brk, r1);
77973         VdbeComment((v, "pk"));
77974         sqlite3ReleaseTempReg(pParse, regFree1);
77975         disableTerm(pLevel, pStart);
77976       }else{
77977         sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, brk);
77978       }
77979       if( pEnd ){
77980         Expr *pX;
77981         pX = pEnd->pExpr;
77982         assert( pX!=0 );
77983         assert( pEnd->leftCursor==iCur );
77984         pLevel->iMem = ++pParse->nMem;
77985         sqlite3ExprCode(pParse, pX->pRight, pLevel->iMem);
77986         if( pX->op==TK_LT || pX->op==TK_GT ){
77987           testOp = bRev ? OP_Le : OP_Ge;
77988         }else{
77989           testOp = bRev ? OP_Lt : OP_Gt;
77990         }
77991         disableTerm(pLevel, pEnd);
77992       }
77993       start = sqlite3VdbeCurrentAddr(v);
77994       pLevel->op = bRev ? OP_Prev : OP_Next;
77995       pLevel->p1 = iCur;
77996       pLevel->p2 = start;
77997       if( testOp!=OP_Noop ){
77998         int r1 = sqlite3GetTempReg(pParse);
77999         sqlite3VdbeAddOp2(v, OP_Rowid, iCur, r1);
78000         /* sqlite3VdbeAddOp2(v, OP_SCopy, pLevel->iMem, 0); */
78001         sqlite3VdbeAddOp3(v, testOp, pLevel->iMem, brk, r1);
78002         sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
78003         sqlite3ReleaseTempReg(pParse, r1);
78004       }
78005     }else if( pLevel->flags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
78006       /* Case 3: A scan using an index.
78007       **
78008       **         The WHERE clause may contain zero or more equality 
78009       **         terms ("==" or "IN" operators) that refer to the N
78010       **         left-most columns of the index. It may also contain
78011       **         inequality constraints (>, <, >= or <=) on the indexed
78012       **         column that immediately follows the N equalities. Only 
78013       **         the right-most column can be an inequality - the rest must
78014       **         use the "==" and "IN" operators. For example, if the 
78015       **         index is on (x,y,z), then the following clauses are all 
78016       **         optimized:
78017       **
78018       **            x=5
78019       **            x=5 AND y=10
78020       **            x=5 AND y<10
78021       **            x=5 AND y>5 AND y<10
78022       **            x=5 AND y=5 AND z<=10
78023       **
78024       **         The z<10 term of the following cannot be used, only
78025       **         the x=5 term:
78026       **
78027       **            x=5 AND z<10
78028       **
78029       **         N may be zero if there are inequality constraints.
78030       **         If there are no inequality constraints, then N is at
78031       **         least one.
78032       **
78033       **         This case is also used when there are no WHERE clause
78034       **         constraints but an index is selected anyway, in order
78035       **         to force the output order to conform to an ORDER BY.
78036       */  
78037       int aStartOp[] = {
78038         0,
78039         0,
78040         OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
78041         OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
78042         OP_MoveGt,           /* 4: (start_constraints  && !startEq && !bRev) */
78043         OP_MoveLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
78044         OP_MoveGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
78045         OP_MoveLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
78046       };
78047       int aEndOp[] = {
78048         OP_Noop,             /* 0: (!end_constraints) */
78049         OP_IdxGE,            /* 1: (end_constraints && !bRev) */
78050         OP_IdxLT             /* 2: (end_constraints && bRev) */
78051       };
78052       int nEq = pLevel->nEq;
78053       int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
78054       int regBase;                 /* Base register holding constraint values */
78055       int r1;                      /* Temp register */
78056       WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
78057       WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
78058       int startEq;                 /* True if range start uses ==, >= or <= */
78059       int endEq;                   /* True if range end uses ==, >= or <= */
78060       int start_constraints;       /* Start of range is constrained */
78061       int k = pIdx->aiColumn[nEq]; /* Column for inequality constraints */
78062       int nConstraint;             /* Number of constraint terms */
78063       int op;
78064
78065       /* Generate code to evaluate all constraint terms using == or IN
78066       ** and store the values of those terms in an array of registers
78067       ** starting at regBase.
78068       */
78069       regBase = codeAllEqualityTerms(pParse, pLevel, &wc, notReady, 2);
78070       nxt = pLevel->nxt;
78071
78072       /* If this loop satisfies a sort order (pOrderBy) request that 
78073       ** was passed to this function to implement a "SELECT min(x) ..." 
78074       ** query, then the caller will only allow the loop to run for
78075       ** a single iteration. This means that the first row returned
78076       ** should not have a NULL value stored in 'x'. If column 'x' is
78077       ** the first one after the nEq equality constraints in the index,
78078       ** this requires some special handling.
78079       */
78080       if( (wflags&WHERE_ORDERBY_MIN)!=0
78081        && (pLevel->flags&WHERE_ORDERBY)
78082        && (pIdx->nColumn>nEq)
78083       ){
78084         assert( pOrderBy->nExpr==1 );
78085         assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] );
78086         isMinQuery = 1;
78087       }
78088
78089       /* Find any inequality constraint terms for the start and end 
78090       ** of the range. 
78091       */
78092       if( pLevel->flags & WHERE_TOP_LIMIT ){
78093         pRangeEnd = findTerm(&wc, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
78094       }
78095       if( pLevel->flags & WHERE_BTM_LIMIT ){
78096         pRangeStart = findTerm(&wc, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
78097       }
78098
78099       /* If we are doing a reverse order scan on an ascending index, or
78100       ** a forward order scan on a descending index, interchange the 
78101       ** start and end terms (pRangeStart and pRangeEnd).
78102       */
78103       if( bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
78104         SWAP(WhereTerm *, pRangeEnd, pRangeStart);
78105       }
78106
78107       testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
78108       testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
78109       testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
78110       testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
78111       startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
78112       endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
78113       start_constraints = pRangeStart || nEq>0;
78114
78115       /* Seek the index cursor to the start of the range. */
78116       nConstraint = nEq;
78117       if( pRangeStart ){
78118         int dcc = pParse->disableColCache;
78119         if( pRangeEnd ){
78120           pParse->disableColCache++;
78121         }
78122         sqlite3ExprCode(pParse, pRangeStart->pExpr->pRight, regBase+nEq);
78123         pParse->disableColCache = dcc;
78124         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, nxt);
78125         nConstraint++;
78126       }else if( isMinQuery ){
78127         sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
78128         nConstraint++;
78129         startEq = 0;
78130         start_constraints = 1;
78131       }
78132       codeApplyAffinity(pParse, regBase, nConstraint, pIdx);
78133       op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
78134       assert( op!=0 );
78135       testcase( op==OP_Rewind );
78136       testcase( op==OP_Last );
78137       testcase( op==OP_MoveGt );
78138       testcase( op==OP_MoveGe );
78139       testcase( op==OP_MoveLe );
78140       testcase( op==OP_MoveLt );
78141       sqlite3VdbeAddOp4(v, op, iIdxCur, nxt, regBase, 
78142                         SQLITE_INT_TO_PTR(nConstraint), P4_INT32);
78143
78144       /* Load the value for the inequality constraint at the end of the
78145       ** range (if any).
78146       */
78147       nConstraint = nEq;
78148       if( pRangeEnd ){
78149         sqlite3ExprCode(pParse, pRangeEnd->pExpr->pRight, regBase+nEq);
78150         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, nxt);
78151         codeApplyAffinity(pParse, regBase, nEq+1, pIdx);
78152         nConstraint++;
78153       }
78154
78155       /* Top of the loop body */
78156       pLevel->p2 = sqlite3VdbeCurrentAddr(v);
78157
78158       /* Check if the index cursor is past the end of the range. */
78159       op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
78160       testcase( op==OP_Noop );
78161       testcase( op==OP_IdxGE );
78162       testcase( op==OP_IdxLT );
78163       sqlite3VdbeAddOp4(v, op, iIdxCur, nxt, regBase,
78164                         SQLITE_INT_TO_PTR(nConstraint), P4_INT32);
78165       sqlite3VdbeChangeP5(v, endEq!=bRev);
78166
78167       /* If there are inequality constraints, check that the value
78168       ** of the table column that the inequality contrains is not NULL.
78169       ** If it is, jump to the next iteration of the loop.
78170       */
78171       r1 = sqlite3GetTempReg(pParse);
78172       testcase( pLevel->flags & WHERE_BTM_LIMIT );
78173       testcase( pLevel->flags & WHERE_TOP_LIMIT );
78174       if( pLevel->flags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT) ){
78175         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
78176         sqlite3VdbeAddOp2(v, OP_IsNull, r1, cont);
78177       }
78178
78179       /* Seek the table cursor, if required */
78180       if( !omitTable ){
78181         sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, r1);
78182         sqlite3VdbeAddOp3(v, OP_MoveGe, iCur, 0, r1);  /* Deferred seek */
78183       }
78184       sqlite3ReleaseTempReg(pParse, r1);
78185
78186       /* Record the instruction used to terminate the loop. Disable 
78187       ** WHERE clause terms made redundant by the index range scan.
78188       */
78189       pLevel->op = bRev ? OP_Prev : OP_Next;
78190       pLevel->p1 = iIdxCur;
78191       disableTerm(pLevel, pRangeStart);
78192       disableTerm(pLevel, pRangeEnd);
78193     }else{
78194       /* Case 4:  There is no usable index.  We must do a complete
78195       **          scan of the entire table.
78196       */
78197       assert( omitTable==0 );
78198       assert( bRev==0 );
78199       pLevel->op = OP_Next;
78200       pLevel->p1 = iCur;
78201       pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, OP_Rewind, iCur, brk);
78202     }
78203     notReady &= ~getMask(&maskSet, iCur);
78204
78205     /* Insert code to test every subexpression that can be completely
78206     ** computed using the current set of tables.
78207     */
78208     for(pTerm=wc.a, j=wc.nTerm; j>0; j--, pTerm++){
78209       Expr *pE;
78210       testcase( pTerm->flags & TERM_VIRTUAL );
78211       testcase( pTerm->flags & TERM_CODED );
78212       if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
78213       if( (pTerm->prereqAll & notReady)!=0 ) continue;
78214       pE = pTerm->pExpr;
78215       assert( pE!=0 );
78216       if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
78217         continue;
78218       }
78219       sqlite3ExprIfFalse(pParse, pE, cont, SQLITE_JUMPIFNULL);
78220       pTerm->flags |= TERM_CODED;
78221     }
78222
78223     /* For a LEFT OUTER JOIN, generate code that will record the fact that
78224     ** at least one row of the right table has matched the left table.  
78225     */
78226     if( pLevel->iLeftJoin ){
78227       pLevel->top = sqlite3VdbeCurrentAddr(v);
78228       sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
78229       VdbeComment((v, "record LEFT JOIN hit"));
78230       sqlite3ExprClearColumnCache(pParse, pLevel->iTabCur);
78231       sqlite3ExprClearColumnCache(pParse, pLevel->iIdxCur);
78232       for(pTerm=wc.a, j=0; j<wc.nTerm; j++, pTerm++){
78233         testcase( pTerm->flags & TERM_VIRTUAL );
78234         testcase( pTerm->flags & TERM_CODED );
78235         if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
78236         if( (pTerm->prereqAll & notReady)!=0 ) continue;
78237         assert( pTerm->pExpr );
78238         sqlite3ExprIfFalse(pParse, pTerm->pExpr, cont, SQLITE_JUMPIFNULL);
78239         pTerm->flags |= TERM_CODED;
78240       }
78241     }
78242   }
78243
78244 #ifdef SQLITE_TEST  /* For testing and debugging use only */
78245   /* Record in the query plan information about the current table
78246   ** and the index used to access it (if any).  If the table itself
78247   ** is not used, its name is just '{}'.  If no index is used
78248   ** the index is listed as "{}".  If the primary key is used the
78249   ** index name is '*'.
78250   */
78251   for(i=0; i<pTabList->nSrc; i++){
78252     char *z;
78253     int n;
78254     pLevel = &pWInfo->a[i];
78255     pTabItem = &pTabList->a[pLevel->iFrom];
78256     z = pTabItem->zAlias;
78257     if( z==0 ) z = pTabItem->pTab->zName;
78258     n = strlen(z);
78259     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
78260       if( pLevel->flags & WHERE_IDX_ONLY ){
78261         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
78262         nQPlan += 2;
78263       }else{
78264         memcpy(&sqlite3_query_plan[nQPlan], z, n);
78265         nQPlan += n;
78266       }
78267       sqlite3_query_plan[nQPlan++] = ' ';
78268     }
78269     testcase( pLevel->flags & WHERE_ROWID_EQ );
78270     testcase( pLevel->flags & WHERE_ROWID_RANGE );
78271     if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
78272       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
78273       nQPlan += 2;
78274     }else if( pLevel->pIdx==0 ){
78275       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
78276       nQPlan += 3;
78277     }else{
78278       n = strlen(pLevel->pIdx->zName);
78279       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
78280         memcpy(&sqlite3_query_plan[nQPlan], pLevel->pIdx->zName, n);
78281         nQPlan += n;
78282         sqlite3_query_plan[nQPlan++] = ' ';
78283       }
78284     }
78285   }
78286   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
78287     sqlite3_query_plan[--nQPlan] = 0;
78288   }
78289   sqlite3_query_plan[nQPlan] = 0;
78290   nQPlan = 0;
78291 #endif /* SQLITE_TEST // Testing and debugging use only */
78292
78293   /* Record the continuation address in the WhereInfo structure.  Then
78294   ** clean up and return.
78295   */
78296   pWInfo->iContinue = cont;
78297   whereClauseClear(&wc);
78298   return pWInfo;
78299
78300   /* Jump here if malloc fails */
78301 whereBeginNoMem:
78302   whereClauseClear(&wc);
78303   whereInfoFree(pWInfo);
78304   return 0;
78305 }
78306
78307 /*
78308 ** Generate the end of the WHERE loop.  See comments on 
78309 ** sqlite3WhereBegin() for additional information.
78310 */
78311 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
78312   Parse *pParse = pWInfo->pParse;
78313   Vdbe *v = pParse->pVdbe;
78314   int i;
78315   WhereLevel *pLevel;
78316   SrcList *pTabList = pWInfo->pTabList;
78317   sqlite3 *db = pParse->db;
78318
78319   /* Generate loop termination code.
78320   */
78321   sqlite3ExprClearColumnCache(pParse, -1);
78322   for(i=pTabList->nSrc-1; i>=0; i--){
78323     pLevel = &pWInfo->a[i];
78324     sqlite3VdbeResolveLabel(v, pLevel->cont);
78325     if( pLevel->op!=OP_Noop ){
78326       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
78327     }
78328     if( pLevel->nIn ){
78329       struct InLoop *pIn;
78330       int j;
78331       sqlite3VdbeResolveLabel(v, pLevel->nxt);
78332       for(j=pLevel->nIn, pIn=&pLevel->aInLoop[j-1]; j>0; j--, pIn--){
78333         sqlite3VdbeJumpHere(v, pIn->topAddr+1);
78334         sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->topAddr);
78335         sqlite3VdbeJumpHere(v, pIn->topAddr-1);
78336       }
78337       sqlite3DbFree(db, pLevel->aInLoop);
78338     }
78339     sqlite3VdbeResolveLabel(v, pLevel->brk);
78340     if( pLevel->iLeftJoin ){
78341       int addr;
78342       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
78343       sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
78344       if( pLevel->iIdxCur>=0 ){
78345         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
78346       }
78347       sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->top);
78348       sqlite3VdbeJumpHere(v, addr);
78349     }
78350   }
78351
78352   /* The "break" point is here, just past the end of the outer loop.
78353   ** Set it.
78354   */
78355   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
78356
78357   /* Close all of the cursors that were opened by sqlite3WhereBegin.
78358   */
78359   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
78360     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
78361     Table *pTab = pTabItem->pTab;
78362     assert( pTab!=0 );
78363     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
78364     if( !pWInfo->okOnePass && (pLevel->flags & WHERE_IDX_ONLY)==0 ){
78365       sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
78366     }
78367     if( pLevel->pIdx!=0 ){
78368       sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
78369     }
78370
78371     /* If this scan uses an index, make code substitutions to read data
78372     ** from the index in preference to the table. Sometimes, this means
78373     ** the table need never be read from. This is a performance boost,
78374     ** as the vdbe level waits until the table is read before actually
78375     ** seeking the table cursor to the record corresponding to the current
78376     ** position in the index.
78377     ** 
78378     ** Calls to the code generator in between sqlite3WhereBegin and
78379     ** sqlite3WhereEnd will have created code that references the table
78380     ** directly.  This loop scans all that code looking for opcodes
78381     ** that reference the table and converts them into opcodes that
78382     ** reference the index.
78383     */
78384     if( pLevel->pIdx ){
78385       int k, j, last;
78386       VdbeOp *pOp;
78387       Index *pIdx = pLevel->pIdx;
78388       int useIndexOnly = pLevel->flags & WHERE_IDX_ONLY;
78389
78390       assert( pIdx!=0 );
78391       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
78392       last = sqlite3VdbeCurrentAddr(v);
78393       for(k=pWInfo->iTop; k<last; k++, pOp++){
78394         if( pOp->p1!=pLevel->iTabCur ) continue;
78395         if( pOp->opcode==OP_Column ){
78396           for(j=0; j<pIdx->nColumn; j++){
78397             if( pOp->p2==pIdx->aiColumn[j] ){
78398               pOp->p2 = j;
78399               pOp->p1 = pLevel->iIdxCur;
78400               break;
78401             }
78402           }
78403           assert(!useIndexOnly || j<pIdx->nColumn);
78404         }else if( pOp->opcode==OP_Rowid ){
78405           pOp->p1 = pLevel->iIdxCur;
78406           pOp->opcode = OP_IdxRowid;
78407         }else if( pOp->opcode==OP_NullRow && useIndexOnly ){
78408           pOp->opcode = OP_Noop;
78409         }
78410       }
78411     }
78412   }
78413
78414   /* Final cleanup
78415   */
78416   whereInfoFree(pWInfo);
78417   return;
78418 }
78419
78420 /************** End of where.c ***********************************************/
78421 /************** Begin file parse.c *******************************************/
78422 /* Driver template for the LEMON parser generator.
78423 ** The author disclaims copyright to this source code.
78424 */
78425 /* First off, code is included that follows the "include" declaration
78426 ** in the input grammar file. */
78427
78428
78429 /*
78430 ** An instance of this structure holds information about the
78431 ** LIMIT clause of a SELECT statement.
78432 */
78433 struct LimitVal {
78434   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
78435   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
78436 };
78437
78438 /*
78439 ** An instance of this structure is used to store the LIKE,
78440 ** GLOB, NOT LIKE, and NOT GLOB operators.
78441 */
78442 struct LikeOp {
78443   Token eOperator;  /* "like" or "glob" or "regexp" */
78444   int not;         /* True if the NOT keyword is present */
78445 };
78446
78447 /*
78448 ** An instance of the following structure describes the event of a
78449 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
78450 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
78451 **
78452 **      UPDATE ON (a,b,c)
78453 **
78454 ** Then the "b" IdList records the list "a,b,c".
78455 */
78456 struct TrigEvent { int a; IdList * b; };
78457
78458 /*
78459 ** An instance of this structure holds the ATTACH key and the key type.
78460 */
78461 struct AttachKey { int type;  Token key; };
78462
78463 /* Next is all token values, in a form suitable for use by makeheaders.
78464 ** This section will be null unless lemon is run with the -m switch.
78465 */
78466 /* 
78467 ** These constants (all generated automatically by the parser generator)
78468 ** specify the various kinds of tokens (terminals) that the parser
78469 ** understands. 
78470 **
78471 ** Each symbol here is a terminal symbol in the grammar.
78472 */
78473 /* Make sure the INTERFACE macro is defined.
78474 */
78475 #ifndef INTERFACE
78476 # define INTERFACE 1
78477 #endif
78478 /* The next thing included is series of defines which control
78479 ** various aspects of the generated parser.
78480 **    YYCODETYPE         is the data type used for storing terminal
78481 **                       and nonterminal numbers.  "unsigned char" is
78482 **                       used if there are fewer than 250 terminals
78483 **                       and nonterminals.  "int" is used otherwise.
78484 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
78485 **                       to no legal terminal or nonterminal number.  This
78486 **                       number is used to fill in empty slots of the hash 
78487 **                       table.
78488 **    YYFALLBACK         If defined, this indicates that one or more tokens
78489 **                       have fall-back values which should be used if the
78490 **                       original value of the token will not parse.
78491 **    YYACTIONTYPE       is the data type used for storing terminal
78492 **                       and nonterminal numbers.  "unsigned char" is
78493 **                       used if there are fewer than 250 rules and
78494 **                       states combined.  "int" is used otherwise.
78495 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given 
78496 **                       directly to the parser from the tokenizer.
78497 **    YYMINORTYPE        is the data type used for all minor tokens.
78498 **                       This is typically a union of many types, one of
78499 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
78500 **                       for base tokens is called "yy0".
78501 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
78502 **                       zero the stack is dynamically sized using realloc()
78503 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
78504 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
78505 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
78506 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
78507 **    YYNSTATE           the combined number of states.
78508 **    YYNRULE            the number of rules in the grammar
78509 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
78510 **                       defined, then do no error processing.
78511 */
78512 #define YYCODETYPE unsigned char
78513 #define YYNOCODE 247
78514 #define YYACTIONTYPE unsigned short int
78515 #define YYWILDCARD 59
78516 #define sqlite3ParserTOKENTYPE Token
78517 typedef union {
78518   sqlite3ParserTOKENTYPE yy0;
78519   struct TrigEvent yy30;
78520   Expr* yy62;
78521   SrcList* yy151;
78522   struct LimitVal yy220;
78523   struct LikeOp yy222;
78524   IdList* yy240;
78525   int yy280;
78526   struct {int value; int mask;} yy359;
78527   TriggerStep* yy360;
78528   Select* yy375;
78529   ExprList* yy418;
78530 } YYMINORTYPE;
78531 #ifndef YYSTACKDEPTH
78532 #define YYSTACKDEPTH 100
78533 #endif
78534 #define sqlite3ParserARG_SDECL Parse *pParse;
78535 #define sqlite3ParserARG_PDECL ,Parse *pParse
78536 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
78537 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
78538 #define YYNSTATE 590
78539 #define YYNRULE 312
78540 #define YYFALLBACK 1
78541 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
78542 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
78543 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
78544
78545 /* The yyzerominor constant is used to initialize instances of
78546 ** YYMINORTYPE objects to zero. */
78547 #if 0
78548 static YYMINORTYPE yyzerominor;
78549 #else
78550 static const YYMINORTYPE yyzerominor;
78551 #endif
78552
78553 /* Next are the tables used to determine what action to take based on the
78554 ** current state and lookahead token.  These tables are used to implement
78555 ** functions that take a state number and lookahead value and return an
78556 ** action integer.  
78557 **
78558 ** Suppose the action integer is N.  Then the action is determined as
78559 ** follows
78560 **
78561 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
78562 **                                      token onto the stack and goto state N.
78563 **
78564 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
78565 **
78566 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
78567 **
78568 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
78569 **
78570 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
78571 **                                      slots in the yy_action[] table.
78572 **
78573 ** The action table is constructed as a single large table named yy_action[].
78574 ** Given state S and lookahead X, the action is computed as
78575 **
78576 **      yy_action[ yy_shift_ofst[S] + X ]
78577 **
78578 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
78579 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
78580 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
78581 ** and that yy_default[S] should be used instead.  
78582 **
78583 ** The formula above is for computing the action when the lookahead is
78584 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
78585 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
78586 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
78587 ** YY_SHIFT_USE_DFLT.
78588 **
78589 ** The following are the tables generated in this section:
78590 **
78591 **  yy_action[]        A single table containing all actions.
78592 **  yy_lookahead[]     A table containing the lookahead for each entry in
78593 **                     yy_action.  Used to detect hash collisions.
78594 **  yy_shift_ofst[]    For each state, the offset into yy_action for
78595 **                     shifting terminals.
78596 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
78597 **                     shifting non-terminals after a reduce.
78598 **  yy_default[]       Default action for each state.
78599 */
78600 static const YYACTIONTYPE yy_action[] = {
78601  /*     0 */   292,  903,  120,  589,    2,  172,  419,  419,   62,   62,
78602  /*    10 */    62,   62,  209,   64,   64,   64,   64,   65,   65,   66,
78603  /*    20 */    66,   66,   67,  211,  392,  389,  426,  432,   69,   64,
78604  /*    30 */    64,   64,   64,   65,   65,   66,   66,   66,   67,  211,
78605  /*    40 */   448,  213,  397,  452,   61,   60,  297,  436,  437,  433,
78606  /*    50 */   433,   63,   63,   62,   62,   62,   62,  264,   64,   64,
78607  /*    60 */    64,   64,   65,   65,   66,   66,   66,   67,  211,  292,
78608  /*    70 */   317,  419,  419,  490,  211,   83,   68,  421,   70,  154,
78609  /*    80 */    64,   64,   64,   64,   65,   65,   66,   66,   66,   67,
78610  /*    90 */   211,  489,  415,   36,  181,  426,  432,  448,  265,   59,
78611  /*   100 */    65,   65,   66,   66,   66,   67,  211,  398,  399,  423,
78612  /*   110 */   423,  423,  292,   61,   60,  297,  436,  437,  433,  433,
78613  /*   120 */    63,   63,   62,   62,   62,   62,  317,   64,   64,   64,
78614  /*   130 */    64,   65,   65,   66,   66,   66,   67,  211,  426,  432,
78615  /*   140 */    95,  313,  394,  475,  237,  172,  208,  419,  415,   35,
78616  /*   150 */    57,   67,  211,  201,  411,  475,   61,   60,  297,  436,
78617  /*   160 */   437,  433,  433,   63,   63,   62,   62,   62,   62,  503,
78618  /*   170 */    64,   64,   64,   64,   65,   65,   66,   66,   66,   67,
78619  /*   180 */   211,  292,  481,  524,  542,  573,  109,  416,  541,  452,
78620  /*   190 */   331,  317,  408,   21,  240,  340,  409,  522,  317,   68,
78621  /*   200 */   362,   70,  154,  572,  571,  519,  492,  426,  432,  149,
78622  /*   210 */   150,  380,  419,  415,   42,  412,  151,  533,  202,  490,
78623  /*   220 */   415,   50,  532,  421,  292,   61,   60,  297,  436,  437,
78624  /*   230 */   433,  433,   63,   63,   62,   62,   62,   62,  388,   64,
78625  /*   240 */    64,   64,   64,   65,   65,   66,   66,   66,   67,  211,
78626  /*   250 */   426,  432,  416,  333,  216,  423,  423,  423,   66,   66,
78627  /*   260 */    66,   67,  211,  491,  568,  212,  308,  292,   61,   60,
78628  /*   270 */   297,  436,  437,  433,  433,   63,   63,   62,   62,   62,
78629  /*   280 */    62,  397,   64,   64,   64,   64,   65,   65,   66,   66,
78630  /*   290 */    66,   67,  211,  426,  432,  182,  300,  410,  345,  348,
78631  /*   300 */   349,  531,  506,  252,   68,  519,   70,  154,  530,  350,
78632  /*   310 */   231,   61,   60,  297,  436,  437,  433,  433,   63,   63,
78633  /*   320 */    62,   62,   62,   62,  575,   64,   64,   64,   64,   65,
78634  /*   330 */    65,   66,   66,   66,   67,  211,  525,  317,  303,   78,
78635  /*   340 */   292,  238,  300,  511,  485,  153,  398,  399,  182,  494,
78636  /*   350 */   495,  345,  348,  349,  320,  152,  439,  439,  339,  415,
78637  /*   360 */    28,  328,  350,  512,  222,  370,  426,  432,  547,  495,
78638  /*   370 */   164,  114,  244,  343,  249,  344,  176,  583,  291,  416,
78639  /*   380 */   415,    3,   81,  253,   61,   60,  297,  436,  437,  433,
78640  /*   390 */   433,   63,   63,   62,   62,   62,   62,  174,   64,   64,
78641  /*   400 */    64,   64,   65,   65,   66,   66,   66,   67,  211,  292,
78642  /*   410 */   222,  587,  894,  488,  894,  302,  573,  114,  244,  343,
78643  /*   420 */   249,  344,  176,  182,  317,  397,  345,  348,  349,  253,
78644  /*   430 */   224,  416,  155,  549,  572,  426,  432,  350,   68,  463,
78645  /*   440 */    70,  154,  397,  175,  160,  397,  415,   35,  338,  587,
78646  /*   450 */   893,  584,  893,   61,   60,  297,  436,  437,  433,  433,
78647  /*   460 */    63,   63,   62,   62,   62,   62,  416,   64,   64,   64,
78648  /*   470 */    64,   65,   65,   66,   66,   66,   67,  211,  292,  550,
78649  /*   480 */   448,  213,  505,  373,  270,  269,  171,  160,  331,  584,
78650  /*   490 */   398,  399,  317,  330,  209,  383,  212,  159,  427,  428,
78651  /*   500 */   569,  570,  483,  524,  426,  432,  336,  398,  399,  230,
78652  /*   510 */   398,  399,  534,   21,  415,   42,  239,  549,  479,  430,
78653  /*   520 */   431,  475,   61,   60,  297,  436,  437,  433,  433,   63,
78654  /*   530 */    63,   62,   62,   62,   62,  264,   64,   64,   64,   64,
78655  /*   540 */    65,   65,   66,   66,   66,   67,  211,  292,  429,  287,
78656  /*   550 */   457,  256,  450,  523,  168,  215,  197,  295,  317,  353,
78657  /*   560 */   242,  317,  458,  298,  443,  444,  468,  373,  270,  269,
78658  /*   570 */   322,  443,  444,  426,  432,  459,  558,  496,  209,  299,
78659  /*   580 */   415,   35,  544,  415,   50,    1,  177,  497,  479,  397,
78660  /*   590 */   416,   61,   60,  297,  436,  437,  433,  433,   63,   63,
78661  /*   600 */    62,   62,   62,   62,  484,   64,   64,   64,   64,   65,
78662  /*   610 */    65,   66,   66,   66,   67,  211,  292,  317,  524,  375,
78663  /*   620 */   457,   94,  335,  590,  392,  389,  212,  580,   21,  309,
78664  /*   630 */    10,  363,  458,  212,  397,  209,  366,  391,    2,  415,
78665  /*   640 */    29,  294,  426,  432,  195,  459,  253,  327,  372,  361,
78666  /*   650 */   440,  450,  323,  168,  398,  399,  252,  147,  546,  292,
78667  /*   660 */    61,   60,  297,  436,  437,  433,  433,   63,   63,   62,
78668  /*   670 */    62,   62,   62,  317,   64,   64,   64,   64,   65,   65,
78669  /*   680 */    66,   66,   66,   67,  211,  426,  432,  210,  318,  453,
78670  /*   690 */   320,  223,  439,  439,   56,  415,   24,  826,  252,  398,
78671  /*   700 */   399,  193,  292,   61,   60,  297,  436,  437,  433,  433,
78672  /*   710 */    63,   63,   62,   62,   62,   62,  226,   64,   64,   64,
78673  /*   720 */    64,   65,   65,   66,   66,   66,   67,  211,  426,  432,
78674  /*   730 */   311,  119,  264,  304,  396,  416,  320,   19,  439,  439,
78675  /*   740 */   400,  401,  402,   85,  274,  292,   61,   71,  297,  436,
78676  /*   750 */   437,  433,  433,   63,   63,   62,   62,   62,   62,  371,
78677  /*   760 */    64,   64,   64,   64,   65,   65,   66,   66,   66,   67,
78678  /*   770 */   211,  426,  432,  385,  115,  320,   18,  439,  439,  446,
78679  /*   780 */   446,  374,  277,    5,  275,  264,    8,  252,  292,  341,
78680  /*   790 */    60,  297,  436,  437,  433,  433,   63,   63,   62,   62,
78681  /*   800 */    62,   62,  397,   64,   64,   64,   64,   65,   65,   66,
78682  /*   810 */    66,   66,   67,  211,  426,  432,  414,  397,  422,  470,
78683  /*   820 */   413,   22,  305,  387,  252,  419,  560,  193,  414,  264,
78684  /*   830 */   264,  370,  413,  190,  297,  436,  437,  433,  433,   63,
78685  /*   840 */    63,   62,   62,   62,   62,  479,   64,   64,   64,   64,
78686  /*   850 */    65,   65,   66,   66,   66,   67,  211,   73,  324,  306,
78687  /*   860 */     4,  416,  264,  276,  296,  449,  177,  398,  399,  317,
78688  /*   870 */   561,  562,  321,   73,  324,  317,    4,  540,  360,  540,
78689  /*   880 */   296,  329,  398,  399,  461,  371,  158,  317,  321,  326,
78690  /*   890 */   419,  415,   33,  471,  317,  165,  225,  415,   54,  452,
78691  /*   900 */   317,  264,  317,  278,  317,  326,  307,  367,  472,  415,
78692  /*   910 */    53,  470,  178,  179,  180,  452,  415,   99,  317,   76,
78693  /*   920 */    75,  294,  415,   97,  415,  102,  415,  103,   74,  315,
78694  /*   930 */   316,  319,  264,  421,  469,   76,   75,  482,  317,  382,
78695  /*   940 */   415,  108,  379,  474,   74,  315,  316,   73,  324,  421,
78696  /*   950 */     4,  209,  317,  156,  296,  317,  184,  465,  209,  187,
78697  /*   960 */   415,  110,  321,  258,  466,  423,  423,  423,  424,  425,
78698  /*   970 */    12,  381,  478,  280,  415,   17,  250,  415,  100,  326,
78699  /*   980 */   507,  423,  423,  423,  424,  425,   12,  416,  624,  452,
78700  /*   990 */   416,  162,  508,  416,  317,  513,  227,  228,  229,  105,
78701  /*  1000 */   514,  262,  317,  260,   20,  317,  144,  434,  317,   76,
78702  /*  1010 */    75,   77,  206,   79,  282,  317,  415,   34,   74,  315,
78703  /*  1020 */   316,  283,  317,  421,  415,   98,  251,  415,   25,  526,
78704  /*  1030 */   415,   55,  441,  204,   23,  549,  257,  415,  111,  203,
78705  /*  1040 */   317,  477,  205,  173,  415,  112,  317,  259,  317,  515,
78706  /*  1050 */   317,  181,  317,  261,  245,  423,  423,  423,  424,  425,
78707  /*  1060 */    12,  263,  415,  113,  357,  246,  317,  268,  415,   26,
78708  /*  1070 */   415,   37,  415,   38,  415,   27,  317,  500,  501,  510,
78709  /*  1080 */   509,  317,  365,  317,  368,  378,  279,  269,  415,   39,
78710  /*  1090 */   369,  293,  317,  255,  317,  181,  209,  271,  415,   40,
78711  /*  1100 */   317,  272,  317,  415,   41,  415,   43,  352,  317,  181,
78712  /*  1110 */   317,  273,  557,  317,  415,   44,  415,   45,  317,  545,
78713  /*  1120 */   384,  181,  415,   30,  415,   31,  317,  585,  567,  317,
78714  /*  1130 */   415,   46,  415,   47,  317,  415,   48,  317,  281,  284,
78715  /*  1140 */   415,   49,  553,  554,  173,   92,  285,  579,  415,   32,
78716  /*  1150 */   406,  415,   11,  565,  420,   92,  415,   51,  146,  415,
78717  /*  1160 */    52,  582,  232,  290,  325,  517,  586,  445,  447,  464,
78718  /*  1170 */   467,  506,  520,  163,  247,  516,  395,  518,  552,  347,
78719  /*  1180 */   403,  404,  405,  564,    7,  314,   85,  334,  332,  233,
78720  /*  1190 */    84,  234,   80,  170,   58,  214,  417,  462,  121,   86,
78721  /*  1200 */   337,  342,  499,  493,  235,  301,  236,  503,  418,  498,
78722  /*  1210 */   248,  124,  504,  502,  220,  354,  288,  241,  527,  476,
78723  /*  1220 */   243,  528,  480,  521,  529,  289,  185,  358,  535,  186,
78724  /*  1230 */    89,  356,  189,  188,  117,  537,  364,  191,  548,  194,
78725  /*  1240 */   219,  132,  142,  221,  376,  377,  555,  133,  134,  310,
78726  /*  1250 */   135,  136,  266,  563,  538,  581,  576,  141,   93,  393,
78727  /*  1260 */    96,  138,  407,  577,  578,  107,  218,  101,  104,  118,
78728  /*  1270 */   312,  625,  626,  166,  435,  167,  438,  442,   72,  454,
78729  /*  1280 */   451,  143,  157,  169,  455,  456,  460,    6,   14,   82,
78730  /*  1290 */   473,   13,  122,  161,  123,  486,  487,  217,   87,  346,
78731  /*  1300 */   125,  126,  116,  254,   88,  127,  183,  246,  355,  145,
78732  /*  1310 */   536,  128,  173,  359,  192,  351,  267,  130,    9,  551,
78733  /*  1320 */   131,  196,   90,  539,   91,  129,   15,  198,  556,  543,
78734  /*  1330 */   199,  559,  200,  137,  139,  566,   16,  140,  106,  574,
78735  /*  1340 */   207,  148,  286,  390,  386,  588,
78736 };
78737 static const YYCODETYPE yy_lookahead[] = {
78738  /*     0 */    16,  139,  140,  141,  142,   21,   23,   23,   69,   70,
78739  /*    10 */    71,   72,  110,   74,   75,   76,   77,   78,   79,   80,
78740  /*    20 */    81,   82,   83,   84,    1,    2,   42,   43,   73,   74,
78741  /*    30 */    75,   76,   77,   78,   79,   80,   81,   82,   83,   84,
78742  /*    40 */    78,   79,   23,   58,   60,   61,   62,   63,   64,   65,
78743  /*    50 */    66,   67,   68,   69,   70,   71,   72,  147,   74,   75,
78744  /*    60 */    76,   77,   78,   79,   80,   81,   82,   83,   84,   16,
78745  /*    70 */   147,   88,   88,   88,   84,   22,  217,   92,  219,  220,
78746  /*    80 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
78747  /*    90 */    84,  169,  169,  170,   22,   42,   43,   78,  188,   46,
78748  /*   100 */    78,   79,   80,   81,   82,   83,   84,   88,   89,  124,
78749  /*   110 */   125,  126,   16,   60,   61,   62,   63,   64,   65,   66,
78750  /*   120 */    67,   68,   69,   70,   71,   72,  147,   74,   75,   76,
78751  /*   130 */    77,   78,   79,   80,   81,   82,   83,   84,   42,   43,
78752  /*   140 */    44,  143,  144,  161,  221,   21,  148,   23,  169,  170,
78753  /*   150 */    19,   83,   84,  155,   23,  161,   60,   61,   62,   63,
78754  /*   160 */    64,   65,   66,   67,   68,   69,   70,   71,   72,   97,
78755  /*   170 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
78756  /*   180 */    84,   16,  200,  147,   25,  147,   21,  189,   29,   58,
78757  /*   190 */   211,  147,  156,  157,  200,  216,  167,  168,  147,  217,
78758  /*   200 */    41,  219,  220,  165,  166,  176,  160,   42,   43,   78,
78759  /*   210 */    79,  213,   88,  169,  170,  169,  180,  181,  155,   88,
78760  /*   220 */   169,  170,  181,   92,   16,   60,   61,   62,   63,   64,
78761  /*   230 */    65,   66,   67,   68,   69,   70,   71,   72,  240,   74,
78762  /*   240 */    75,   76,   77,   78,   79,   80,   81,   82,   83,   84,
78763  /*   250 */    42,   43,  189,  209,  210,  124,  125,  126,   80,   81,
78764  /*   260 */    82,   83,   84,  169,  226,  227,  215,   16,   60,   61,
78765  /*   270 */    62,   63,   64,   65,   66,   67,   68,   69,   70,   71,
78766  /*   280 */    72,   23,   74,   75,   76,   77,   78,   79,   80,   81,
78767  /*   290 */    82,   83,   84,   42,   43,   90,   16,  168,   93,   94,
78768  /*   300 */    95,  176,  177,  147,  217,  176,  219,  220,  183,  104,
78769  /*   310 */   190,   60,   61,   62,   63,   64,   65,   66,   67,   68,
78770  /*   320 */    69,   70,   71,   72,  237,   74,   75,   76,   77,   78,
78771  /*   330 */    79,   80,   81,   82,   83,   84,  181,  147,  182,  131,
78772  /*   340 */    16,  147,   16,   30,   20,  155,   88,   89,   90,  185,
78773  /*   350 */   186,   93,   94,   95,  106,   22,  108,  109,  147,  169,
78774  /*   360 */   170,  186,  104,   50,   84,  147,   42,   43,  185,  186,
78775  /*   370 */    90,   91,   92,   93,   94,   95,   96,  243,  244,  189,
78776  /*   380 */   169,  170,  131,  103,   60,   61,   62,   63,   64,   65,
78777  /*   390 */    66,   67,   68,   69,   70,   71,   72,  155,   74,   75,
78778  /*   400 */    76,   77,   78,   79,   80,   81,   82,   83,   84,   16,
78779  /*   410 */    84,   19,   20,   20,   22,  102,  147,   91,   92,   93,
78780  /*   420 */    94,   95,   96,   90,  147,   23,   93,   94,   95,  103,
78781  /*   430 */   212,  189,  155,   49,  165,   42,   43,  104,  217,  218,
78782  /*   440 */   219,  220,   23,  201,  202,   23,  169,  170,  206,   19,
78783  /*   450 */    20,   59,   22,   60,   61,   62,   63,   64,   65,   66,
78784  /*   460 */    67,   68,   69,   70,   71,   72,  189,   74,   75,   76,
78785  /*   470 */    77,   78,   79,   80,   81,   82,   83,   84,   16,   11,
78786  /*   480 */    78,   79,   20,   99,  100,  101,  201,  202,  211,   59,
78787  /*   490 */    88,   89,  147,  216,  110,  226,  227,  147,   42,   43,
78788  /*   500 */    98,   99,   80,  147,   42,   43,  147,   88,   89,  153,
78789  /*   510 */    88,   89,  156,  157,  169,  170,  147,   49,  147,   63,
78790  /*   520 */    64,  161,   60,   61,   62,   63,   64,   65,   66,   67,
78791  /*   530 */    68,   69,   70,   71,   72,  147,   74,   75,   76,   77,
78792  /*   540 */    78,   79,   80,   81,   82,   83,   84,   16,   92,  158,
78793  /*   550 */    12,   20,  161,  162,  163,  210,  155,  150,  147,   16,
78794  /*   560 */   200,  147,   24,  164,  165,  166,   22,   99,  100,  101,
78795  /*   570 */   164,  165,  166,   42,   43,   37,  188,   39,  110,  208,
78796  /*   580 */   169,  170,   18,  169,  170,   19,   43,   49,  147,   23,
78797  /*   590 */   189,   60,   61,   62,   63,   64,   65,   66,   67,   68,
78798  /*   600 */    69,   70,   71,   72,   20,   74,   75,   76,   77,   78,
78799  /*   610 */    79,   80,   81,   82,   83,   84,   16,  147,  147,   55,
78800  /*   620 */    12,   21,  211,    0,    1,    2,  227,  156,  157,  215,
78801  /*   630 */    19,  224,   24,  227,   23,  110,  229,  141,  142,  169,
78802  /*   640 */   170,   98,   42,   43,   22,   37,  103,   39,  123,  208,
78803  /*   650 */    20,  161,  162,  163,   88,   89,  147,  113,   94,   16,
78804  /*   660 */    60,   61,   62,   63,   64,   65,   66,   67,   68,   69,
78805  /*   670 */    70,   71,   72,  147,   74,   75,   76,   77,   78,   79,
78806  /*   680 */    80,   81,   82,   83,   84,   42,   43,  192,  147,   20,
78807  /*   690 */   106,  182,  108,  109,  199,  169,  170,  133,  147,   88,
78808  /*   700 */    89,  155,   16,   60,   61,   62,   63,   64,   65,   66,
78809  /*   710 */    67,   68,   69,   70,   71,   72,  145,   74,   75,   76,
78810  /*   720 */    77,   78,   79,   80,   81,   82,   83,   84,   42,   43,
78811  /*   730 */   241,  242,  147,  182,  147,  189,  106,   19,  108,  109,
78812  /*   740 */     7,    8,    9,  121,   14,   16,   60,   61,   62,   63,
78813  /*   750 */    64,   65,   66,   67,   68,   69,   70,   71,   72,  213,
78814  /*   760 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
78815  /*   770 */    84,   42,   43,  188,  147,  106,  230,  108,  109,  124,
78816  /*   780 */   125,  235,   52,  191,   54,  147,   68,  147,   16,   80,
78817  /*   790 */    61,   62,   63,   64,   65,   66,   67,   68,   69,   70,
78818  /*   800 */    71,   72,   23,   74,   75,   76,   77,   78,   79,   80,
78819  /*   810 */    81,   82,   83,   84,   42,   43,  107,   23,  147,   22,
78820  /*   820 */   111,   19,  182,  238,  147,   23,  188,  155,  107,  147,
78821  /*   830 */   147,  147,  111,  231,   62,   63,   64,   65,   66,   67,
78822  /*   840 */    68,   69,   70,   71,   72,  147,   74,   75,   76,   77,
78823  /*   850 */    78,   79,   80,   81,   82,   83,   84,   16,   17,  182,
78824  /*   860 */    19,  189,  147,  133,   23,  161,   43,   88,   89,  147,
78825  /*   870 */   188,  188,   31,   16,   17,  147,   19,   99,  100,  101,
78826  /*   880 */    23,  147,   88,   89,  147,  213,   89,  147,   31,   48,
78827  /*   890 */    88,  169,  170,  114,  147,   19,  212,  169,  170,   58,
78828  /*   900 */   147,  147,  147,  188,  147,   48,  208,  235,  114,  169,
78829  /*   910 */   170,  114,   99,  100,  101,   58,  169,  170,  147,   78,
78830  /*   920 */    79,   98,  169,  170,  169,  170,  169,  170,   87,   88,
78831  /*   930 */    89,   16,  147,   92,  203,   78,   79,   80,  147,   91,
78832  /*   940 */   169,  170,  188,  147,   87,   88,   89,   16,   17,   92,
78833  /*   950 */    19,  110,  147,  155,   23,  147,  155,   27,  110,  155,
78834  /*   960 */   169,  170,   31,   14,   34,  124,  125,  126,  127,  128,
78835  /*   970 */   129,  123,  147,  188,  169,  170,  147,  169,  170,   48,
78836  /*   980 */   147,  124,  125,  126,  127,  128,  129,  189,  112,   58,
78837  /*   990 */   189,    5,  178,  189,  147,  178,   10,   11,   12,   13,
78838  /*  1000 */   178,   52,  147,   54,   19,  147,   21,   92,  147,   78,
78839  /*  1010 */    79,  130,   26,  132,   28,  147,  169,  170,   87,   88,
78840  /*  1020 */    89,   35,  147,   92,  169,  170,  147,  169,  170,  147,
78841  /*  1030 */   169,  170,   20,   47,   22,   49,  147,  169,  170,   53,
78842  /*  1040 */   147,   20,   56,   22,  169,  170,  147,  147,  147,   20,
78843  /*  1050 */   147,   22,  147,  147,   92,  124,  125,  126,  127,  128,
78844  /*  1060 */   129,  147,  169,  170,  232,  103,  147,  147,  169,  170,
78845  /*  1070 */   169,  170,  169,  170,  169,  170,  147,    7,    8,   91,
78846  /*  1080 */    92,  147,  147,  147,  147,   99,  100,  101,  169,  170,
78847  /*  1090 */   147,  105,  147,   20,  147,   22,  110,  147,  169,  170,
78848  /*  1100 */   147,  147,  147,  169,  170,  169,  170,   20,  147,   22,
78849  /*  1110 */   147,  147,  147,  147,  169,  170,  169,  170,  147,   20,
78850  /*  1120 */   134,   22,  169,  170,  169,  170,  147,   20,  147,  147,
78851  /*  1130 */   169,  170,  169,  170,  147,  169,  170,  147,  147,  147,
78852  /*  1140 */   169,  170,   20,   20,   22,   22,  147,  147,  169,  170,
78853  /*  1150 */   149,  169,  170,   20,  161,   22,  169,  170,  191,  169,
78854  /*  1160 */   170,   20,  193,   22,  223,  161,   59,  228,  228,  172,
78855  /*  1170 */   172,  177,  161,    6,  172,  172,  146,  172,  194,  173,
78856  /*  1180 */   146,  146,  146,  194,   22,  154,  121,  118,  116,  194,
78857  /*  1190 */   119,  195,  130,  112,  120,  222,  189,  152,  152,   98,
78858  /*  1200 */   115,   98,  179,  171,  196,   40,  197,   97,  198,  171,
78859  /*  1210 */   171,   19,  171,  173,   84,   15,  174,  204,  171,  205,
78860  /*  1220 */   204,  171,  205,  179,  171,  174,  151,   38,  152,  151,
78861  /*  1230 */   130,  152,  152,  151,   60,  152,  152,  151,  184,  184,
78862  /*  1240 */   225,   19,  214,  225,  152,   15,  194,  187,  187,  152,
78863  /*  1250 */   187,  187,  233,  194,  234,  137,   33,  214,  236,    1,
78864  /*  1260 */   236,  184,   20,  152,  152,  239,  175,  159,  175,  242,
78865  /*  1270 */   245,  112,  112,  112,   92,  112,  107,   20,   19,   11,
78866  /*  1280 */    20,   19,   19,   22,   20,   20,   20,  117,  117,   22,
78867  /*  1290 */   114,   22,   19,  112,   20,   20,   20,   44,   19,   44,
78868  /*  1300 */    19,   19,   32,   20,   19,   19,   96,  103,   16,   21,
78869  /*  1310 */    17,   98,   22,   36,   98,   44,  133,   19,    5,    1,
78870  /*  1320 */   102,  122,   68,   51,   68,   45,   19,  113,    1,   45,
78871  /*  1330 */    14,   17,  115,  113,  102,  123,   19,  122,   14,   20,
78872  /*  1340 */   135,   19,  136,    3,   57,    4,
78873 };
78874 #define YY_SHIFT_USE_DFLT (-99)
78875 #define YY_SHIFT_MAX 390
78876 static const short yy_shift_ofst[] = {
78877  /*     0 */    23,  841,  986,  -16,  841,  931,  931,  258,  402,  384,
78878  /*    10 */   -98,   96,  931,  931,  931,  931,  931,  -45,  468,   19,
78879  /*    20 */   419,  -17,  -38,  -38,   53,  165,  208,  251,  324,  393,
78880  /*    30 */   462,  531,  600,  643,  686,  643,  643,  643,  643,  643,
78881  /*    40 */   643,  643,  643,  643,  643,  643,  643,  643,  643,  643,
78882  /*    50 */   643,  643,  643,  729,  772,  772,  857,  931,  931,  931,
78883  /*    60 */   931,  931,  931,  931,  931,  931,  931,  931,  931,  931,
78884  /*    70 */   931,  931,  931,  931,  931,  931,  931,  931,  931,  931,
78885  /*    80 */   931,  931,  931,  931,  931,  931,  931,  931,  931,  931,
78886  /*    90 */   931,  931,  931,  931,  931,  931,  931,  -61,  -61,    6,
78887  /*   100 */     6,  280,   22,  178,  543,  564,  419,  419,   68,  -17,
78888  /*   110 */   -10,  -99,  -99,  -99,  131,  326,  538,  538,  392,  430,
78889  /*   120 */   623,  124,  419,  124,  419,  419,  419,  419,  419,  419,
78890  /*   130 */   419,  419,  419,  419,  419,  419,  419,  419,  419,  419,
78891  /*   140 */   419,  848,  525,  -98,  -98,  -98,  -99,  -99,  -99,  -15,
78892  /*   150 */   -15,  333,  205,  584,  566,  630,  669,  608,  779,  794,
78893  /*   160 */   611,  422,  733,  419,  419,  709,  419,  419,  802,  419,
78894  /*   170 */   419,  797,  419,  419,  248,  797,  419,  419,  313,  313,
78895  /*   180 */   313,  419,  419,  419,  248,  419,  419,  248,  419,  159,
78896  /*   190 */   778,  419,  419,  248,  419,  419,  419,  248,  419,  419,
78897  /*   200 */   419,  248,  248,  419,  419,  419,  419,  419,  985,  721,
78898  /*   210 */   544,  -17,  655,  655,  881,  930,  930,  930,  823,  930,
78899  /*   220 */   -17,  930,  -17,   72,  622,  622, 1167, 1167, 1167, 1167,
78900  /*   230 */  1162,  -98, 1065, 1069, 1071, 1072, 1074, 1062, 1081, 1081,
78901  /*   240 */  1101, 1085, 1101, 1085, 1103, 1103, 1165, 1103, 1110, 1103,
78902  /*   250 */  1192, 1130, 1130, 1165, 1103, 1103, 1103, 1192, 1200, 1081,
78903  /*   260 */  1200, 1081, 1200, 1081, 1081, 1189, 1100, 1200, 1081, 1174,
78904  /*   270 */  1174, 1222, 1065, 1081, 1230, 1230, 1230, 1230, 1065, 1174,
78905  /*   280 */  1222, 1081, 1223, 1223, 1081, 1081, 1118,  -99,  -99,  -99,
78906  /*   290 */   -99,  -99,  456,  730,  813,  949,  876,  915, 1012, 1021,
78907  /*   300 */   962, 1070,  988, 1029, 1073, 1087, 1099, 1122, 1123, 1133,
78908  /*   310 */   718, 1141, 1107, 1258, 1242, 1159, 1160, 1161, 1163, 1182,
78909  /*   320 */  1169, 1259, 1257, 1260, 1262, 1268, 1263, 1264, 1261, 1265,
78910  /*   330 */  1266, 1267, 1170, 1269, 1171, 1267, 1176, 1273, 1274, 1181,
78911  /*   340 */  1275, 1276, 1270, 1253, 1279, 1255, 1281, 1283, 1282, 1285,
78912  /*   350 */  1271, 1286, 1210, 1204, 1292, 1293, 1288, 1213, 1277, 1272,
78913  /*   360 */  1280, 1290, 1284, 1183, 1216, 1298, 1313, 1318, 1218, 1254,
78914  /*   370 */  1256, 1199, 1307, 1214, 1327, 1316, 1217, 1314, 1220, 1232,
78915  /*   380 */  1215, 1317, 1212, 1319, 1324, 1287, 1205, 1206, 1322, 1340,
78916  /*   390 */  1341,
78917 };
78918 #define YY_REDUCE_USE_DFLT (-142)
78919 #define YY_REDUCE_MAX 291
78920 static const short yy_reduce_ofst[] = {
78921  /*     0 */  -138,  277,   -2,  -18,  190,  -21,   44,   36,   38,  546,
78922  /*    10 */   242,   87,  -77,  345,  411,   51,  414,  221,  672,  269,
78923  /*    20 */   356,  391,  399,  406, -141, -141, -141, -141, -141, -141,
78924  /*    30 */  -141, -141, -141, -141, -141, -141, -141, -141, -141, -141,
78925  /*    40 */  -141, -141, -141, -141, -141, -141, -141, -141, -141, -141,
78926  /*    50 */  -141, -141, -141, -141, -141, -141,  211,  470,  526,  722,
78927  /*    60 */   728,  740,  747,  753,  755,  757,  771,  791,  805,  808,
78928  /*    70 */   847,  855,  858,  861,  868,  875,  893,  899,  901,  903,
78929  /*    80 */   905,  919,  929,  934,  936,  945,  947,  953,  955,  961,
78930  /*    90 */   963,  966,  971,  979,  982,  987,  990, -141, -141, -141,
78931  /*   100 */  -141,   29, -141, -141,  125,  407,  585,  471, -141,  490,
78932  /*   110 */  -141, -141, -141, -141,   46,  129,  164,  183,  134,  134,
78933  /*   120 */   496,   -6,  371,  360,  156,  509,  551,  640,  -90,  441,
78934  /*   130 */   677,  218,  698,  388,  638,  682,  683,  715,  754,  684,
78935  /*   140 */   785,   63,  401,  798,  801,  804,  495,  285,  489,  -78,
78936  /*   150 */    94,   41,  155,  120,  194,  120,  120,  175,  350,  359,
78937  /*   160 */   369,  541,  571,  587,  627,  592,  541,  671,  704,  734,
78938  /*   170 */   737,  731,  796,  825,  120,  731,  829,  833,  814,  817,
78939  /*   180 */   822,  879,  882,  889,  120,  900,  906,  120,  914,  602,
78940  /*   190 */   832,  920,  935,  120,  937,  943,  950,  120,  954,  964,
78941  /*   200 */   965,  120,  120,  981,  991,  992,  999, 1000, 1001,  967,
78942  /*   210 */   969,  993,  939,  940,  941,  997,  998, 1002,  994, 1003,
78943  /*   220 */  1004, 1005, 1011, 1006,  984,  989, 1030, 1034, 1035, 1036,
78944  /*   230 */  1031, 1007,  995,  996, 1008, 1009, 1010,  973, 1045, 1046,
78945  /*   240 */  1013, 1014, 1016, 1017, 1032, 1038, 1023, 1039, 1040, 1041,
78946  /*   250 */  1042, 1015, 1018, 1044, 1047, 1050, 1053, 1051, 1075, 1076,
78947  /*   260 */  1078, 1079, 1082, 1080, 1083, 1019, 1020, 1086, 1084, 1054,
78948  /*   270 */  1055, 1028, 1052, 1092, 1060, 1061, 1063, 1064, 1059, 1077,
78949  /*   280 */  1043, 1097, 1022, 1024, 1111, 1112, 1026, 1108, 1091, 1093,
78950  /*   290 */  1027, 1025,
78951 };
78952 static const YYACTIONTYPE yy_default[] = {
78953  /*     0 */   595,  821,  902,  711,  902,  821,  902,  902,  848,  902,
78954  /*    10 */   715,  877,  819,  902,  902,  902,  902,  793,  902,  848,
78955  /*    20 */   902,  627,  848,  848,  744,  902,  902,  902,  902,  902,
78956  /*    30 */   902,  902,  902,  745,  902,  823,  818,  814,  816,  815,
78957  /*    40 */   822,  746,  735,  742,  749,  727,  861,  751,  752,  758,
78958  /*    50 */   759,  878,  876,  781,  780,  799,  902,  902,  902,  902,
78959  /*    60 */   902,  902,  902,  902,  902,  902,  902,  902,  902,  902,
78960  /*    70 */   902,  902,  902,  902,  902,  902,  902,  902,  902,  902,
78961  /*    80 */   902,  902,  902,  902,  902,  902,  902,  902,  902,  902,
78962  /*    90 */   902,  902,  902,  902,  902,  902,  902,  783,  805,  782,
78963  /*   100 */   792,  620,  784,  785,  680,  615,  902,  902,  786,  902,
78964  /*   110 */   787,  800,  801,  802,  902,  902,  902,  902,  902,  902,
78965  /*   120 */   595,  711,  902,  711,  902,  902,  902,  902,  902,  902,
78966  /*   130 */   902,  902,  902,  902,  902,  902,  902,  902,  902,  902,
78967  /*   140 */   902,  902,  902,  902,  902,  902,  705,  715,  895,  902,
78968  /*   150 */   902,  671,  902,  902,  902,  902,  902,  902,  902,  902,
78969  /*   160 */   902,  902,  603,  601,  902,  703,  902,  902,  629,  902,
78970  /*   170 */   902,  713,  902,  902,  718,  719,  902,  902,  902,  902,
78971  /*   180 */   902,  902,  902,  902,  617,  902,  902,  692,  902,  854,
78972  /*   190 */   902,  902,  902,  868,  902,  902,  902,  866,  902,  902,
78973  /*   200 */   902,  694,  754,  834,  902,  881,  883,  902,  902,  703,
78974  /*   210 */   712,  902,  902,  902,  817,  738,  738,  738,  650,  738,
78975  /*   220 */   902,  738,  902,  653,  748,  748,  600,  600,  600,  600,
78976  /*   230 */   670,  902,  748,  739,  741,  731,  743,  902,  720,  720,
78977  /*   240 */   728,  730,  728,  730,  682,  682,  667,  682,  653,  682,
78978  /*   250 */   827,  831,  831,  667,  682,  682,  682,  827,  612,  720,
78979  /*   260 */   612,  720,  612,  720,  720,  858,  860,  612,  720,  684,
78980  /*   270 */   684,  760,  748,  720,  691,  691,  691,  691,  748,  684,
78981  /*   280 */   760,  720,  880,  880,  720,  720,  888,  637,  655,  655,
78982  /*   290 */   895,  900,  902,  902,  902,  902,  767,  902,  902,  902,
78983  /*   300 */   902,  902,  902,  902,  902,  902,  902,  902,  902,  902,
78984  /*   310 */   841,  902,  902,  902,  902,  772,  768,  902,  769,  902,
78985  /*   320 */   697,  902,  902,  902,  902,  902,  902,  902,  902,  902,
78986  /*   330 */   902,  820,  902,  732,  902,  740,  902,  902,  902,  902,
78987  /*   340 */   902,  902,  902,  902,  902,  902,  902,  902,  902,  902,
78988  /*   350 */   902,  902,  902,  902,  902,  902,  902,  902,  902,  902,
78989  /*   360 */   856,  857,  902,  902,  902,  902,  902,  902,  902,  902,
78990  /*   370 */   902,  902,  902,  902,  902,  902,  902,  902,  902,  902,
78991  /*   380 */   902,  902,  902,  902,  902,  887,  902,  902,  890,  596,
78992  /*   390 */   902,  591,  593,  594,  598,  599,  602,  624,  625,  626,
78993  /*   400 */   604,  605,  606,  607,  608,  609,  610,  616,  618,  636,
78994  /*   410 */   638,  622,  640,  701,  702,  764,  695,  696,  700,  623,
78995  /*   420 */   775,  766,  770,  771,  773,  774,  788,  789,  791,  797,
78996  /*   430 */   804,  807,  790,  795,  796,  798,  803,  806,  698,  699,
78997  /*   440 */   810,  630,  631,  634,  635,  844,  846,  845,  847,  633,
78998  /*   450 */   632,  776,  779,  812,  813,  869,  870,  871,  872,  873,
78999  /*   460 */   808,  721,  811,  794,  733,  736,  737,  734,  704,  714,
79000  /*   470 */   723,  724,  725,  726,  709,  710,  716,  729,  762,  763,
79001  /*   480 */   717,  706,  707,  708,  809,  765,  777,  778,  641,  642,
79002  /*   490 */   772,  643,  644,  645,  683,  686,  687,  688,  646,  665,
79003  /*   500 */   668,  669,  647,  654,  648,  649,  656,  657,  658,  661,
79004  /*   510 */   662,  663,  664,  659,  660,  828,  829,  832,  830,  651,
79005  /*   520 */   652,  666,  639,  628,  621,  672,  675,  676,  677,  678,
79006  /*   530 */   679,  681,  673,  674,  619,  611,  613,  722,  850,  859,
79007  /*   540 */   855,  851,  852,  853,  614,  824,  825,  685,  756,  757,
79008  /*   550 */   849,  862,  864,  761,  865,  867,  863,  892,  689,  690,
79009  /*   560 */   693,  833,  874,  747,  750,  753,  755,  835,  836,  837,
79010  /*   570 */   838,  839,  842,  843,  840,  875,  879,  882,  884,  885,
79011  /*   580 */   886,  889,  891,  896,  897,  898,  901,  899,  597,  592,
79012 };
79013 #define YY_SZ_ACTTAB (int)(sizeof(yy_action)/sizeof(yy_action[0]))
79014
79015 /* The next table maps tokens into fallback tokens.  If a construct
79016 ** like the following:
79017 ** 
79018 **      %fallback ID X Y Z.
79019 **
79020 ** appears in the grammar, then ID becomes a fallback token for X, Y,
79021 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
79022 ** but it does not parse, the type of the token is changed to ID and
79023 ** the parse is retried before an error is thrown.
79024 */
79025 #ifdef YYFALLBACK
79026 static const YYCODETYPE yyFallback[] = {
79027     0,  /*          $ => nothing */
79028     0,  /*       SEMI => nothing */
79029    23,  /*    EXPLAIN => ID */
79030    23,  /*      QUERY => ID */
79031    23,  /*       PLAN => ID */
79032    23,  /*      BEGIN => ID */
79033     0,  /* TRANSACTION => nothing */
79034    23,  /*   DEFERRED => ID */
79035    23,  /*  IMMEDIATE => ID */
79036    23,  /*  EXCLUSIVE => ID */
79037     0,  /*     COMMIT => nothing */
79038    23,  /*        END => ID */
79039     0,  /*   ROLLBACK => nothing */
79040     0,  /*     CREATE => nothing */
79041     0,  /*      TABLE => nothing */
79042    23,  /*         IF => ID */
79043     0,  /*        NOT => nothing */
79044     0,  /*     EXISTS => nothing */
79045    23,  /*       TEMP => ID */
79046     0,  /*         LP => nothing */
79047     0,  /*         RP => nothing */
79048     0,  /*         AS => nothing */
79049     0,  /*      COMMA => nothing */
79050     0,  /*         ID => nothing */
79051    23,  /*      ABORT => ID */
79052    23,  /*      AFTER => ID */
79053    23,  /*    ANALYZE => ID */
79054    23,  /*        ASC => ID */
79055    23,  /*     ATTACH => ID */
79056    23,  /*     BEFORE => ID */
79057    23,  /*    CASCADE => ID */
79058    23,  /*       CAST => ID */
79059    23,  /*   CONFLICT => ID */
79060    23,  /*   DATABASE => ID */
79061    23,  /*       DESC => ID */
79062    23,  /*     DETACH => ID */
79063    23,  /*       EACH => ID */
79064    23,  /*       FAIL => ID */
79065    23,  /*        FOR => ID */
79066    23,  /*     IGNORE => ID */
79067    23,  /*  INITIALLY => ID */
79068    23,  /*    INSTEAD => ID */
79069    23,  /*    LIKE_KW => ID */
79070    23,  /*      MATCH => ID */
79071    23,  /*        KEY => ID */
79072    23,  /*         OF => ID */
79073    23,  /*     OFFSET => ID */
79074    23,  /*     PRAGMA => ID */
79075    23,  /*      RAISE => ID */
79076    23,  /*    REPLACE => ID */
79077    23,  /*   RESTRICT => ID */
79078    23,  /*        ROW => ID */
79079    23,  /*    TRIGGER => ID */
79080    23,  /*     VACUUM => ID */
79081    23,  /*       VIEW => ID */
79082    23,  /*    VIRTUAL => ID */
79083    23,  /*    REINDEX => ID */
79084    23,  /*     RENAME => ID */
79085    23,  /*   CTIME_KW => ID */
79086     0,  /*        ANY => nothing */
79087     0,  /*         OR => nothing */
79088     0,  /*        AND => nothing */
79089     0,  /*         IS => nothing */
79090     0,  /*    BETWEEN => nothing */
79091     0,  /*         IN => nothing */
79092     0,  /*     ISNULL => nothing */
79093     0,  /*    NOTNULL => nothing */
79094     0,  /*         NE => nothing */
79095     0,  /*         EQ => nothing */
79096     0,  /*         GT => nothing */
79097     0,  /*         LE => nothing */
79098     0,  /*         LT => nothing */
79099     0,  /*         GE => nothing */
79100     0,  /*     ESCAPE => nothing */
79101     0,  /*     BITAND => nothing */
79102     0,  /*      BITOR => nothing */
79103     0,  /*     LSHIFT => nothing */
79104     0,  /*     RSHIFT => nothing */
79105     0,  /*       PLUS => nothing */
79106     0,  /*      MINUS => nothing */
79107     0,  /*       STAR => nothing */
79108     0,  /*      SLASH => nothing */
79109     0,  /*        REM => nothing */
79110     0,  /*     CONCAT => nothing */
79111     0,  /*    COLLATE => nothing */
79112     0,  /*     UMINUS => nothing */
79113     0,  /*      UPLUS => nothing */
79114     0,  /*     BITNOT => nothing */
79115     0,  /*     STRING => nothing */
79116     0,  /*    JOIN_KW => nothing */
79117     0,  /* CONSTRAINT => nothing */
79118     0,  /*    DEFAULT => nothing */
79119     0,  /*       NULL => nothing */
79120     0,  /*    PRIMARY => nothing */
79121     0,  /*     UNIQUE => nothing */
79122     0,  /*      CHECK => nothing */
79123     0,  /* REFERENCES => nothing */
79124     0,  /*   AUTOINCR => nothing */
79125     0,  /*         ON => nothing */
79126     0,  /*     DELETE => nothing */
79127     0,  /*     UPDATE => nothing */
79128     0,  /*     INSERT => nothing */
79129     0,  /*        SET => nothing */
79130     0,  /* DEFERRABLE => nothing */
79131     0,  /*    FOREIGN => nothing */
79132     0,  /*       DROP => nothing */
79133     0,  /*      UNION => nothing */
79134     0,  /*        ALL => nothing */
79135     0,  /*     EXCEPT => nothing */
79136     0,  /*  INTERSECT => nothing */
79137     0,  /*     SELECT => nothing */
79138     0,  /*   DISTINCT => nothing */
79139     0,  /*        DOT => nothing */
79140     0,  /*       FROM => nothing */
79141     0,  /*       JOIN => nothing */
79142     0,  /*      USING => nothing */
79143     0,  /*      ORDER => nothing */
79144     0,  /*         BY => nothing */
79145     0,  /*      GROUP => nothing */
79146     0,  /*     HAVING => nothing */
79147     0,  /*      LIMIT => nothing */
79148     0,  /*      WHERE => nothing */
79149     0,  /*       INTO => nothing */
79150     0,  /*     VALUES => nothing */
79151     0,  /*    INTEGER => nothing */
79152     0,  /*      FLOAT => nothing */
79153     0,  /*       BLOB => nothing */
79154     0,  /*   REGISTER => nothing */
79155     0,  /*   VARIABLE => nothing */
79156     0,  /*       CASE => nothing */
79157     0,  /*       WHEN => nothing */
79158     0,  /*       THEN => nothing */
79159     0,  /*       ELSE => nothing */
79160     0,  /*      INDEX => nothing */
79161     0,  /*      ALTER => nothing */
79162     0,  /*         TO => nothing */
79163     0,  /*        ADD => nothing */
79164     0,  /*   COLUMNKW => nothing */
79165 };
79166 #endif /* YYFALLBACK */
79167
79168 /* The following structure represents a single element of the
79169 ** parser's stack.  Information stored includes:
79170 **
79171 **   +  The state number for the parser at this level of the stack.
79172 **
79173 **   +  The value of the token stored at this level of the stack.
79174 **      (In other words, the "major" token.)
79175 **
79176 **   +  The semantic value stored at this level of the stack.  This is
79177 **      the information used by the action routines in the grammar.
79178 **      It is sometimes called the "minor" token.
79179 */
79180 struct yyStackEntry {
79181   YYACTIONTYPE stateno;  /* The state-number */
79182   YYCODETYPE major;      /* The major token value.  This is the code
79183                          ** number for the token at this stack level */
79184   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
79185                          ** is the value of the token  */
79186 };
79187 typedef struct yyStackEntry yyStackEntry;
79188
79189 /* The state of the parser is completely contained in an instance of
79190 ** the following structure */
79191 struct yyParser {
79192   int yyidx;                    /* Index of top element in stack */
79193 #ifdef YYTRACKMAXSTACKDEPTH
79194   int yyidxMax;                 /* Maximum value of yyidx */
79195 #endif
79196   int yyerrcnt;                 /* Shifts left before out of the error */
79197   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
79198 #if YYSTACKDEPTH<=0
79199   int yystksz;                  /* Current side of the stack */
79200   yyStackEntry *yystack;        /* The parser's stack */
79201 #else
79202   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
79203 #endif
79204 };
79205 typedef struct yyParser yyParser;
79206
79207 #ifndef NDEBUG
79208 static FILE *yyTraceFILE = 0;
79209 static char *yyTracePrompt = 0;
79210 #endif /* NDEBUG */
79211
79212 #ifndef NDEBUG
79213 /* 
79214 ** Turn parser tracing on by giving a stream to which to write the trace
79215 ** and a prompt to preface each trace message.  Tracing is turned off
79216 ** by making either argument NULL 
79217 **
79218 ** Inputs:
79219 ** <ul>
79220 ** <li> A FILE* to which trace output should be written.
79221 **      If NULL, then tracing is turned off.
79222 ** <li> A prefix string written at the beginning of every
79223 **      line of trace output.  If NULL, then tracing is
79224 **      turned off.
79225 ** </ul>
79226 **
79227 ** Outputs:
79228 ** None.
79229 */
79230 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
79231   yyTraceFILE = TraceFILE;
79232   yyTracePrompt = zTracePrompt;
79233   if( yyTraceFILE==0 ) yyTracePrompt = 0;
79234   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
79235 }
79236 #endif /* NDEBUG */
79237
79238 #ifndef NDEBUG
79239 /* For tracing shifts, the names of all terminals and nonterminals
79240 ** are required.  The following table supplies these names */
79241 static const char *const yyTokenName[] = { 
79242   "$",             "SEMI",          "EXPLAIN",       "QUERY",       
79243   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",    
79244   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",         
79245   "ROLLBACK",      "CREATE",        "TABLE",         "IF",          
79246   "NOT",           "EXISTS",        "TEMP",          "LP",          
79247   "RP",            "AS",            "COMMA",         "ID",          
79248   "ABORT",         "AFTER",         "ANALYZE",       "ASC",         
79249   "ATTACH",        "BEFORE",        "CASCADE",       "CAST",        
79250   "CONFLICT",      "DATABASE",      "DESC",          "DETACH",      
79251   "EACH",          "FAIL",          "FOR",           "IGNORE",      
79252   "INITIALLY",     "INSTEAD",       "LIKE_KW",       "MATCH",       
79253   "KEY",           "OF",            "OFFSET",        "PRAGMA",      
79254   "RAISE",         "REPLACE",       "RESTRICT",      "ROW",         
79255   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",     
79256   "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",         
79257   "OR",            "AND",           "IS",            "BETWEEN",     
79258   "IN",            "ISNULL",        "NOTNULL",       "NE",          
79259   "EQ",            "GT",            "LE",            "LT",          
79260   "GE",            "ESCAPE",        "BITAND",        "BITOR",       
79261   "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",       
79262   "STAR",          "SLASH",         "REM",           "CONCAT",      
79263   "COLLATE",       "UMINUS",        "UPLUS",         "BITNOT",      
79264   "STRING",        "JOIN_KW",       "CONSTRAINT",    "DEFAULT",     
79265   "NULL",          "PRIMARY",       "UNIQUE",        "CHECK",       
79266   "REFERENCES",    "AUTOINCR",      "ON",            "DELETE",      
79267   "UPDATE",        "INSERT",        "SET",           "DEFERRABLE",  
79268   "FOREIGN",       "DROP",          "UNION",         "ALL",         
79269   "EXCEPT",        "INTERSECT",     "SELECT",        "DISTINCT",    
79270   "DOT",           "FROM",          "JOIN",          "USING",       
79271   "ORDER",         "BY",            "GROUP",         "HAVING",      
79272   "LIMIT",         "WHERE",         "INTO",          "VALUES",      
79273   "INTEGER",       "FLOAT",         "BLOB",          "REGISTER",    
79274   "VARIABLE",      "CASE",          "WHEN",          "THEN",        
79275   "ELSE",          "INDEX",         "ALTER",         "TO",          
79276   "ADD",           "COLUMNKW",      "error",         "input",       
79277   "cmdlist",       "ecmd",          "explain",       "cmdx",        
79278   "cmd",           "transtype",     "trans_opt",     "nm",          
79279   "create_table",  "create_table_args",  "temp",          "ifnotexists", 
79280   "dbnm",          "columnlist",    "conslist_opt",  "select",      
79281   "column",        "columnid",      "type",          "carglist",    
79282   "id",            "ids",           "typetoken",     "typename",    
79283   "signed",        "plus_num",      "minus_num",     "carg",        
79284   "ccons",         "term",          "expr",          "onconf",      
79285   "sortorder",     "autoinc",       "idxlist_opt",   "refargs",     
79286   "defer_subclause",  "refarg",        "refact",        "init_deferred_pred_opt",
79287   "conslist",      "tcons",         "idxlist",       "defer_subclause_opt",
79288   "orconf",        "resolvetype",   "raisetype",     "ifexists",    
79289   "fullname",      "oneselect",     "multiselect_op",  "distinct",    
79290   "selcollist",    "from",          "where_opt",     "groupby_opt", 
79291   "having_opt",    "orderby_opt",   "limit_opt",     "sclp",        
79292   "as",            "seltablist",    "stl_prefix",    "joinop",      
79293   "on_opt",        "using_opt",     "seltablist_paren",  "joinop2",     
79294   "inscollist",    "sortlist",      "sortitem",      "nexprlist",   
79295   "setlist",       "insert_cmd",    "inscollist_opt",  "itemlist",    
79296   "exprlist",      "likeop",        "escape",        "between_op",  
79297   "in_op",         "case_operand",  "case_exprlist",  "case_else",   
79298   "uniqueflag",    "collate",       "nmnum",         "plus_opt",    
79299   "number",        "trigger_decl",  "trigger_cmd_list",  "trigger_time",
79300   "trigger_event",  "foreach_clause",  "when_clause",   "trigger_cmd", 
79301   "database_kw_opt",  "key_opt",       "add_column_fullname",  "kwcolumn_opt",
79302   "create_vtab",   "vtabarglist",   "vtabarg",       "vtabargtoken",
79303   "lp",            "anylist",     
79304 };
79305 #endif /* NDEBUG */
79306
79307 #ifndef NDEBUG
79308 /* For tracing reduce actions, the names of all rules are required.
79309 */
79310 static const char *const yyRuleName[] = {
79311  /*   0 */ "input ::= cmdlist",
79312  /*   1 */ "cmdlist ::= cmdlist ecmd",
79313  /*   2 */ "cmdlist ::= ecmd",
79314  /*   3 */ "ecmd ::= SEMI",
79315  /*   4 */ "ecmd ::= explain cmdx SEMI",
79316  /*   5 */ "explain ::=",
79317  /*   6 */ "explain ::= EXPLAIN",
79318  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
79319  /*   8 */ "cmdx ::= cmd",
79320  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
79321  /*  10 */ "trans_opt ::=",
79322  /*  11 */ "trans_opt ::= TRANSACTION",
79323  /*  12 */ "trans_opt ::= TRANSACTION nm",
79324  /*  13 */ "transtype ::=",
79325  /*  14 */ "transtype ::= DEFERRED",
79326  /*  15 */ "transtype ::= IMMEDIATE",
79327  /*  16 */ "transtype ::= EXCLUSIVE",
79328  /*  17 */ "cmd ::= COMMIT trans_opt",
79329  /*  18 */ "cmd ::= END trans_opt",
79330  /*  19 */ "cmd ::= ROLLBACK trans_opt",
79331  /*  20 */ "cmd ::= create_table create_table_args",
79332  /*  21 */ "create_table ::= CREATE temp TABLE ifnotexists nm dbnm",
79333  /*  22 */ "ifnotexists ::=",
79334  /*  23 */ "ifnotexists ::= IF NOT EXISTS",
79335  /*  24 */ "temp ::= TEMP",
79336  /*  25 */ "temp ::=",
79337  /*  26 */ "create_table_args ::= LP columnlist conslist_opt RP",
79338  /*  27 */ "create_table_args ::= AS select",
79339  /*  28 */ "columnlist ::= columnlist COMMA column",
79340  /*  29 */ "columnlist ::= column",
79341  /*  30 */ "column ::= columnid type carglist",
79342  /*  31 */ "columnid ::= nm",
79343  /*  32 */ "id ::= ID",
79344  /*  33 */ "ids ::= ID|STRING",
79345  /*  34 */ "nm ::= ID",
79346  /*  35 */ "nm ::= STRING",
79347  /*  36 */ "nm ::= JOIN_KW",
79348  /*  37 */ "type ::=",
79349  /*  38 */ "type ::= typetoken",
79350  /*  39 */ "typetoken ::= typename",
79351  /*  40 */ "typetoken ::= typename LP signed RP",
79352  /*  41 */ "typetoken ::= typename LP signed COMMA signed RP",
79353  /*  42 */ "typename ::= ids",
79354  /*  43 */ "typename ::= typename ids",
79355  /*  44 */ "signed ::= plus_num",
79356  /*  45 */ "signed ::= minus_num",
79357  /*  46 */ "carglist ::= carglist carg",
79358  /*  47 */ "carglist ::=",
79359  /*  48 */ "carg ::= CONSTRAINT nm ccons",
79360  /*  49 */ "carg ::= ccons",
79361  /*  50 */ "ccons ::= DEFAULT term",
79362  /*  51 */ "ccons ::= DEFAULT LP expr RP",
79363  /*  52 */ "ccons ::= DEFAULT PLUS term",
79364  /*  53 */ "ccons ::= DEFAULT MINUS term",
79365  /*  54 */ "ccons ::= DEFAULT id",
79366  /*  55 */ "ccons ::= NULL onconf",
79367  /*  56 */ "ccons ::= NOT NULL onconf",
79368  /*  57 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
79369  /*  58 */ "ccons ::= UNIQUE onconf",
79370  /*  59 */ "ccons ::= CHECK LP expr RP",
79371  /*  60 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
79372  /*  61 */ "ccons ::= defer_subclause",
79373  /*  62 */ "ccons ::= COLLATE ids",
79374  /*  63 */ "autoinc ::=",
79375  /*  64 */ "autoinc ::= AUTOINCR",
79376  /*  65 */ "refargs ::=",
79377  /*  66 */ "refargs ::= refargs refarg",
79378  /*  67 */ "refarg ::= MATCH nm",
79379  /*  68 */ "refarg ::= ON DELETE refact",
79380  /*  69 */ "refarg ::= ON UPDATE refact",
79381  /*  70 */ "refarg ::= ON INSERT refact",
79382  /*  71 */ "refact ::= SET NULL",
79383  /*  72 */ "refact ::= SET DEFAULT",
79384  /*  73 */ "refact ::= CASCADE",
79385  /*  74 */ "refact ::= RESTRICT",
79386  /*  75 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
79387  /*  76 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
79388  /*  77 */ "init_deferred_pred_opt ::=",
79389  /*  78 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
79390  /*  79 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
79391  /*  80 */ "conslist_opt ::=",
79392  /*  81 */ "conslist_opt ::= COMMA conslist",
79393  /*  82 */ "conslist ::= conslist COMMA tcons",
79394  /*  83 */ "conslist ::= conslist tcons",
79395  /*  84 */ "conslist ::= tcons",
79396  /*  85 */ "tcons ::= CONSTRAINT nm",
79397  /*  86 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
79398  /*  87 */ "tcons ::= UNIQUE LP idxlist RP onconf",
79399  /*  88 */ "tcons ::= CHECK LP expr RP onconf",
79400  /*  89 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
79401  /*  90 */ "defer_subclause_opt ::=",
79402  /*  91 */ "defer_subclause_opt ::= defer_subclause",
79403  /*  92 */ "onconf ::=",
79404  /*  93 */ "onconf ::= ON CONFLICT resolvetype",
79405  /*  94 */ "orconf ::=",
79406  /*  95 */ "orconf ::= OR resolvetype",
79407  /*  96 */ "resolvetype ::= raisetype",
79408  /*  97 */ "resolvetype ::= IGNORE",
79409  /*  98 */ "resolvetype ::= REPLACE",
79410  /*  99 */ "cmd ::= DROP TABLE ifexists fullname",
79411  /* 100 */ "ifexists ::= IF EXISTS",
79412  /* 101 */ "ifexists ::=",
79413  /* 102 */ "cmd ::= CREATE temp VIEW ifnotexists nm dbnm AS select",
79414  /* 103 */ "cmd ::= DROP VIEW ifexists fullname",
79415  /* 104 */ "cmd ::= select",
79416  /* 105 */ "select ::= oneselect",
79417  /* 106 */ "select ::= select multiselect_op oneselect",
79418  /* 107 */ "multiselect_op ::= UNION",
79419  /* 108 */ "multiselect_op ::= UNION ALL",
79420  /* 109 */ "multiselect_op ::= EXCEPT|INTERSECT",
79421  /* 110 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
79422  /* 111 */ "distinct ::= DISTINCT",
79423  /* 112 */ "distinct ::= ALL",
79424  /* 113 */ "distinct ::=",
79425  /* 114 */ "sclp ::= selcollist COMMA",
79426  /* 115 */ "sclp ::=",
79427  /* 116 */ "selcollist ::= sclp expr as",
79428  /* 117 */ "selcollist ::= sclp STAR",
79429  /* 118 */ "selcollist ::= sclp nm DOT STAR",
79430  /* 119 */ "as ::= AS nm",
79431  /* 120 */ "as ::= ids",
79432  /* 121 */ "as ::=",
79433  /* 122 */ "from ::=",
79434  /* 123 */ "from ::= FROM seltablist",
79435  /* 124 */ "stl_prefix ::= seltablist joinop",
79436  /* 125 */ "stl_prefix ::=",
79437  /* 126 */ "seltablist ::= stl_prefix nm dbnm as on_opt using_opt",
79438  /* 127 */ "seltablist ::= stl_prefix LP seltablist_paren RP as on_opt using_opt",
79439  /* 128 */ "seltablist_paren ::= select",
79440  /* 129 */ "seltablist_paren ::= seltablist",
79441  /* 130 */ "dbnm ::=",
79442  /* 131 */ "dbnm ::= DOT nm",
79443  /* 132 */ "fullname ::= nm dbnm",
79444  /* 133 */ "joinop ::= COMMA|JOIN",
79445  /* 134 */ "joinop ::= JOIN_KW JOIN",
79446  /* 135 */ "joinop ::= JOIN_KW nm JOIN",
79447  /* 136 */ "joinop ::= JOIN_KW nm nm JOIN",
79448  /* 137 */ "on_opt ::= ON expr",
79449  /* 138 */ "on_opt ::=",
79450  /* 139 */ "using_opt ::= USING LP inscollist RP",
79451  /* 140 */ "using_opt ::=",
79452  /* 141 */ "orderby_opt ::=",
79453  /* 142 */ "orderby_opt ::= ORDER BY sortlist",
79454  /* 143 */ "sortlist ::= sortlist COMMA sortitem sortorder",
79455  /* 144 */ "sortlist ::= sortitem sortorder",
79456  /* 145 */ "sortitem ::= expr",
79457  /* 146 */ "sortorder ::= ASC",
79458  /* 147 */ "sortorder ::= DESC",
79459  /* 148 */ "sortorder ::=",
79460  /* 149 */ "groupby_opt ::=",
79461  /* 150 */ "groupby_opt ::= GROUP BY nexprlist",
79462  /* 151 */ "having_opt ::=",
79463  /* 152 */ "having_opt ::= HAVING expr",
79464  /* 153 */ "limit_opt ::=",
79465  /* 154 */ "limit_opt ::= LIMIT expr",
79466  /* 155 */ "limit_opt ::= LIMIT expr OFFSET expr",
79467  /* 156 */ "limit_opt ::= LIMIT expr COMMA expr",
79468  /* 157 */ "cmd ::= DELETE FROM fullname where_opt",
79469  /* 158 */ "where_opt ::=",
79470  /* 159 */ "where_opt ::= WHERE expr",
79471  /* 160 */ "cmd ::= UPDATE orconf fullname SET setlist where_opt",
79472  /* 161 */ "setlist ::= setlist COMMA nm EQ expr",
79473  /* 162 */ "setlist ::= nm EQ expr",
79474  /* 163 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
79475  /* 164 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
79476  /* 165 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
79477  /* 166 */ "insert_cmd ::= INSERT orconf",
79478  /* 167 */ "insert_cmd ::= REPLACE",
79479  /* 168 */ "itemlist ::= itemlist COMMA expr",
79480  /* 169 */ "itemlist ::= expr",
79481  /* 170 */ "inscollist_opt ::=",
79482  /* 171 */ "inscollist_opt ::= LP inscollist RP",
79483  /* 172 */ "inscollist ::= inscollist COMMA nm",
79484  /* 173 */ "inscollist ::= nm",
79485  /* 174 */ "expr ::= term",
79486  /* 175 */ "expr ::= LP expr RP",
79487  /* 176 */ "term ::= NULL",
79488  /* 177 */ "expr ::= ID",
79489  /* 178 */ "expr ::= JOIN_KW",
79490  /* 179 */ "expr ::= nm DOT nm",
79491  /* 180 */ "expr ::= nm DOT nm DOT nm",
79492  /* 181 */ "term ::= INTEGER|FLOAT|BLOB",
79493  /* 182 */ "term ::= STRING",
79494  /* 183 */ "expr ::= REGISTER",
79495  /* 184 */ "expr ::= VARIABLE",
79496  /* 185 */ "expr ::= expr COLLATE ids",
79497  /* 186 */ "expr ::= CAST LP expr AS typetoken RP",
79498  /* 187 */ "expr ::= ID LP distinct exprlist RP",
79499  /* 188 */ "expr ::= ID LP STAR RP",
79500  /* 189 */ "term ::= CTIME_KW",
79501  /* 190 */ "expr ::= expr AND expr",
79502  /* 191 */ "expr ::= expr OR expr",
79503  /* 192 */ "expr ::= expr LT|GT|GE|LE expr",
79504  /* 193 */ "expr ::= expr EQ|NE expr",
79505  /* 194 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
79506  /* 195 */ "expr ::= expr PLUS|MINUS expr",
79507  /* 196 */ "expr ::= expr STAR|SLASH|REM expr",
79508  /* 197 */ "expr ::= expr CONCAT expr",
79509  /* 198 */ "likeop ::= LIKE_KW",
79510  /* 199 */ "likeop ::= NOT LIKE_KW",
79511  /* 200 */ "likeop ::= MATCH",
79512  /* 201 */ "likeop ::= NOT MATCH",
79513  /* 202 */ "escape ::= ESCAPE expr",
79514  /* 203 */ "escape ::=",
79515  /* 204 */ "expr ::= expr likeop expr escape",
79516  /* 205 */ "expr ::= expr ISNULL|NOTNULL",
79517  /* 206 */ "expr ::= expr IS NULL",
79518  /* 207 */ "expr ::= expr NOT NULL",
79519  /* 208 */ "expr ::= expr IS NOT NULL",
79520  /* 209 */ "expr ::= NOT expr",
79521  /* 210 */ "expr ::= BITNOT expr",
79522  /* 211 */ "expr ::= MINUS expr",
79523  /* 212 */ "expr ::= PLUS expr",
79524  /* 213 */ "between_op ::= BETWEEN",
79525  /* 214 */ "between_op ::= NOT BETWEEN",
79526  /* 215 */ "expr ::= expr between_op expr AND expr",
79527  /* 216 */ "in_op ::= IN",
79528  /* 217 */ "in_op ::= NOT IN",
79529  /* 218 */ "expr ::= expr in_op LP exprlist RP",
79530  /* 219 */ "expr ::= LP select RP",
79531  /* 220 */ "expr ::= expr in_op LP select RP",
79532  /* 221 */ "expr ::= expr in_op nm dbnm",
79533  /* 222 */ "expr ::= EXISTS LP select RP",
79534  /* 223 */ "expr ::= CASE case_operand case_exprlist case_else END",
79535  /* 224 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
79536  /* 225 */ "case_exprlist ::= WHEN expr THEN expr",
79537  /* 226 */ "case_else ::= ELSE expr",
79538  /* 227 */ "case_else ::=",
79539  /* 228 */ "case_operand ::= expr",
79540  /* 229 */ "case_operand ::=",
79541  /* 230 */ "exprlist ::= nexprlist",
79542  /* 231 */ "exprlist ::=",
79543  /* 232 */ "nexprlist ::= nexprlist COMMA expr",
79544  /* 233 */ "nexprlist ::= expr",
79545  /* 234 */ "cmd ::= CREATE uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
79546  /* 235 */ "uniqueflag ::= UNIQUE",
79547  /* 236 */ "uniqueflag ::=",
79548  /* 237 */ "idxlist_opt ::=",
79549  /* 238 */ "idxlist_opt ::= LP idxlist RP",
79550  /* 239 */ "idxlist ::= idxlist COMMA nm collate sortorder",
79551  /* 240 */ "idxlist ::= nm collate sortorder",
79552  /* 241 */ "collate ::=",
79553  /* 242 */ "collate ::= COLLATE ids",
79554  /* 243 */ "cmd ::= DROP INDEX ifexists fullname",
79555  /* 244 */ "cmd ::= VACUUM",
79556  /* 245 */ "cmd ::= VACUUM nm",
79557  /* 246 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
79558  /* 247 */ "cmd ::= PRAGMA nm dbnm EQ ON",
79559  /* 248 */ "cmd ::= PRAGMA nm dbnm EQ DELETE",
79560  /* 249 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
79561  /* 250 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
79562  /* 251 */ "cmd ::= PRAGMA nm dbnm",
79563  /* 252 */ "nmnum ::= plus_num",
79564  /* 253 */ "nmnum ::= nm",
79565  /* 254 */ "plus_num ::= plus_opt number",
79566  /* 255 */ "minus_num ::= MINUS number",
79567  /* 256 */ "number ::= INTEGER|FLOAT",
79568  /* 257 */ "plus_opt ::= PLUS",
79569  /* 258 */ "plus_opt ::=",
79570  /* 259 */ "cmd ::= CREATE trigger_decl BEGIN trigger_cmd_list END",
79571  /* 260 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
79572  /* 261 */ "trigger_time ::= BEFORE",
79573  /* 262 */ "trigger_time ::= AFTER",
79574  /* 263 */ "trigger_time ::= INSTEAD OF",
79575  /* 264 */ "trigger_time ::=",
79576  /* 265 */ "trigger_event ::= DELETE|INSERT",
79577  /* 266 */ "trigger_event ::= UPDATE",
79578  /* 267 */ "trigger_event ::= UPDATE OF inscollist",
79579  /* 268 */ "foreach_clause ::=",
79580  /* 269 */ "foreach_clause ::= FOR EACH ROW",
79581  /* 270 */ "when_clause ::=",
79582  /* 271 */ "when_clause ::= WHEN expr",
79583  /* 272 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
79584  /* 273 */ "trigger_cmd_list ::= trigger_cmd SEMI",
79585  /* 274 */ "trigger_cmd ::= UPDATE orconf nm SET setlist where_opt",
79586  /* 275 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP",
79587  /* 276 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt select",
79588  /* 277 */ "trigger_cmd ::= DELETE FROM nm where_opt",
79589  /* 278 */ "trigger_cmd ::= select",
79590  /* 279 */ "expr ::= RAISE LP IGNORE RP",
79591  /* 280 */ "expr ::= RAISE LP raisetype COMMA nm RP",
79592  /* 281 */ "raisetype ::= ROLLBACK",
79593  /* 282 */ "raisetype ::= ABORT",
79594  /* 283 */ "raisetype ::= FAIL",
79595  /* 284 */ "cmd ::= DROP TRIGGER ifexists fullname",
79596  /* 285 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
79597  /* 286 */ "cmd ::= DETACH database_kw_opt expr",
79598  /* 287 */ "key_opt ::=",
79599  /* 288 */ "key_opt ::= KEY expr",
79600  /* 289 */ "database_kw_opt ::= DATABASE",
79601  /* 290 */ "database_kw_opt ::=",
79602  /* 291 */ "cmd ::= REINDEX",
79603  /* 292 */ "cmd ::= REINDEX nm dbnm",
79604  /* 293 */ "cmd ::= ANALYZE",
79605  /* 294 */ "cmd ::= ANALYZE nm dbnm",
79606  /* 295 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
79607  /* 296 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
79608  /* 297 */ "add_column_fullname ::= fullname",
79609  /* 298 */ "kwcolumn_opt ::=",
79610  /* 299 */ "kwcolumn_opt ::= COLUMNKW",
79611  /* 300 */ "cmd ::= create_vtab",
79612  /* 301 */ "cmd ::= create_vtab LP vtabarglist RP",
79613  /* 302 */ "create_vtab ::= CREATE VIRTUAL TABLE nm dbnm USING nm",
79614  /* 303 */ "vtabarglist ::= vtabarg",
79615  /* 304 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
79616  /* 305 */ "vtabarg ::=",
79617  /* 306 */ "vtabarg ::= vtabarg vtabargtoken",
79618  /* 307 */ "vtabargtoken ::= ANY",
79619  /* 308 */ "vtabargtoken ::= lp anylist RP",
79620  /* 309 */ "lp ::= LP",
79621  /* 310 */ "anylist ::=",
79622  /* 311 */ "anylist ::= anylist ANY",
79623 };
79624 #endif /* NDEBUG */
79625
79626
79627 #if YYSTACKDEPTH<=0
79628 /*
79629 ** Try to increase the size of the parser stack.
79630 */
79631 static void yyGrowStack(yyParser *p){
79632   int newSize;
79633   yyStackEntry *pNew;
79634
79635   newSize = p->yystksz*2 + 100;
79636   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
79637   if( pNew ){
79638     p->yystack = pNew;
79639     p->yystksz = newSize;
79640 #ifndef NDEBUG
79641     if( yyTraceFILE ){
79642       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
79643               yyTracePrompt, p->yystksz);
79644     }
79645 #endif
79646   }
79647 }
79648 #endif
79649
79650 /* 
79651 ** This function allocates a new parser.
79652 ** The only argument is a pointer to a function which works like
79653 ** malloc.
79654 **
79655 ** Inputs:
79656 ** A pointer to the function used to allocate memory.
79657 **
79658 ** Outputs:
79659 ** A pointer to a parser.  This pointer is used in subsequent calls
79660 ** to sqlite3Parser and sqlite3ParserFree.
79661 */
79662 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
79663   yyParser *pParser;
79664   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
79665   if( pParser ){
79666     pParser->yyidx = -1;
79667 #ifdef YYTRACKMAXSTACKDEPTH
79668     pParser->yyidxMax = 0;
79669 #endif
79670 #if YYSTACKDEPTH<=0
79671     yyGrowStack(pParser);
79672 #endif
79673   }
79674   return pParser;
79675 }
79676
79677 /* The following function deletes the value associated with a
79678 ** symbol.  The symbol can be either a terminal or nonterminal.
79679 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
79680 ** the value.
79681 */
79682 static void yy_destructor(
79683   yyParser *yypParser,    /* The parser */
79684   YYCODETYPE yymajor,     /* Type code for object to destroy */
79685   YYMINORTYPE *yypminor   /* The object to be destroyed */
79686 ){
79687   sqlite3ParserARG_FETCH;
79688   switch( yymajor ){
79689     /* Here is inserted the actions which take place when a
79690     ** terminal or non-terminal is destroyed.  This can happen
79691     ** when the symbol is popped from the stack during a
79692     ** reduce or during error processing or when a parser is 
79693     ** being destroyed before it is finished parsing.
79694     **
79695     ** Note: during a reduce, the only symbols destroyed are those
79696     ** which appear on the RHS of the rule, but which are not used
79697     ** inside the C code.
79698     */
79699     case 155: /* select */
79700     case 189: /* oneselect */
79701     case 206: /* seltablist_paren */
79702 {
79703 sqlite3SelectDelete(pParse->db, (yypminor->yy375));
79704 }
79705       break;
79706     case 169: /* term */
79707     case 170: /* expr */
79708     case 194: /* where_opt */
79709     case 196: /* having_opt */
79710     case 204: /* on_opt */
79711     case 210: /* sortitem */
79712     case 218: /* escape */
79713     case 221: /* case_operand */
79714     case 223: /* case_else */
79715     case 234: /* when_clause */
79716     case 237: /* key_opt */
79717 {
79718 sqlite3ExprDelete(pParse->db, (yypminor->yy62));
79719 }
79720       break;
79721     case 174: /* idxlist_opt */
79722     case 182: /* idxlist */
79723     case 192: /* selcollist */
79724     case 195: /* groupby_opt */
79725     case 197: /* orderby_opt */
79726     case 199: /* sclp */
79727     case 209: /* sortlist */
79728     case 211: /* nexprlist */
79729     case 212: /* setlist */
79730     case 215: /* itemlist */
79731     case 216: /* exprlist */
79732     case 222: /* case_exprlist */
79733 {
79734 sqlite3ExprListDelete(pParse->db, (yypminor->yy418));
79735 }
79736       break;
79737     case 188: /* fullname */
79738     case 193: /* from */
79739     case 201: /* seltablist */
79740     case 202: /* stl_prefix */
79741 {
79742 sqlite3SrcListDelete(pParse->db, (yypminor->yy151));
79743 }
79744       break;
79745     case 205: /* using_opt */
79746     case 208: /* inscollist */
79747     case 214: /* inscollist_opt */
79748 {
79749 sqlite3IdListDelete(pParse->db, (yypminor->yy240));
79750 }
79751       break;
79752     case 230: /* trigger_cmd_list */
79753     case 235: /* trigger_cmd */
79754 {
79755 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy360));
79756 }
79757       break;
79758     case 232: /* trigger_event */
79759 {
79760 sqlite3IdListDelete(pParse->db, (yypminor->yy30).b);
79761 }
79762       break;
79763     default:  break;   /* If no destructor action specified: do nothing */
79764   }
79765 }
79766
79767 /*
79768 ** Pop the parser's stack once.
79769 **
79770 ** If there is a destructor routine associated with the token which
79771 ** is popped from the stack, then call it.
79772 **
79773 ** Return the major token number for the symbol popped.
79774 */
79775 static int yy_pop_parser_stack(yyParser *pParser){
79776   YYCODETYPE yymajor;
79777   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
79778
79779   if( pParser->yyidx<0 ) return 0;
79780 #ifndef NDEBUG
79781   if( yyTraceFILE && pParser->yyidx>=0 ){
79782     fprintf(yyTraceFILE,"%sPopping %s\n",
79783       yyTracePrompt,
79784       yyTokenName[yytos->major]);
79785   }
79786 #endif
79787   yymajor = yytos->major;
79788   yy_destructor(pParser, yymajor, &yytos->minor);
79789   pParser->yyidx--;
79790   return yymajor;
79791 }
79792
79793 /* 
79794 ** Deallocate and destroy a parser.  Destructors are all called for
79795 ** all stack elements before shutting the parser down.
79796 **
79797 ** Inputs:
79798 ** <ul>
79799 ** <li>  A pointer to the parser.  This should be a pointer
79800 **       obtained from sqlite3ParserAlloc.
79801 ** <li>  A pointer to a function used to reclaim memory obtained
79802 **       from malloc.
79803 ** </ul>
79804 */
79805 SQLITE_PRIVATE void sqlite3ParserFree(
79806   void *p,                    /* The parser to be deleted */
79807   void (*freeProc)(void*)     /* Function used to reclaim memory */
79808 ){
79809   yyParser *pParser = (yyParser*)p;
79810   if( pParser==0 ) return;
79811   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
79812 #if YYSTACKDEPTH<=0
79813   free(pParser->yystack);
79814 #endif
79815   (*freeProc)((void*)pParser);
79816 }
79817
79818 /*
79819 ** Return the peak depth of the stack for a parser.
79820 */
79821 #ifdef YYTRACKMAXSTACKDEPTH
79822 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
79823   yyParser *pParser = (yyParser*)p;
79824   return pParser->yyidxMax;
79825 }
79826 #endif
79827
79828 /*
79829 ** Find the appropriate action for a parser given the terminal
79830 ** look-ahead token iLookAhead.
79831 **
79832 ** If the look-ahead token is YYNOCODE, then check to see if the action is
79833 ** independent of the look-ahead.  If it is, return the action, otherwise
79834 ** return YY_NO_ACTION.
79835 */
79836 static int yy_find_shift_action(
79837   yyParser *pParser,        /* The parser */
79838   YYCODETYPE iLookAhead     /* The look-ahead token */
79839 ){
79840   int i;
79841   int stateno = pParser->yystack[pParser->yyidx].stateno;
79842  
79843   if( stateno>YY_SHIFT_MAX || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
79844     return yy_default[stateno];
79845   }
79846   assert( iLookAhead!=YYNOCODE );
79847   i += iLookAhead;
79848   if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){
79849     if( iLookAhead>0 ){
79850 #ifdef YYFALLBACK
79851       int iFallback;            /* Fallback token */
79852       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
79853              && (iFallback = yyFallback[iLookAhead])!=0 ){
79854 #ifndef NDEBUG
79855         if( yyTraceFILE ){
79856           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
79857              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
79858         }
79859 #endif
79860         return yy_find_shift_action(pParser, iFallback);
79861       }
79862 #endif
79863 #ifdef YYWILDCARD
79864       {
79865         int j = i - iLookAhead + YYWILDCARD;
79866         if( j>=0 && j<YY_SZ_ACTTAB && yy_lookahead[j]==YYWILDCARD ){
79867 #ifndef NDEBUG
79868           if( yyTraceFILE ){
79869             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
79870                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
79871           }
79872 #endif /* NDEBUG */
79873           return yy_action[j];
79874         }
79875       }
79876 #endif /* YYWILDCARD */
79877     }
79878     return yy_default[stateno];
79879   }else{
79880     return yy_action[i];
79881   }
79882 }
79883
79884 /*
79885 ** Find the appropriate action for a parser given the non-terminal
79886 ** look-ahead token iLookAhead.
79887 **
79888 ** If the look-ahead token is YYNOCODE, then check to see if the action is
79889 ** independent of the look-ahead.  If it is, return the action, otherwise
79890 ** return YY_NO_ACTION.
79891 */
79892 static int yy_find_reduce_action(
79893   int stateno,              /* Current state number */
79894   YYCODETYPE iLookAhead     /* The look-ahead token */
79895 ){
79896   int i;
79897 #ifdef YYERRORSYMBOL
79898   if( stateno>YY_REDUCE_MAX ){
79899     return yy_default[stateno];
79900   }
79901 #else
79902   assert( stateno<=YY_REDUCE_MAX );
79903 #endif
79904   i = yy_reduce_ofst[stateno];
79905   assert( i!=YY_REDUCE_USE_DFLT );
79906   assert( iLookAhead!=YYNOCODE );
79907   i += iLookAhead;
79908 #ifdef YYERRORSYMBOL
79909   if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){
79910     return yy_default[stateno];
79911   }
79912 #else
79913   assert( i>=0 && i<YY_SZ_ACTTAB );
79914   assert( yy_lookahead[i]==iLookAhead );
79915 #endif
79916   return yy_action[i];
79917 }
79918
79919 /*
79920 ** The following routine is called if the stack overflows.
79921 */
79922 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
79923    sqlite3ParserARG_FETCH;
79924    yypParser->yyidx--;
79925 #ifndef NDEBUG
79926    if( yyTraceFILE ){
79927      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
79928    }
79929 #endif
79930    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
79931    /* Here code is inserted which will execute if the parser
79932    ** stack every overflows */
79933
79934   sqlite3ErrorMsg(pParse, "parser stack overflow");
79935   pParse->parseError = 1;
79936    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
79937 }
79938
79939 /*
79940 ** Perform a shift action.
79941 */
79942 static void yy_shift(
79943   yyParser *yypParser,          /* The parser to be shifted */
79944   int yyNewState,               /* The new state to shift in */
79945   int yyMajor,                  /* The major token to shift in */
79946   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
79947 ){
79948   yyStackEntry *yytos;
79949   yypParser->yyidx++;
79950 #ifdef YYTRACKMAXSTACKDEPTH
79951   if( yypParser->yyidx>yypParser->yyidxMax ){
79952     yypParser->yyidxMax = yypParser->yyidx;
79953   }
79954 #endif
79955 #if YYSTACKDEPTH>0 
79956   if( yypParser->yyidx>=YYSTACKDEPTH ){
79957     yyStackOverflow(yypParser, yypMinor);
79958     return;
79959   }
79960 #else
79961   if( yypParser->yyidx>=yypParser->yystksz ){
79962     yyGrowStack(yypParser);
79963     if( yypParser->yyidx>=yypParser->yystksz ){
79964       yyStackOverflow(yypParser, yypMinor);
79965       return;
79966     }
79967   }
79968 #endif
79969   yytos = &yypParser->yystack[yypParser->yyidx];
79970   yytos->stateno = yyNewState;
79971   yytos->major = yyMajor;
79972   yytos->minor = *yypMinor;
79973 #ifndef NDEBUG
79974   if( yyTraceFILE && yypParser->yyidx>0 ){
79975     int i;
79976     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
79977     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
79978     for(i=1; i<=yypParser->yyidx; i++)
79979       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
79980     fprintf(yyTraceFILE,"\n");
79981   }
79982 #endif
79983 }
79984
79985 /* The following table contains information about every rule that
79986 ** is used during the reduce.
79987 */
79988 static const struct {
79989   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
79990   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
79991 } yyRuleInfo[] = {
79992   { 139, 1 },
79993   { 140, 2 },
79994   { 140, 1 },
79995   { 141, 1 },
79996   { 141, 3 },
79997   { 142, 0 },
79998   { 142, 1 },
79999   { 142, 3 },
80000   { 143, 1 },
80001   { 144, 3 },
80002   { 146, 0 },
80003   { 146, 1 },
80004   { 146, 2 },
80005   { 145, 0 },
80006   { 145, 1 },
80007   { 145, 1 },
80008   { 145, 1 },
80009   { 144, 2 },
80010   { 144, 2 },
80011   { 144, 2 },
80012   { 144, 2 },
80013   { 148, 6 },
80014   { 151, 0 },
80015   { 151, 3 },
80016   { 150, 1 },
80017   { 150, 0 },
80018   { 149, 4 },
80019   { 149, 2 },
80020   { 153, 3 },
80021   { 153, 1 },
80022   { 156, 3 },
80023   { 157, 1 },
80024   { 160, 1 },
80025   { 161, 1 },
80026   { 147, 1 },
80027   { 147, 1 },
80028   { 147, 1 },
80029   { 158, 0 },
80030   { 158, 1 },
80031   { 162, 1 },
80032   { 162, 4 },
80033   { 162, 6 },
80034   { 163, 1 },
80035   { 163, 2 },
80036   { 164, 1 },
80037   { 164, 1 },
80038   { 159, 2 },
80039   { 159, 0 },
80040   { 167, 3 },
80041   { 167, 1 },
80042   { 168, 2 },
80043   { 168, 4 },
80044   { 168, 3 },
80045   { 168, 3 },
80046   { 168, 2 },
80047   { 168, 2 },
80048   { 168, 3 },
80049   { 168, 5 },
80050   { 168, 2 },
80051   { 168, 4 },
80052   { 168, 4 },
80053   { 168, 1 },
80054   { 168, 2 },
80055   { 173, 0 },
80056   { 173, 1 },
80057   { 175, 0 },
80058   { 175, 2 },
80059   { 177, 2 },
80060   { 177, 3 },
80061   { 177, 3 },
80062   { 177, 3 },
80063   { 178, 2 },
80064   { 178, 2 },
80065   { 178, 1 },
80066   { 178, 1 },
80067   { 176, 3 },
80068   { 176, 2 },
80069   { 179, 0 },
80070   { 179, 2 },
80071   { 179, 2 },
80072   { 154, 0 },
80073   { 154, 2 },
80074   { 180, 3 },
80075   { 180, 2 },
80076   { 180, 1 },
80077   { 181, 2 },
80078   { 181, 7 },
80079   { 181, 5 },
80080   { 181, 5 },
80081   { 181, 10 },
80082   { 183, 0 },
80083   { 183, 1 },
80084   { 171, 0 },
80085   { 171, 3 },
80086   { 184, 0 },
80087   { 184, 2 },
80088   { 185, 1 },
80089   { 185, 1 },
80090   { 185, 1 },
80091   { 144, 4 },
80092   { 187, 2 },
80093   { 187, 0 },
80094   { 144, 8 },
80095   { 144, 4 },
80096   { 144, 1 },
80097   { 155, 1 },
80098   { 155, 3 },
80099   { 190, 1 },
80100   { 190, 2 },
80101   { 190, 1 },
80102   { 189, 9 },
80103   { 191, 1 },
80104   { 191, 1 },
80105   { 191, 0 },
80106   { 199, 2 },
80107   { 199, 0 },
80108   { 192, 3 },
80109   { 192, 2 },
80110   { 192, 4 },
80111   { 200, 2 },
80112   { 200, 1 },
80113   { 200, 0 },
80114   { 193, 0 },
80115   { 193, 2 },
80116   { 202, 2 },
80117   { 202, 0 },
80118   { 201, 6 },
80119   { 201, 7 },
80120   { 206, 1 },
80121   { 206, 1 },
80122   { 152, 0 },
80123   { 152, 2 },
80124   { 188, 2 },
80125   { 203, 1 },
80126   { 203, 2 },
80127   { 203, 3 },
80128   { 203, 4 },
80129   { 204, 2 },
80130   { 204, 0 },
80131   { 205, 4 },
80132   { 205, 0 },
80133   { 197, 0 },
80134   { 197, 3 },
80135   { 209, 4 },
80136   { 209, 2 },
80137   { 210, 1 },
80138   { 172, 1 },
80139   { 172, 1 },
80140   { 172, 0 },
80141   { 195, 0 },
80142   { 195, 3 },
80143   { 196, 0 },
80144   { 196, 2 },
80145   { 198, 0 },
80146   { 198, 2 },
80147   { 198, 4 },
80148   { 198, 4 },
80149   { 144, 4 },
80150   { 194, 0 },
80151   { 194, 2 },
80152   { 144, 6 },
80153   { 212, 5 },
80154   { 212, 3 },
80155   { 144, 8 },
80156   { 144, 5 },
80157   { 144, 6 },
80158   { 213, 2 },
80159   { 213, 1 },
80160   { 215, 3 },
80161   { 215, 1 },
80162   { 214, 0 },
80163   { 214, 3 },
80164   { 208, 3 },
80165   { 208, 1 },
80166   { 170, 1 },
80167   { 170, 3 },
80168   { 169, 1 },
80169   { 170, 1 },
80170   { 170, 1 },
80171   { 170, 3 },
80172   { 170, 5 },
80173   { 169, 1 },
80174   { 169, 1 },
80175   { 170, 1 },
80176   { 170, 1 },
80177   { 170, 3 },
80178   { 170, 6 },
80179   { 170, 5 },
80180   { 170, 4 },
80181   { 169, 1 },
80182   { 170, 3 },
80183   { 170, 3 },
80184   { 170, 3 },
80185   { 170, 3 },
80186   { 170, 3 },
80187   { 170, 3 },
80188   { 170, 3 },
80189   { 170, 3 },
80190   { 217, 1 },
80191   { 217, 2 },
80192   { 217, 1 },
80193   { 217, 2 },
80194   { 218, 2 },
80195   { 218, 0 },
80196   { 170, 4 },
80197   { 170, 2 },
80198   { 170, 3 },
80199   { 170, 3 },
80200   { 170, 4 },
80201   { 170, 2 },
80202   { 170, 2 },
80203   { 170, 2 },
80204   { 170, 2 },
80205   { 219, 1 },
80206   { 219, 2 },
80207   { 170, 5 },
80208   { 220, 1 },
80209   { 220, 2 },
80210   { 170, 5 },
80211   { 170, 3 },
80212   { 170, 5 },
80213   { 170, 4 },
80214   { 170, 4 },
80215   { 170, 5 },
80216   { 222, 5 },
80217   { 222, 4 },
80218   { 223, 2 },
80219   { 223, 0 },
80220   { 221, 1 },
80221   { 221, 0 },
80222   { 216, 1 },
80223   { 216, 0 },
80224   { 211, 3 },
80225   { 211, 1 },
80226   { 144, 11 },
80227   { 224, 1 },
80228   { 224, 0 },
80229   { 174, 0 },
80230   { 174, 3 },
80231   { 182, 5 },
80232   { 182, 3 },
80233   { 225, 0 },
80234   { 225, 2 },
80235   { 144, 4 },
80236   { 144, 1 },
80237   { 144, 2 },
80238   { 144, 5 },
80239   { 144, 5 },
80240   { 144, 5 },
80241   { 144, 5 },
80242   { 144, 6 },
80243   { 144, 3 },
80244   { 226, 1 },
80245   { 226, 1 },
80246   { 165, 2 },
80247   { 166, 2 },
80248   { 228, 1 },
80249   { 227, 1 },
80250   { 227, 0 },
80251   { 144, 5 },
80252   { 229, 11 },
80253   { 231, 1 },
80254   { 231, 1 },
80255   { 231, 2 },
80256   { 231, 0 },
80257   { 232, 1 },
80258   { 232, 1 },
80259   { 232, 3 },
80260   { 233, 0 },
80261   { 233, 3 },
80262   { 234, 0 },
80263   { 234, 2 },
80264   { 230, 3 },
80265   { 230, 2 },
80266   { 235, 6 },
80267   { 235, 8 },
80268   { 235, 5 },
80269   { 235, 4 },
80270   { 235, 1 },
80271   { 170, 4 },
80272   { 170, 6 },
80273   { 186, 1 },
80274   { 186, 1 },
80275   { 186, 1 },
80276   { 144, 4 },
80277   { 144, 6 },
80278   { 144, 3 },
80279   { 237, 0 },
80280   { 237, 2 },
80281   { 236, 1 },
80282   { 236, 0 },
80283   { 144, 1 },
80284   { 144, 3 },
80285   { 144, 1 },
80286   { 144, 3 },
80287   { 144, 6 },
80288   { 144, 6 },
80289   { 238, 1 },
80290   { 239, 0 },
80291   { 239, 1 },
80292   { 144, 1 },
80293   { 144, 4 },
80294   { 240, 7 },
80295   { 241, 1 },
80296   { 241, 3 },
80297   { 242, 0 },
80298   { 242, 2 },
80299   { 243, 1 },
80300   { 243, 3 },
80301   { 244, 1 },
80302   { 245, 0 },
80303   { 245, 2 },
80304 };
80305
80306 static void yy_accept(yyParser*);  /* Forward Declaration */
80307
80308 /*
80309 ** Perform a reduce action and the shift that must immediately
80310 ** follow the reduce.
80311 */
80312 static void yy_reduce(
80313   yyParser *yypParser,         /* The parser */
80314   int yyruleno                 /* Number of the rule by which to reduce */
80315 ){
80316   int yygoto;                     /* The next state */
80317   int yyact;                      /* The next action */
80318   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
80319   yyStackEntry *yymsp;            /* The top of the parser's stack */
80320   int yysize;                     /* Amount to pop the stack */
80321   sqlite3ParserARG_FETCH;
80322   yymsp = &yypParser->yystack[yypParser->yyidx];
80323 #ifndef NDEBUG
80324   if( yyTraceFILE && yyruleno>=0 
80325         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
80326     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
80327       yyRuleName[yyruleno]);
80328   }
80329 #endif /* NDEBUG */
80330
80331   /* Silence complaints from purify about yygotominor being uninitialized
80332   ** in some cases when it is copied into the stack after the following
80333   ** switch.  yygotominor is uninitialized when a rule reduces that does
80334   ** not set the value of its left-hand side nonterminal.  Leaving the
80335   ** value of the nonterminal uninitialized is utterly harmless as long
80336   ** as the value is never used.  So really the only thing this code
80337   ** accomplishes is to quieten purify.  
80338   **
80339   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
80340   ** without this code, their parser segfaults.  I'm not sure what there
80341   ** parser is doing to make this happen.  This is the second bug report
80342   ** from wireshark this week.  Clearly they are stressing Lemon in ways
80343   ** that it has not been previously stressed...  (SQLite ticket #2172)
80344   */
80345   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
80346   yygotominor = yyzerominor;
80347
80348
80349   switch( yyruleno ){
80350   /* Beginning here are the reduction cases.  A typical example
80351   ** follows:
80352   **   case 0:
80353   **  #line <lineno> <grammarfile>
80354   **     { ... }           // User supplied code
80355   **  #line <lineno> <thisfile>
80356   **     break;
80357   */
80358       case 0: /* input ::= cmdlist */
80359       case 1: /* cmdlist ::= cmdlist ecmd */
80360       case 2: /* cmdlist ::= ecmd */
80361       case 3: /* ecmd ::= SEMI */
80362       case 4: /* ecmd ::= explain cmdx SEMI */
80363       case 10: /* trans_opt ::= */
80364       case 11: /* trans_opt ::= TRANSACTION */
80365       case 12: /* trans_opt ::= TRANSACTION nm */
80366       case 20: /* cmd ::= create_table create_table_args */
80367       case 28: /* columnlist ::= columnlist COMMA column */
80368       case 29: /* columnlist ::= column */
80369       case 37: /* type ::= */
80370       case 44: /* signed ::= plus_num */
80371       case 45: /* signed ::= minus_num */
80372       case 46: /* carglist ::= carglist carg */
80373       case 47: /* carglist ::= */
80374       case 48: /* carg ::= CONSTRAINT nm ccons */
80375       case 49: /* carg ::= ccons */
80376       case 55: /* ccons ::= NULL onconf */
80377       case 82: /* conslist ::= conslist COMMA tcons */
80378       case 83: /* conslist ::= conslist tcons */
80379       case 84: /* conslist ::= tcons */
80380       case 85: /* tcons ::= CONSTRAINT nm */
80381       case 257: /* plus_opt ::= PLUS */
80382       case 258: /* plus_opt ::= */
80383       case 268: /* foreach_clause ::= */
80384       case 269: /* foreach_clause ::= FOR EACH ROW */
80385       case 289: /* database_kw_opt ::= DATABASE */
80386       case 290: /* database_kw_opt ::= */
80387       case 298: /* kwcolumn_opt ::= */
80388       case 299: /* kwcolumn_opt ::= COLUMNKW */
80389       case 303: /* vtabarglist ::= vtabarg */
80390       case 304: /* vtabarglist ::= vtabarglist COMMA vtabarg */
80391       case 306: /* vtabarg ::= vtabarg vtabargtoken */
80392       case 310: /* anylist ::= */
80393 {
80394 }
80395         break;
80396       case 5: /* explain ::= */
80397 { sqlite3BeginParse(pParse, 0); }
80398         break;
80399       case 6: /* explain ::= EXPLAIN */
80400 { sqlite3BeginParse(pParse, 1); }
80401         break;
80402       case 7: /* explain ::= EXPLAIN QUERY PLAN */
80403 { sqlite3BeginParse(pParse, 2); }
80404         break;
80405       case 8: /* cmdx ::= cmd */
80406 { sqlite3FinishCoding(pParse); }
80407         break;
80408       case 9: /* cmd ::= BEGIN transtype trans_opt */
80409 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy280);}
80410         break;
80411       case 13: /* transtype ::= */
80412 {yygotominor.yy280 = TK_DEFERRED;}
80413         break;
80414       case 14: /* transtype ::= DEFERRED */
80415       case 15: /* transtype ::= IMMEDIATE */
80416       case 16: /* transtype ::= EXCLUSIVE */
80417       case 107: /* multiselect_op ::= UNION */
80418       case 109: /* multiselect_op ::= EXCEPT|INTERSECT */
80419 {yygotominor.yy280 = yymsp[0].major;}
80420         break;
80421       case 17: /* cmd ::= COMMIT trans_opt */
80422       case 18: /* cmd ::= END trans_opt */
80423 {sqlite3CommitTransaction(pParse);}
80424         break;
80425       case 19: /* cmd ::= ROLLBACK trans_opt */
80426 {sqlite3RollbackTransaction(pParse);}
80427         break;
80428       case 21: /* create_table ::= CREATE temp TABLE ifnotexists nm dbnm */
80429 {
80430    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy280,0,0,yymsp[-2].minor.yy280);
80431 }
80432         break;
80433       case 22: /* ifnotexists ::= */
80434       case 25: /* temp ::= */
80435       case 63: /* autoinc ::= */
80436       case 77: /* init_deferred_pred_opt ::= */
80437       case 79: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
80438       case 90: /* defer_subclause_opt ::= */
80439       case 101: /* ifexists ::= */
80440       case 112: /* distinct ::= ALL */
80441       case 113: /* distinct ::= */
80442       case 213: /* between_op ::= BETWEEN */
80443       case 216: /* in_op ::= IN */
80444 {yygotominor.yy280 = 0;}
80445         break;
80446       case 23: /* ifnotexists ::= IF NOT EXISTS */
80447       case 24: /* temp ::= TEMP */
80448       case 64: /* autoinc ::= AUTOINCR */
80449       case 78: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
80450       case 100: /* ifexists ::= IF EXISTS */
80451       case 111: /* distinct ::= DISTINCT */
80452       case 214: /* between_op ::= NOT BETWEEN */
80453       case 217: /* in_op ::= NOT IN */
80454 {yygotominor.yy280 = 1;}
80455         break;
80456       case 26: /* create_table_args ::= LP columnlist conslist_opt RP */
80457 {
80458   sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
80459 }
80460         break;
80461       case 27: /* create_table_args ::= AS select */
80462 {
80463   sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy375);
80464   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy375);
80465 }
80466         break;
80467       case 30: /* column ::= columnid type carglist */
80468 {
80469   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
80470   yygotominor.yy0.n = (pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
80471 }
80472         break;
80473       case 31: /* columnid ::= nm */
80474 {
80475   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
80476   yygotominor.yy0 = yymsp[0].minor.yy0;
80477 }
80478         break;
80479       case 32: /* id ::= ID */
80480       case 33: /* ids ::= ID|STRING */
80481       case 34: /* nm ::= ID */
80482       case 35: /* nm ::= STRING */
80483       case 36: /* nm ::= JOIN_KW */
80484       case 39: /* typetoken ::= typename */
80485       case 42: /* typename ::= ids */
80486       case 119: /* as ::= AS nm */
80487       case 120: /* as ::= ids */
80488       case 131: /* dbnm ::= DOT nm */
80489       case 242: /* collate ::= COLLATE ids */
80490       case 252: /* nmnum ::= plus_num */
80491       case 253: /* nmnum ::= nm */
80492       case 254: /* plus_num ::= plus_opt number */
80493       case 255: /* minus_num ::= MINUS number */
80494       case 256: /* number ::= INTEGER|FLOAT */
80495 {yygotominor.yy0 = yymsp[0].minor.yy0;}
80496         break;
80497       case 38: /* type ::= typetoken */
80498 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
80499         break;
80500       case 40: /* typetoken ::= typename LP signed RP */
80501 {
80502   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
80503   yygotominor.yy0.n = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z;
80504 }
80505         break;
80506       case 41: /* typetoken ::= typename LP signed COMMA signed RP */
80507 {
80508   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
80509   yygotominor.yy0.n = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z;
80510 }
80511         break;
80512       case 43: /* typename ::= typename ids */
80513 {yygotominor.yy0.z=yymsp[-1].minor.yy0.z; yygotominor.yy0.n=yymsp[0].minor.yy0.n+(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
80514         break;
80515       case 50: /* ccons ::= DEFAULT term */
80516       case 52: /* ccons ::= DEFAULT PLUS term */
80517 {sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy62);}
80518         break;
80519       case 51: /* ccons ::= DEFAULT LP expr RP */
80520 {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy62);}
80521         break;
80522       case 53: /* ccons ::= DEFAULT MINUS term */
80523 {
80524   Expr *p = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy62, 0, 0);
80525   sqlite3AddDefaultValue(pParse,p);
80526 }
80527         break;
80528       case 54: /* ccons ::= DEFAULT id */
80529 {
80530   Expr *p = sqlite3PExpr(pParse, TK_STRING, 0, 0, &yymsp[0].minor.yy0);
80531   sqlite3AddDefaultValue(pParse,p);
80532 }
80533         break;
80534       case 56: /* ccons ::= NOT NULL onconf */
80535 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy280);}
80536         break;
80537       case 57: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
80538 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy280,yymsp[0].minor.yy280,yymsp[-2].minor.yy280);}
80539         break;
80540       case 58: /* ccons ::= UNIQUE onconf */
80541 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy280,0,0,0,0);}
80542         break;
80543       case 59: /* ccons ::= CHECK LP expr RP */
80544 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy62);}
80545         break;
80546       case 60: /* ccons ::= REFERENCES nm idxlist_opt refargs */
80547 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy418,yymsp[0].minor.yy280);}
80548         break;
80549       case 61: /* ccons ::= defer_subclause */
80550 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy280);}
80551         break;
80552       case 62: /* ccons ::= COLLATE ids */
80553 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
80554         break;
80555       case 65: /* refargs ::= */
80556 { yygotominor.yy280 = OE_Restrict * 0x010101; }
80557         break;
80558       case 66: /* refargs ::= refargs refarg */
80559 { yygotominor.yy280 = (yymsp[-1].minor.yy280 & yymsp[0].minor.yy359.mask) | yymsp[0].minor.yy359.value; }
80560         break;
80561       case 67: /* refarg ::= MATCH nm */
80562 { yygotominor.yy359.value = 0;     yygotominor.yy359.mask = 0x000000; }
80563         break;
80564       case 68: /* refarg ::= ON DELETE refact */
80565 { yygotominor.yy359.value = yymsp[0].minor.yy280;     yygotominor.yy359.mask = 0x0000ff; }
80566         break;
80567       case 69: /* refarg ::= ON UPDATE refact */
80568 { yygotominor.yy359.value = yymsp[0].minor.yy280<<8;  yygotominor.yy359.mask = 0x00ff00; }
80569         break;
80570       case 70: /* refarg ::= ON INSERT refact */
80571 { yygotominor.yy359.value = yymsp[0].minor.yy280<<16; yygotominor.yy359.mask = 0xff0000; }
80572         break;
80573       case 71: /* refact ::= SET NULL */
80574 { yygotominor.yy280 = OE_SetNull; }
80575         break;
80576       case 72: /* refact ::= SET DEFAULT */
80577 { yygotominor.yy280 = OE_SetDflt; }
80578         break;
80579       case 73: /* refact ::= CASCADE */
80580 { yygotominor.yy280 = OE_Cascade; }
80581         break;
80582       case 74: /* refact ::= RESTRICT */
80583 { yygotominor.yy280 = OE_Restrict; }
80584         break;
80585       case 75: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
80586       case 76: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
80587       case 91: /* defer_subclause_opt ::= defer_subclause */
80588       case 93: /* onconf ::= ON CONFLICT resolvetype */
80589       case 95: /* orconf ::= OR resolvetype */
80590       case 96: /* resolvetype ::= raisetype */
80591       case 166: /* insert_cmd ::= INSERT orconf */
80592 {yygotominor.yy280 = yymsp[0].minor.yy280;}
80593         break;
80594       case 80: /* conslist_opt ::= */
80595 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
80596         break;
80597       case 81: /* conslist_opt ::= COMMA conslist */
80598 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
80599         break;
80600       case 86: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
80601 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy418,yymsp[0].minor.yy280,yymsp[-2].minor.yy280,0);}
80602         break;
80603       case 87: /* tcons ::= UNIQUE LP idxlist RP onconf */
80604 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy418,yymsp[0].minor.yy280,0,0,0,0);}
80605         break;
80606       case 88: /* tcons ::= CHECK LP expr RP onconf */
80607 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy62);}
80608         break;
80609       case 89: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
80610 {
80611     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy418, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy418, yymsp[-1].minor.yy280);
80612     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy280);
80613 }
80614         break;
80615       case 92: /* onconf ::= */
80616       case 94: /* orconf ::= */
80617 {yygotominor.yy280 = OE_Default;}
80618         break;
80619       case 97: /* resolvetype ::= IGNORE */
80620 {yygotominor.yy280 = OE_Ignore;}
80621         break;
80622       case 98: /* resolvetype ::= REPLACE */
80623       case 167: /* insert_cmd ::= REPLACE */
80624 {yygotominor.yy280 = OE_Replace;}
80625         break;
80626       case 99: /* cmd ::= DROP TABLE ifexists fullname */
80627 {
80628   sqlite3DropTable(pParse, yymsp[0].minor.yy151, 0, yymsp[-1].minor.yy280);
80629 }
80630         break;
80631       case 102: /* cmd ::= CREATE temp VIEW ifnotexists nm dbnm AS select */
80632 {
80633   sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy375, yymsp[-6].minor.yy280, yymsp[-4].minor.yy280);
80634 }
80635         break;
80636       case 103: /* cmd ::= DROP VIEW ifexists fullname */
80637 {
80638   sqlite3DropTable(pParse, yymsp[0].minor.yy151, 1, yymsp[-1].minor.yy280);
80639 }
80640         break;
80641       case 104: /* cmd ::= select */
80642 {
80643   SelectDest dest = {SRT_Output, 0, 0, 0, 0};
80644   sqlite3Select(pParse, yymsp[0].minor.yy375, &dest);
80645   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy375);
80646 }
80647         break;
80648       case 105: /* select ::= oneselect */
80649       case 128: /* seltablist_paren ::= select */
80650 {yygotominor.yy375 = yymsp[0].minor.yy375;}
80651         break;
80652       case 106: /* select ::= select multiselect_op oneselect */
80653 {
80654   if( yymsp[0].minor.yy375 ){
80655     yymsp[0].minor.yy375->op = yymsp[-1].minor.yy280;
80656     yymsp[0].minor.yy375->pPrior = yymsp[-2].minor.yy375;
80657   }else{
80658     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy375);
80659   }
80660   yygotominor.yy375 = yymsp[0].minor.yy375;
80661 }
80662         break;
80663       case 108: /* multiselect_op ::= UNION ALL */
80664 {yygotominor.yy280 = TK_ALL;}
80665         break;
80666       case 110: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
80667 {
80668   yygotominor.yy375 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy418,yymsp[-5].minor.yy151,yymsp[-4].minor.yy62,yymsp[-3].minor.yy418,yymsp[-2].minor.yy62,yymsp[-1].minor.yy418,yymsp[-7].minor.yy280,yymsp[0].minor.yy220.pLimit,yymsp[0].minor.yy220.pOffset);
80669 }
80670         break;
80671       case 114: /* sclp ::= selcollist COMMA */
80672       case 238: /* idxlist_opt ::= LP idxlist RP */
80673 {yygotominor.yy418 = yymsp[-1].minor.yy418;}
80674         break;
80675       case 115: /* sclp ::= */
80676       case 141: /* orderby_opt ::= */
80677       case 149: /* groupby_opt ::= */
80678       case 231: /* exprlist ::= */
80679       case 237: /* idxlist_opt ::= */
80680 {yygotominor.yy418 = 0;}
80681         break;
80682       case 116: /* selcollist ::= sclp expr as */
80683 {
80684    yygotominor.yy418 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy418,yymsp[-1].minor.yy62,yymsp[0].minor.yy0.n?&yymsp[0].minor.yy0:0);
80685 }
80686         break;
80687       case 117: /* selcollist ::= sclp STAR */
80688 {
80689   Expr *p = sqlite3PExpr(pParse, TK_ALL, 0, 0, 0);
80690   yygotominor.yy418 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy418, p, 0);
80691 }
80692         break;
80693       case 118: /* selcollist ::= sclp nm DOT STAR */
80694 {
80695   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
80696   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
80697   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
80698   yygotominor.yy418 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy418, pDot, 0);
80699 }
80700         break;
80701       case 121: /* as ::= */
80702 {yygotominor.yy0.n = 0;}
80703         break;
80704       case 122: /* from ::= */
80705 {yygotominor.yy151 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy151));}
80706         break;
80707       case 123: /* from ::= FROM seltablist */
80708 {
80709   yygotominor.yy151 = yymsp[0].minor.yy151;
80710   sqlite3SrcListShiftJoinType(yygotominor.yy151);
80711 }
80712         break;
80713       case 124: /* stl_prefix ::= seltablist joinop */
80714 {
80715    yygotominor.yy151 = yymsp[-1].minor.yy151;
80716    if( yygotominor.yy151 && yygotominor.yy151->nSrc>0 ) yygotominor.yy151->a[yygotominor.yy151->nSrc-1].jointype = yymsp[0].minor.yy280;
80717 }
80718         break;
80719       case 125: /* stl_prefix ::= */
80720 {yygotominor.yy151 = 0;}
80721         break;
80722       case 126: /* seltablist ::= stl_prefix nm dbnm as on_opt using_opt */
80723 {
80724   yygotominor.yy151 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-5].minor.yy151,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy62,yymsp[0].minor.yy240);
80725 }
80726         break;
80727       case 127: /* seltablist ::= stl_prefix LP seltablist_paren RP as on_opt using_opt */
80728 {
80729     yygotominor.yy151 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy151,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy375,yymsp[-1].minor.yy62,yymsp[0].minor.yy240);
80730   }
80731         break;
80732       case 129: /* seltablist_paren ::= seltablist */
80733 {
80734      sqlite3SrcListShiftJoinType(yymsp[0].minor.yy151);
80735      yygotominor.yy375 = sqlite3SelectNew(pParse,0,yymsp[0].minor.yy151,0,0,0,0,0,0,0);
80736   }
80737         break;
80738       case 130: /* dbnm ::= */
80739 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
80740         break;
80741       case 132: /* fullname ::= nm dbnm */
80742 {yygotominor.yy151 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
80743         break;
80744       case 133: /* joinop ::= COMMA|JOIN */
80745 { yygotominor.yy280 = JT_INNER; }
80746         break;
80747       case 134: /* joinop ::= JOIN_KW JOIN */
80748 { yygotominor.yy280 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
80749         break;
80750       case 135: /* joinop ::= JOIN_KW nm JOIN */
80751 { yygotominor.yy280 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
80752         break;
80753       case 136: /* joinop ::= JOIN_KW nm nm JOIN */
80754 { yygotominor.yy280 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
80755         break;
80756       case 137: /* on_opt ::= ON expr */
80757       case 145: /* sortitem ::= expr */
80758       case 152: /* having_opt ::= HAVING expr */
80759       case 159: /* where_opt ::= WHERE expr */
80760       case 174: /* expr ::= term */
80761       case 202: /* escape ::= ESCAPE expr */
80762       case 226: /* case_else ::= ELSE expr */
80763       case 228: /* case_operand ::= expr */
80764 {yygotominor.yy62 = yymsp[0].minor.yy62;}
80765         break;
80766       case 138: /* on_opt ::= */
80767       case 151: /* having_opt ::= */
80768       case 158: /* where_opt ::= */
80769       case 203: /* escape ::= */
80770       case 227: /* case_else ::= */
80771       case 229: /* case_operand ::= */
80772 {yygotominor.yy62 = 0;}
80773         break;
80774       case 139: /* using_opt ::= USING LP inscollist RP */
80775       case 171: /* inscollist_opt ::= LP inscollist RP */
80776 {yygotominor.yy240 = yymsp[-1].minor.yy240;}
80777         break;
80778       case 140: /* using_opt ::= */
80779       case 170: /* inscollist_opt ::= */
80780 {yygotominor.yy240 = 0;}
80781         break;
80782       case 142: /* orderby_opt ::= ORDER BY sortlist */
80783       case 150: /* groupby_opt ::= GROUP BY nexprlist */
80784       case 230: /* exprlist ::= nexprlist */
80785 {yygotominor.yy418 = yymsp[0].minor.yy418;}
80786         break;
80787       case 143: /* sortlist ::= sortlist COMMA sortitem sortorder */
80788 {
80789   yygotominor.yy418 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy418,yymsp[-1].minor.yy62,0);
80790   if( yygotominor.yy418 ) yygotominor.yy418->a[yygotominor.yy418->nExpr-1].sortOrder = yymsp[0].minor.yy280;
80791 }
80792         break;
80793       case 144: /* sortlist ::= sortitem sortorder */
80794 {
80795   yygotominor.yy418 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy62,0);
80796   if( yygotominor.yy418 && yygotominor.yy418->a ) yygotominor.yy418->a[0].sortOrder = yymsp[0].minor.yy280;
80797 }
80798         break;
80799       case 146: /* sortorder ::= ASC */
80800       case 148: /* sortorder ::= */
80801 {yygotominor.yy280 = SQLITE_SO_ASC;}
80802         break;
80803       case 147: /* sortorder ::= DESC */
80804 {yygotominor.yy280 = SQLITE_SO_DESC;}
80805         break;
80806       case 153: /* limit_opt ::= */
80807 {yygotominor.yy220.pLimit = 0; yygotominor.yy220.pOffset = 0;}
80808         break;
80809       case 154: /* limit_opt ::= LIMIT expr */
80810 {yygotominor.yy220.pLimit = yymsp[0].minor.yy62; yygotominor.yy220.pOffset = 0;}
80811         break;
80812       case 155: /* limit_opt ::= LIMIT expr OFFSET expr */
80813 {yygotominor.yy220.pLimit = yymsp[-2].minor.yy62; yygotominor.yy220.pOffset = yymsp[0].minor.yy62;}
80814         break;
80815       case 156: /* limit_opt ::= LIMIT expr COMMA expr */
80816 {yygotominor.yy220.pOffset = yymsp[-2].minor.yy62; yygotominor.yy220.pLimit = yymsp[0].minor.yy62;}
80817         break;
80818       case 157: /* cmd ::= DELETE FROM fullname where_opt */
80819 {sqlite3DeleteFrom(pParse,yymsp[-1].minor.yy151,yymsp[0].minor.yy62);}
80820         break;
80821       case 160: /* cmd ::= UPDATE orconf fullname SET setlist where_opt */
80822 {
80823   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy418,"set list"); 
80824   sqlite3Update(pParse,yymsp[-3].minor.yy151,yymsp[-1].minor.yy418,yymsp[0].minor.yy62,yymsp[-4].minor.yy280);
80825 }
80826         break;
80827       case 161: /* setlist ::= setlist COMMA nm EQ expr */
80828 {yygotominor.yy418 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy418,yymsp[0].minor.yy62,&yymsp[-2].minor.yy0);}
80829         break;
80830       case 162: /* setlist ::= nm EQ expr */
80831 {yygotominor.yy418 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy62,&yymsp[-2].minor.yy0);}
80832         break;
80833       case 163: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
80834 {sqlite3Insert(pParse, yymsp[-5].minor.yy151, yymsp[-1].minor.yy418, 0, yymsp[-4].minor.yy240, yymsp[-7].minor.yy280);}
80835         break;
80836       case 164: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
80837 {sqlite3Insert(pParse, yymsp[-2].minor.yy151, 0, yymsp[0].minor.yy375, yymsp[-1].minor.yy240, yymsp[-4].minor.yy280);}
80838         break;
80839       case 165: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
80840 {sqlite3Insert(pParse, yymsp[-3].minor.yy151, 0, 0, yymsp[-2].minor.yy240, yymsp[-5].minor.yy280);}
80841         break;
80842       case 168: /* itemlist ::= itemlist COMMA expr */
80843       case 232: /* nexprlist ::= nexprlist COMMA expr */
80844 {yygotominor.yy418 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy418,yymsp[0].minor.yy62,0);}
80845         break;
80846       case 169: /* itemlist ::= expr */
80847       case 233: /* nexprlist ::= expr */
80848 {yygotominor.yy418 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy62,0);}
80849         break;
80850       case 172: /* inscollist ::= inscollist COMMA nm */
80851 {yygotominor.yy240 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy240,&yymsp[0].minor.yy0);}
80852         break;
80853       case 173: /* inscollist ::= nm */
80854 {yygotominor.yy240 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
80855         break;
80856       case 175: /* expr ::= LP expr RP */
80857 {yygotominor.yy62 = yymsp[-1].minor.yy62; sqlite3ExprSpan(yygotominor.yy62,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); }
80858         break;
80859       case 176: /* term ::= NULL */
80860       case 181: /* term ::= INTEGER|FLOAT|BLOB */
80861       case 182: /* term ::= STRING */
80862 {yygotominor.yy62 = sqlite3PExpr(pParse, yymsp[0].major, 0, 0, &yymsp[0].minor.yy0);}
80863         break;
80864       case 177: /* expr ::= ID */
80865       case 178: /* expr ::= JOIN_KW */
80866 {yygotominor.yy62 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);}
80867         break;
80868       case 179: /* expr ::= nm DOT nm */
80869 {
80870   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
80871   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
80872   yygotominor.yy62 = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
80873 }
80874         break;
80875       case 180: /* expr ::= nm DOT nm DOT nm */
80876 {
80877   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
80878   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
80879   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
80880   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
80881   yygotominor.yy62 = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
80882 }
80883         break;
80884       case 183: /* expr ::= REGISTER */
80885 {yygotominor.yy62 = sqlite3RegisterExpr(pParse, &yymsp[0].minor.yy0);}
80886         break;
80887       case 184: /* expr ::= VARIABLE */
80888 {
80889   Token *pToken = &yymsp[0].minor.yy0;
80890   Expr *pExpr = yygotominor.yy62 = sqlite3PExpr(pParse, TK_VARIABLE, 0, 0, pToken);
80891   sqlite3ExprAssignVarNumber(pParse, pExpr);
80892 }
80893         break;
80894       case 185: /* expr ::= expr COLLATE ids */
80895 {
80896   yygotominor.yy62 = sqlite3ExprSetColl(pParse, yymsp[-2].minor.yy62, &yymsp[0].minor.yy0);
80897 }
80898         break;
80899       case 186: /* expr ::= CAST LP expr AS typetoken RP */
80900 {
80901   yygotominor.yy62 = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy62, 0, &yymsp[-1].minor.yy0);
80902   sqlite3ExprSpan(yygotominor.yy62,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
80903 }
80904         break;
80905       case 187: /* expr ::= ID LP distinct exprlist RP */
80906 {
80907   if( yymsp[-1].minor.yy418 && yymsp[-1].minor.yy418->nExpr>SQLITE_MAX_FUNCTION_ARG ){
80908     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
80909   }
80910   yygotominor.yy62 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy418, &yymsp[-4].minor.yy0);
80911   sqlite3ExprSpan(yygotominor.yy62,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
80912   if( yymsp[-2].minor.yy280 && yygotominor.yy62 ){
80913     yygotominor.yy62->flags |= EP_Distinct;
80914   }
80915 }
80916         break;
80917       case 188: /* expr ::= ID LP STAR RP */
80918 {
80919   yygotominor.yy62 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
80920   sqlite3ExprSpan(yygotominor.yy62,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
80921 }
80922         break;
80923       case 189: /* term ::= CTIME_KW */
80924 {
80925   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
80926   ** treated as functions that return constants */
80927   yygotominor.yy62 = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
80928   if( yygotominor.yy62 ){
80929     yygotominor.yy62->op = TK_CONST_FUNC;  
80930     yygotominor.yy62->span = yymsp[0].minor.yy0;
80931   }
80932 }
80933         break;
80934       case 190: /* expr ::= expr AND expr */
80935       case 191: /* expr ::= expr OR expr */
80936       case 192: /* expr ::= expr LT|GT|GE|LE expr */
80937       case 193: /* expr ::= expr EQ|NE expr */
80938       case 194: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
80939       case 195: /* expr ::= expr PLUS|MINUS expr */
80940       case 196: /* expr ::= expr STAR|SLASH|REM expr */
80941       case 197: /* expr ::= expr CONCAT expr */
80942 {yygotominor.yy62 = sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy62,yymsp[0].minor.yy62,0);}
80943         break;
80944       case 198: /* likeop ::= LIKE_KW */
80945       case 200: /* likeop ::= MATCH */
80946 {yygotominor.yy222.eOperator = yymsp[0].minor.yy0; yygotominor.yy222.not = 0;}
80947         break;
80948       case 199: /* likeop ::= NOT LIKE_KW */
80949       case 201: /* likeop ::= NOT MATCH */
80950 {yygotominor.yy222.eOperator = yymsp[0].minor.yy0; yygotominor.yy222.not = 1;}
80951         break;
80952       case 204: /* expr ::= expr likeop expr escape */
80953 {
80954   ExprList *pList;
80955   pList = sqlite3ExprListAppend(pParse,0, yymsp[-1].minor.yy62, 0);
80956   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-3].minor.yy62, 0);
80957   if( yymsp[0].minor.yy62 ){
80958     pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy62, 0);
80959   }
80960   yygotominor.yy62 = sqlite3ExprFunction(pParse, pList, &yymsp[-2].minor.yy222.eOperator);
80961   if( yymsp[-2].minor.yy222.not ) yygotominor.yy62 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy62, 0, 0);
80962   sqlite3ExprSpan(yygotominor.yy62, &yymsp[-3].minor.yy62->span, &yymsp[-1].minor.yy62->span);
80963   if( yygotominor.yy62 ) yygotominor.yy62->flags |= EP_InfixFunc;
80964 }
80965         break;
80966       case 205: /* expr ::= expr ISNULL|NOTNULL */
80967 {
80968   yygotominor.yy62 = sqlite3PExpr(pParse, yymsp[0].major, yymsp[-1].minor.yy62, 0, 0);
80969   sqlite3ExprSpan(yygotominor.yy62,&yymsp[-1].minor.yy62->span,&yymsp[0].minor.yy0);
80970 }
80971         break;
80972       case 206: /* expr ::= expr IS NULL */
80973 {
80974   yygotominor.yy62 = sqlite3PExpr(pParse, TK_ISNULL, yymsp[-2].minor.yy62, 0, 0);
80975   sqlite3ExprSpan(yygotominor.yy62,&yymsp[-2].minor.yy62->span,&yymsp[0].minor.yy0);
80976 }
80977         break;
80978       case 207: /* expr ::= expr NOT NULL */
80979 {
80980   yygotominor.yy62 = sqlite3PExpr(pParse, TK_NOTNULL, yymsp[-2].minor.yy62, 0, 0);
80981   sqlite3ExprSpan(yygotominor.yy62,&yymsp[-2].minor.yy62->span,&yymsp[0].minor.yy0);
80982 }
80983         break;
80984       case 208: /* expr ::= expr IS NOT NULL */
80985 {
80986   yygotominor.yy62 = sqlite3PExpr(pParse, TK_NOTNULL, yymsp[-3].minor.yy62, 0, 0);
80987   sqlite3ExprSpan(yygotominor.yy62,&yymsp[-3].minor.yy62->span,&yymsp[0].minor.yy0);
80988 }
80989         break;
80990       case 209: /* expr ::= NOT expr */
80991       case 210: /* expr ::= BITNOT expr */
80992 {
80993   yygotominor.yy62 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy62, 0, 0);
80994   sqlite3ExprSpan(yygotominor.yy62,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy62->span);
80995 }
80996         break;
80997       case 211: /* expr ::= MINUS expr */
80998 {
80999   yygotominor.yy62 = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy62, 0, 0);
81000   sqlite3ExprSpan(yygotominor.yy62,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy62->span);
81001 }
81002         break;
81003       case 212: /* expr ::= PLUS expr */
81004 {
81005   yygotominor.yy62 = sqlite3PExpr(pParse, TK_UPLUS, yymsp[0].minor.yy62, 0, 0);
81006   sqlite3ExprSpan(yygotominor.yy62,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy62->span);
81007 }
81008         break;
81009       case 215: /* expr ::= expr between_op expr AND expr */
81010 {
81011   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy62, 0);
81012   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy62, 0);
81013   yygotominor.yy62 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy62, 0, 0);
81014   if( yygotominor.yy62 ){
81015     yygotominor.yy62->pList = pList;
81016   }else{
81017     sqlite3ExprListDelete(pParse->db, pList);
81018   } 
81019   if( yymsp[-3].minor.yy280 ) yygotominor.yy62 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy62, 0, 0);
81020   sqlite3ExprSpan(yygotominor.yy62,&yymsp[-4].minor.yy62->span,&yymsp[0].minor.yy62->span);
81021 }
81022         break;
81023       case 218: /* expr ::= expr in_op LP exprlist RP */
81024 {
81025     yygotominor.yy62 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy62, 0, 0);
81026     if( yygotominor.yy62 ){
81027       yygotominor.yy62->pList = yymsp[-1].minor.yy418;
81028       sqlite3ExprSetHeight(pParse, yygotominor.yy62);
81029     }else{
81030       sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy418);
81031     }
81032     if( yymsp[-3].minor.yy280 ) yygotominor.yy62 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy62, 0, 0);
81033     sqlite3ExprSpan(yygotominor.yy62,&yymsp[-4].minor.yy62->span,&yymsp[0].minor.yy0);
81034   }
81035         break;
81036       case 219: /* expr ::= LP select RP */
81037 {
81038     yygotominor.yy62 = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
81039     if( yygotominor.yy62 ){
81040       yygotominor.yy62->pSelect = yymsp[-1].minor.yy375;
81041       sqlite3ExprSetHeight(pParse, yygotominor.yy62);
81042     }else{
81043       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy375);
81044     }
81045     sqlite3ExprSpan(yygotominor.yy62,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
81046   }
81047         break;
81048       case 220: /* expr ::= expr in_op LP select RP */
81049 {
81050     yygotominor.yy62 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy62, 0, 0);
81051     if( yygotominor.yy62 ){
81052       yygotominor.yy62->pSelect = yymsp[-1].minor.yy375;
81053       sqlite3ExprSetHeight(pParse, yygotominor.yy62);
81054     }else{
81055       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy375);
81056     }
81057     if( yymsp[-3].minor.yy280 ) yygotominor.yy62 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy62, 0, 0);
81058     sqlite3ExprSpan(yygotominor.yy62,&yymsp[-4].minor.yy62->span,&yymsp[0].minor.yy0);
81059   }
81060         break;
81061       case 221: /* expr ::= expr in_op nm dbnm */
81062 {
81063     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
81064     yygotominor.yy62 = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy62, 0, 0);
81065     if( yygotominor.yy62 ){
81066       yygotominor.yy62->pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
81067       sqlite3ExprSetHeight(pParse, yygotominor.yy62);
81068     }else{
81069       sqlite3SrcListDelete(pParse->db, pSrc);
81070     }
81071     if( yymsp[-2].minor.yy280 ) yygotominor.yy62 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy62, 0, 0);
81072     sqlite3ExprSpan(yygotominor.yy62,&yymsp[-3].minor.yy62->span,yymsp[0].minor.yy0.z?&yymsp[0].minor.yy0:&yymsp[-1].minor.yy0);
81073   }
81074         break;
81075       case 222: /* expr ::= EXISTS LP select RP */
81076 {
81077     Expr *p = yygotominor.yy62 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
81078     if( p ){
81079       p->pSelect = yymsp[-1].minor.yy375;
81080       sqlite3ExprSpan(p,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
81081       sqlite3ExprSetHeight(pParse, yygotominor.yy62);
81082     }else{
81083       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy375);
81084     }
81085   }
81086         break;
81087       case 223: /* expr ::= CASE case_operand case_exprlist case_else END */
81088 {
81089   yygotominor.yy62 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy62, yymsp[-1].minor.yy62, 0);
81090   if( yygotominor.yy62 ){
81091     yygotominor.yy62->pList = yymsp[-2].minor.yy418;
81092     sqlite3ExprSetHeight(pParse, yygotominor.yy62);
81093   }else{
81094     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy418);
81095   }
81096   sqlite3ExprSpan(yygotominor.yy62, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0);
81097 }
81098         break;
81099       case 224: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
81100 {
81101   yygotominor.yy418 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy418, yymsp[-2].minor.yy62, 0);
81102   yygotominor.yy418 = sqlite3ExprListAppend(pParse,yygotominor.yy418, yymsp[0].minor.yy62, 0);
81103 }
81104         break;
81105       case 225: /* case_exprlist ::= WHEN expr THEN expr */
81106 {
81107   yygotominor.yy418 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy62, 0);
81108   yygotominor.yy418 = sqlite3ExprListAppend(pParse,yygotominor.yy418, yymsp[0].minor.yy62, 0);
81109 }
81110         break;
81111       case 234: /* cmd ::= CREATE uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
81112 {
81113   sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0, 
81114                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy418, yymsp[-9].minor.yy280,
81115                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy280);
81116 }
81117         break;
81118       case 235: /* uniqueflag ::= UNIQUE */
81119       case 282: /* raisetype ::= ABORT */
81120 {yygotominor.yy280 = OE_Abort;}
81121         break;
81122       case 236: /* uniqueflag ::= */
81123 {yygotominor.yy280 = OE_None;}
81124         break;
81125       case 239: /* idxlist ::= idxlist COMMA nm collate sortorder */
81126 {
81127   Expr *p = 0;
81128   if( yymsp[-1].minor.yy0.n>0 ){
81129     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
81130     sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
81131   }
81132   yygotominor.yy418 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy418, p, &yymsp[-2].minor.yy0);
81133   sqlite3ExprListCheckLength(pParse, yygotominor.yy418, "index");
81134   if( yygotominor.yy418 ) yygotominor.yy418->a[yygotominor.yy418->nExpr-1].sortOrder = yymsp[0].minor.yy280;
81135 }
81136         break;
81137       case 240: /* idxlist ::= nm collate sortorder */
81138 {
81139   Expr *p = 0;
81140   if( yymsp[-1].minor.yy0.n>0 ){
81141     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
81142     sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
81143   }
81144   yygotominor.yy418 = sqlite3ExprListAppend(pParse,0, p, &yymsp[-2].minor.yy0);
81145   sqlite3ExprListCheckLength(pParse, yygotominor.yy418, "index");
81146   if( yygotominor.yy418 ) yygotominor.yy418->a[yygotominor.yy418->nExpr-1].sortOrder = yymsp[0].minor.yy280;
81147 }
81148         break;
81149       case 241: /* collate ::= */
81150 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
81151         break;
81152       case 243: /* cmd ::= DROP INDEX ifexists fullname */
81153 {sqlite3DropIndex(pParse, yymsp[0].minor.yy151, yymsp[-1].minor.yy280);}
81154         break;
81155       case 244: /* cmd ::= VACUUM */
81156       case 245: /* cmd ::= VACUUM nm */
81157 {sqlite3Vacuum(pParse);}
81158         break;
81159       case 246: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
81160       case 247: /* cmd ::= PRAGMA nm dbnm EQ ON */
81161       case 248: /* cmd ::= PRAGMA nm dbnm EQ DELETE */
81162 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
81163         break;
81164       case 249: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
81165 {
81166   sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);
81167 }
81168         break;
81169       case 250: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
81170 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
81171         break;
81172       case 251: /* cmd ::= PRAGMA nm dbnm */
81173 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
81174         break;
81175       case 259: /* cmd ::= CREATE trigger_decl BEGIN trigger_cmd_list END */
81176 {
81177   Token all;
81178   all.z = yymsp[-3].minor.yy0.z;
81179   all.n = (yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
81180   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy360, &all);
81181 }
81182         break;
81183       case 260: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
81184 {
81185   sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy280, yymsp[-4].minor.yy30.a, yymsp[-4].minor.yy30.b, yymsp[-2].minor.yy151, yymsp[0].minor.yy62, yymsp[-10].minor.yy280, yymsp[-8].minor.yy280);
81186   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
81187 }
81188         break;
81189       case 261: /* trigger_time ::= BEFORE */
81190       case 264: /* trigger_time ::= */
81191 { yygotominor.yy280 = TK_BEFORE; }
81192         break;
81193       case 262: /* trigger_time ::= AFTER */
81194 { yygotominor.yy280 = TK_AFTER;  }
81195         break;
81196       case 263: /* trigger_time ::= INSTEAD OF */
81197 { yygotominor.yy280 = TK_INSTEAD;}
81198         break;
81199       case 265: /* trigger_event ::= DELETE|INSERT */
81200       case 266: /* trigger_event ::= UPDATE */
81201 {yygotominor.yy30.a = yymsp[0].major; yygotominor.yy30.b = 0;}
81202         break;
81203       case 267: /* trigger_event ::= UPDATE OF inscollist */
81204 {yygotominor.yy30.a = TK_UPDATE; yygotominor.yy30.b = yymsp[0].minor.yy240;}
81205         break;
81206       case 270: /* when_clause ::= */
81207       case 287: /* key_opt ::= */
81208 { yygotominor.yy62 = 0; }
81209         break;
81210       case 271: /* when_clause ::= WHEN expr */
81211       case 288: /* key_opt ::= KEY expr */
81212 { yygotominor.yy62 = yymsp[0].minor.yy62; }
81213         break;
81214       case 272: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
81215 {
81216 /*
81217   if( yymsp[-2].minor.yy360 ){
81218     yymsp[-2].minor.yy360->pLast->pNext = yymsp[-1].minor.yy360;
81219   }else{
81220     yymsp[-2].minor.yy360 = yymsp[-1].minor.yy360;
81221   }
81222 */
81223   assert( yymsp[-2].minor.yy360!=0 );
81224   yymsp[-2].minor.yy360->pLast->pNext = yymsp[-1].minor.yy360;
81225   yymsp[-2].minor.yy360->pLast = yymsp[-1].minor.yy360;
81226   yygotominor.yy360 = yymsp[-2].minor.yy360;
81227 }
81228         break;
81229       case 273: /* trigger_cmd_list ::= trigger_cmd SEMI */
81230
81231   /* if( yymsp[-1].minor.yy360 ) */
81232   assert( yymsp[-1].minor.yy360!=0 );
81233   yymsp[-1].minor.yy360->pLast = yymsp[-1].minor.yy360;
81234   yygotominor.yy360 = yymsp[-1].minor.yy360;
81235 }
81236         break;
81237       case 274: /* trigger_cmd ::= UPDATE orconf nm SET setlist where_opt */
81238 { yygotominor.yy360 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy418, yymsp[0].minor.yy62, yymsp[-4].minor.yy280); }
81239         break;
81240       case 275: /* trigger_cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP */
81241 {yygotominor.yy360 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy240, yymsp[-1].minor.yy418, 0, yymsp[-7].minor.yy280);}
81242         break;
81243       case 276: /* trigger_cmd ::= insert_cmd INTO nm inscollist_opt select */
81244 {yygotominor.yy360 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy240, 0, yymsp[0].minor.yy375, yymsp[-4].minor.yy280);}
81245         break;
81246       case 277: /* trigger_cmd ::= DELETE FROM nm where_opt */
81247 {yygotominor.yy360 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-1].minor.yy0, yymsp[0].minor.yy62);}
81248         break;
81249       case 278: /* trigger_cmd ::= select */
81250 {yygotominor.yy360 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy375); }
81251         break;
81252       case 279: /* expr ::= RAISE LP IGNORE RP */
81253 {
81254   yygotominor.yy62 = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); 
81255   if( yygotominor.yy62 ){
81256     yygotominor.yy62->iColumn = OE_Ignore;
81257     sqlite3ExprSpan(yygotominor.yy62, &yymsp[-3].minor.yy0, &yymsp[0].minor.yy0);
81258   }
81259 }
81260         break;
81261       case 280: /* expr ::= RAISE LP raisetype COMMA nm RP */
81262 {
81263   yygotominor.yy62 = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); 
81264   if( yygotominor.yy62 ) {
81265     yygotominor.yy62->iColumn = yymsp[-3].minor.yy280;
81266     sqlite3ExprSpan(yygotominor.yy62, &yymsp[-5].minor.yy0, &yymsp[0].minor.yy0);
81267   }
81268 }
81269         break;
81270       case 281: /* raisetype ::= ROLLBACK */
81271 {yygotominor.yy280 = OE_Rollback;}
81272         break;
81273       case 283: /* raisetype ::= FAIL */
81274 {yygotominor.yy280 = OE_Fail;}
81275         break;
81276       case 284: /* cmd ::= DROP TRIGGER ifexists fullname */
81277 {
81278   sqlite3DropTrigger(pParse,yymsp[0].minor.yy151,yymsp[-1].minor.yy280);
81279 }
81280         break;
81281       case 285: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
81282 {
81283   sqlite3Attach(pParse, yymsp[-3].minor.yy62, yymsp[-1].minor.yy62, yymsp[0].minor.yy62);
81284 }
81285         break;
81286       case 286: /* cmd ::= DETACH database_kw_opt expr */
81287 {
81288   sqlite3Detach(pParse, yymsp[0].minor.yy62);
81289 }
81290         break;
81291       case 291: /* cmd ::= REINDEX */
81292 {sqlite3Reindex(pParse, 0, 0);}
81293         break;
81294       case 292: /* cmd ::= REINDEX nm dbnm */
81295 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
81296         break;
81297       case 293: /* cmd ::= ANALYZE */
81298 {sqlite3Analyze(pParse, 0, 0);}
81299         break;
81300       case 294: /* cmd ::= ANALYZE nm dbnm */
81301 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
81302         break;
81303       case 295: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
81304 {
81305   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy151,&yymsp[0].minor.yy0);
81306 }
81307         break;
81308       case 296: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
81309 {
81310   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
81311 }
81312         break;
81313       case 297: /* add_column_fullname ::= fullname */
81314 {
81315   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy151);
81316 }
81317         break;
81318       case 300: /* cmd ::= create_vtab */
81319 {sqlite3VtabFinishParse(pParse,0);}
81320         break;
81321       case 301: /* cmd ::= create_vtab LP vtabarglist RP */
81322 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
81323         break;
81324       case 302: /* create_vtab ::= CREATE VIRTUAL TABLE nm dbnm USING nm */
81325 {
81326     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
81327 }
81328         break;
81329       case 305: /* vtabarg ::= */
81330 {sqlite3VtabArgInit(pParse);}
81331         break;
81332       case 307: /* vtabargtoken ::= ANY */
81333       case 308: /* vtabargtoken ::= lp anylist RP */
81334       case 309: /* lp ::= LP */
81335       case 311: /* anylist ::= anylist ANY */
81336 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
81337         break;
81338   };
81339   yygoto = yyRuleInfo[yyruleno].lhs;
81340   yysize = yyRuleInfo[yyruleno].nrhs;
81341   yypParser->yyidx -= yysize;
81342   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,yygoto);
81343   if( yyact < YYNSTATE ){
81344 #ifdef NDEBUG
81345     /* If we are not debugging and the reduce action popped at least
81346     ** one element off the stack, then we can push the new element back
81347     ** onto the stack here, and skip the stack overflow test in yy_shift().
81348     ** That gives a significant speed improvement. */
81349     if( yysize ){
81350       yypParser->yyidx++;
81351       yymsp -= yysize-1;
81352       yymsp->stateno = yyact;
81353       yymsp->major = yygoto;
81354       yymsp->minor = yygotominor;
81355     }else
81356 #endif
81357     {
81358       yy_shift(yypParser,yyact,yygoto,&yygotominor);
81359     }
81360   }else{
81361     assert( yyact == YYNSTATE + YYNRULE + 1 );
81362     yy_accept(yypParser);
81363   }
81364 }
81365
81366 /*
81367 ** The following code executes when the parse fails
81368 */
81369 static void yy_parse_failed(
81370   yyParser *yypParser           /* The parser */
81371 ){
81372   sqlite3ParserARG_FETCH;
81373 #ifndef NDEBUG
81374   if( yyTraceFILE ){
81375     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
81376   }
81377 #endif
81378   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
81379   /* Here code is inserted which will be executed whenever the
81380   ** parser fails */
81381   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
81382 }
81383
81384 /*
81385 ** The following code executes when a syntax error first occurs.
81386 */
81387 static void yy_syntax_error(
81388   yyParser *yypParser,           /* The parser */
81389   int yymajor,                   /* The major type of the error token */
81390   YYMINORTYPE yyminor            /* The minor type of the error token */
81391 ){
81392   sqlite3ParserARG_FETCH;
81393 #define TOKEN (yyminor.yy0)
81394
81395   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
81396   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
81397   pParse->parseError = 1;
81398   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
81399 }
81400
81401 /*
81402 ** The following is executed when the parser accepts
81403 */
81404 static void yy_accept(
81405   yyParser *yypParser           /* The parser */
81406 ){
81407   sqlite3ParserARG_FETCH;
81408 #ifndef NDEBUG
81409   if( yyTraceFILE ){
81410     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
81411   }
81412 #endif
81413   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
81414   /* Here code is inserted which will be executed whenever the
81415   ** parser accepts */
81416   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
81417 }
81418
81419 /* The main parser program.
81420 ** The first argument is a pointer to a structure obtained from
81421 ** "sqlite3ParserAlloc" which describes the current state of the parser.
81422 ** The second argument is the major token number.  The third is
81423 ** the minor token.  The fourth optional argument is whatever the
81424 ** user wants (and specified in the grammar) and is available for
81425 ** use by the action routines.
81426 **
81427 ** Inputs:
81428 ** <ul>
81429 ** <li> A pointer to the parser (an opaque structure.)
81430 ** <li> The major token number.
81431 ** <li> The minor token number.
81432 ** <li> An option argument of a grammar-specified type.
81433 ** </ul>
81434 **
81435 ** Outputs:
81436 ** None.
81437 */
81438 SQLITE_PRIVATE void sqlite3Parser(
81439   void *yyp,                   /* The parser */
81440   int yymajor,                 /* The major token code number */
81441   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
81442   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
81443 ){
81444   YYMINORTYPE yyminorunion;
81445   int yyact;            /* The parser action. */
81446   int yyendofinput;     /* True if we are at the end of input */
81447 #ifdef YYERRORSYMBOL
81448   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
81449 #endif
81450   yyParser *yypParser;  /* The parser */
81451
81452   /* (re)initialize the parser, if necessary */
81453   yypParser = (yyParser*)yyp;
81454   if( yypParser->yyidx<0 ){
81455 #if YYSTACKDEPTH<=0
81456     if( yypParser->yystksz <=0 ){
81457       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
81458       yyminorunion = yyzerominor;
81459       yyStackOverflow(yypParser, &yyminorunion);
81460       return;
81461     }
81462 #endif
81463     yypParser->yyidx = 0;
81464     yypParser->yyerrcnt = -1;
81465     yypParser->yystack[0].stateno = 0;
81466     yypParser->yystack[0].major = 0;
81467   }
81468   yyminorunion.yy0 = yyminor;
81469   yyendofinput = (yymajor==0);
81470   sqlite3ParserARG_STORE;
81471
81472 #ifndef NDEBUG
81473   if( yyTraceFILE ){
81474     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
81475   }
81476 #endif
81477
81478   do{
81479     yyact = yy_find_shift_action(yypParser,yymajor);
81480     if( yyact<YYNSTATE ){
81481       assert( !yyendofinput );  /* Impossible to shift the $ token */
81482       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
81483       yypParser->yyerrcnt--;
81484       yymajor = YYNOCODE;
81485     }else if( yyact < YYNSTATE + YYNRULE ){
81486       yy_reduce(yypParser,yyact-YYNSTATE);
81487     }else{
81488       assert( yyact == YY_ERROR_ACTION );
81489 #ifdef YYERRORSYMBOL
81490       int yymx;
81491 #endif
81492 #ifndef NDEBUG
81493       if( yyTraceFILE ){
81494         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
81495       }
81496 #endif
81497 #ifdef YYERRORSYMBOL
81498       /* A syntax error has occurred.
81499       ** The response to an error depends upon whether or not the
81500       ** grammar defines an error token "ERROR".  
81501       **
81502       ** This is what we do if the grammar does define ERROR:
81503       **
81504       **  * Call the %syntax_error function.
81505       **
81506       **  * Begin popping the stack until we enter a state where
81507       **    it is legal to shift the error symbol, then shift
81508       **    the error symbol.
81509       **
81510       **  * Set the error count to three.
81511       **
81512       **  * Begin accepting and shifting new tokens.  No new error
81513       **    processing will occur until three tokens have been
81514       **    shifted successfully.
81515       **
81516       */
81517       if( yypParser->yyerrcnt<0 ){
81518         yy_syntax_error(yypParser,yymajor,yyminorunion);
81519       }
81520       yymx = yypParser->yystack[yypParser->yyidx].major;
81521       if( yymx==YYERRORSYMBOL || yyerrorhit ){
81522 #ifndef NDEBUG
81523         if( yyTraceFILE ){
81524           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
81525              yyTracePrompt,yyTokenName[yymajor]);
81526         }
81527 #endif
81528         yy_destructor(yypParser, yymajor,&yyminorunion);
81529         yymajor = YYNOCODE;
81530       }else{
81531          while(
81532           yypParser->yyidx >= 0 &&
81533           yymx != YYERRORSYMBOL &&
81534           (yyact = yy_find_reduce_action(
81535                         yypParser->yystack[yypParser->yyidx].stateno,
81536                         YYERRORSYMBOL)) >= YYNSTATE
81537         ){
81538           yy_pop_parser_stack(yypParser);
81539         }
81540         if( yypParser->yyidx < 0 || yymajor==0 ){
81541           yy_destructor(yypParser,yymajor,&yyminorunion);
81542           yy_parse_failed(yypParser);
81543           yymajor = YYNOCODE;
81544         }else if( yymx!=YYERRORSYMBOL ){
81545           YYMINORTYPE u2;
81546           u2.YYERRSYMDT = 0;
81547           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
81548         }
81549       }
81550       yypParser->yyerrcnt = 3;
81551       yyerrorhit = 1;
81552 #else  /* YYERRORSYMBOL is not defined */
81553       /* This is what we do if the grammar does not define ERROR:
81554       **
81555       **  * Report an error message, and throw away the input token.
81556       **
81557       **  * If the input token is $, then fail the parse.
81558       **
81559       ** As before, subsequent error messages are suppressed until
81560       ** three input tokens have been successfully shifted.
81561       */
81562       if( yypParser->yyerrcnt<=0 ){
81563         yy_syntax_error(yypParser,yymajor,yyminorunion);
81564       }
81565       yypParser->yyerrcnt = 3;
81566       yy_destructor(yypParser,yymajor,&yyminorunion);
81567       if( yyendofinput ){
81568         yy_parse_failed(yypParser);
81569       }
81570       yymajor = YYNOCODE;
81571 #endif
81572     }
81573   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
81574   return;
81575 }
81576
81577 /************** End of parse.c ***********************************************/
81578 /************** Begin file tokenize.c ****************************************/
81579 /*
81580 ** 2001 September 15
81581 **
81582 ** The author disclaims copyright to this source code.  In place of
81583 ** a legal notice, here is a blessing:
81584 **
81585 **    May you do good and not evil.
81586 **    May you find forgiveness for yourself and forgive others.
81587 **    May you share freely, never taking more than you give.
81588 **
81589 *************************************************************************
81590 ** An tokenizer for SQL
81591 **
81592 ** This file contains C code that splits an SQL input string up into
81593 ** individual tokens and sends those tokens one-by-one over to the
81594 ** parser for analysis.
81595 **
81596 ** $Id: tokenize.c,v 1.152 2008/09/01 15:52:11 drh Exp $
81597 */
81598
81599 /*
81600 ** The charMap() macro maps alphabetic characters into their
81601 ** lower-case ASCII equivalent.  On ASCII machines, this is just
81602 ** an upper-to-lower case map.  On EBCDIC machines we also need
81603 ** to adjust the encoding.  Only alphabetic characters and underscores
81604 ** need to be translated.
81605 */
81606 #ifdef SQLITE_ASCII
81607 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
81608 #endif
81609 #ifdef SQLITE_EBCDIC
81610 # define charMap(X) ebcdicToAscii[(unsigned char)X]
81611 const unsigned char ebcdicToAscii[] = {
81612 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
81613    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
81614    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
81615    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
81616    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
81617    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
81618    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
81619    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
81620    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
81621    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
81622    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
81623    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
81624    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
81625    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
81626    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
81627    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
81628    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
81629 };
81630 #endif
81631
81632 /*
81633 ** The sqlite3KeywordCode function looks up an identifier to determine if
81634 ** it is a keyword.  If it is a keyword, the token code of that keyword is 
81635 ** returned.  If the input is not a keyword, TK_ID is returned.
81636 **
81637 ** The implementation of this routine was generated by a program,
81638 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
81639 ** The output of the mkkeywordhash.c program is written into a file
81640 ** named keywordhash.h and then included into this source file by
81641 ** the #include below.
81642 */
81643 /************** Include keywordhash.h in the middle of tokenize.c ************/
81644 /************** Begin file keywordhash.h *************************************/
81645 /***** This file contains automatically generated code ******
81646 **
81647 ** The code in this file has been automatically generated by
81648 **
81649 **     $Header: /sqlite/sqlite/tool/mkkeywordhash.c,v 1.31 2007/07/30 18:26:20 rse Exp $
81650 **
81651 ** The code in this file implements a function that determines whether
81652 ** or not a given identifier is really an SQL keyword.  The same thing
81653 ** might be implemented more directly using a hand-written hash table.
81654 ** But by using this automatically generated code, the size of the code
81655 ** is substantially reduced.  This is important for embedded applications
81656 ** on platforms with limited memory.
81657 */
81658 /* Hash score: 165 */
81659 static int keywordCode(const char *z, int n){
81660   /* zText[] encodes 775 bytes of keywords in 526 bytes */
81661   static const char zText[526] =
81662     "BEFOREIGNOREGEXPLAINSTEADDESCAPEACHECKEYCONSTRAINTERSECTABLEFT"
81663     "HENDATABASELECTRANSACTIONATURALTERAISELSEXCEPTRIGGEREFERENCES"
81664     "UNIQUERYATTACHAVINGROUPDATEMPORARYBEGINNEREINDEXCLUSIVEXISTSBETWEEN"
81665     "OTNULLIKECASCADEFERRABLECASECOLLATECREATECURRENT_DATEDELETEDETACH"
81666     "IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN"
81667     "WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICT"
81668     "CROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOB"
81669     "YIFINTOFFSETISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUM"
81670     "VIEWINITIALLY";
81671   static const unsigned char aHash[127] = {
81672       63,  92, 109,  61,   0,  38,   0,   0,  69,   0,  64,   0,   0,
81673      102,   4,  65,   7,   0, 108,  72, 103,  99,   0,  22,   0,   0,
81674      113,   0, 111, 106,   0,  18,  80,   0,   1,   0,   0,  56,  57,
81675        0,  55,  11,   0,  33,  77,  89,   0, 110,  88,   0,   0,  45,
81676        0,  90,  54,   0,  20,   0, 114,  34,  19,   0,  10,  97,  28,
81677       83,   0,   0, 116,  93,  47, 115,  41,  12,  44,   0,  78,   0,
81678       87,  29,   0,  86,   0,   0,   0,  82,  79,  84,  75,  96,   6,
81679       14,  95,   0,  68,   0,  21,  76,  98,  27,   0, 112,  67, 104,
81680       49,  40,  71,   0,   0,  81, 100,   0, 107,   0,  15,   0,   0,
81681       24,   0,  73,  42,  50,   0,  16,  48,   0,  37,
81682   };
81683   static const unsigned char aNext[116] = {
81684        0,   0,   0,   0,   0,   0,   0,   0,   0,   9,   0,   0,   0,
81685        0,   0,   0,   0,   5,   0,   0,   0,   0,   0,   0,   0,   0,
81686        0,   0,   0,   0,   0,   0,   0,   0,   0,   0,  32,   0,   0,
81687       17,   0,   0,   0,  36,  39,   0,   0,  25,   0,   0,  31,   0,
81688        0,   0,  43,  52,   0,   0,   0,  53,   0,   0,   0,   0,   0,
81689        0,   0,   0,   0,  51,   0,   0,   0,   0,  26,   0,   8,  46,
81690        2,   0,   0,   0,   0,   0,   0,   0,   3,  58,  66,   0,  13,
81691        0,  91,  85,   0,  94,   0,  74,   0,   0,  62,   0,  35, 101,
81692        0,   0, 105,  23,  30,  60,  70,   0,   0,  59,   0,   0,
81693   };
81694   static const unsigned char aLen[116] = {
81695        6,   7,   3,   6,   6,   7,   7,   3,   4,   6,   4,   5,   3,
81696       10,   9,   5,   4,   4,   3,   8,   2,   6,  11,   2,   7,   5,
81697        5,   4,   6,   7,  10,   6,   5,   6,   6,   5,   6,   4,   9,
81698        2,   5,   5,   7,   5,   9,   6,   7,   7,   3,   4,   4,   7,
81699        3,  10,   4,   7,   6,  12,   6,   6,   9,   4,   6,   5,   4,
81700        7,   6,   5,   6,   7,   5,   4,   5,   6,   5,   7,   3,   7,
81701       13,   2,   2,   4,   6,   6,   8,   5,  17,  12,   7,   8,   8,
81702        2,   4,   4,   4,   4,   4,   2,   2,   4,   6,   2,   3,   6,
81703        5,   8,   5,   5,   8,   3,   5,   5,   6,   4,   9,   3,
81704   };
81705   static const unsigned short int aOffset[116] = {
81706        0,   2,   2,   6,  10,  13,  18,  23,  25,  26,  31,  33,  37,
81707       40,  47,  55,  58,  61,  63,  65,  70,  71,  76,  85,  86,  91,
81708       95,  99, 102, 107, 113, 123, 126, 131, 136, 141, 144, 148, 148,
81709      152, 157, 160, 164, 166, 169, 177, 183, 189, 189, 192, 195, 199,
81710      200, 204, 214, 218, 225, 231, 243, 249, 255, 264, 266, 272, 277,
81711      279, 286, 291, 296, 302, 308, 313, 317, 320, 326, 330, 337, 339,
81712      346, 348, 350, 359, 363, 369, 375, 383, 388, 388, 404, 411, 418,
81713      419, 426, 430, 434, 438, 442, 445, 447, 449, 452, 452, 455, 458,
81714      464, 468, 476, 480, 485, 493, 496, 501, 506, 512, 516, 521,
81715   };
81716   static const unsigned char aCode[116] = {
81717     TK_BEFORE,     TK_FOREIGN,    TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    
81718     TK_EXPLAIN,    TK_INSTEAD,    TK_ADD,        TK_DESC,       TK_ESCAPE,     
81719     TK_EACH,       TK_CHECK,      TK_KEY,        TK_CONSTRAINT, TK_INTERSECT,  
81720     TK_TABLE,      TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DATABASE,   
81721     TK_AS,         TK_SELECT,     TK_TRANSACTION,TK_ON,         TK_JOIN_KW,    
81722     TK_ALTER,      TK_RAISE,      TK_ELSE,       TK_EXCEPT,     TK_TRIGGER,    
81723     TK_REFERENCES, TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,     
81724     TK_GROUP,      TK_UPDATE,     TK_TEMP,       TK_TEMP,       TK_OR,         
81725     TK_BEGIN,      TK_JOIN_KW,    TK_REINDEX,    TK_INDEX,      TK_EXCLUSIVE,  
81726     TK_EXISTS,     TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NULL,       
81727     TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DEFERRABLE, TK_CASE,       
81728     TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DELETE,     TK_DETACH,     
81729     TK_IMMEDIATE,  TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       
81730     TK_ANALYZE,    TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    
81731     TK_LIMIT,      TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      
81732     TK_REPLACE,    TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         
81733     TK_IN,         TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   
81734     TK_JOIN_KW,    TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   
81735     TK_DISTINCT,   TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       
81736     TK_JOIN_KW,    TK_LIKE_KW,    TK_BY,         TK_IF,         TK_INTO,       
81737     TK_OFFSET,     TK_OF,         TK_SET,        TK_ISNULL,     TK_ORDER,      
81738     TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        
81739     TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  
81740     TK_ALL,        
81741   };
81742   int h, i;
81743   if( n<2 ) return TK_ID;
81744   h = ((charMap(z[0])*4) ^
81745       (charMap(z[n-1])*3) ^
81746       n) % 127;
81747   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
81748     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
81749       return aCode[i];
81750     }
81751   }
81752   return TK_ID;
81753 }
81754 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
81755   return keywordCode((char*)z, n);
81756 }
81757
81758 /************** End of keywordhash.h *****************************************/
81759 /************** Continuing where we left off in tokenize.c *******************/
81760
81761
81762 /*
81763 ** If X is a character that can be used in an identifier then
81764 ** IdChar(X) will be true.  Otherwise it is false.
81765 **
81766 ** For ASCII, any character with the high-order bit set is
81767 ** allowed in an identifier.  For 7-bit characters, 
81768 ** sqlite3IsIdChar[X] must be 1.
81769 **
81770 ** For EBCDIC, the rules are more complex but have the same
81771 ** end result.
81772 **
81773 ** Ticket #1066.  the SQL standard does not allow '$' in the
81774 ** middle of identfiers.  But many SQL implementations do. 
81775 ** SQLite will allow '$' in identifiers for compatibility.
81776 ** But the feature is undocumented.
81777 */
81778 #ifdef SQLITE_ASCII
81779 SQLITE_PRIVATE const char sqlite3IsAsciiIdChar[] = {
81780 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
81781     0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
81782     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
81783     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
81784     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
81785     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
81786     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
81787 };
81788 #define IdChar(C)  (((c=C)&0x80)!=0 || (c>0x1f && sqlite3IsAsciiIdChar[c-0x20]))
81789 #endif
81790 #ifdef SQLITE_EBCDIC
81791 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
81792 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
81793     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
81794     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
81795     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
81796     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
81797     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
81798     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
81799     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
81800     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
81801     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
81802     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
81803     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
81804     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
81805 };
81806 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
81807 #endif
81808
81809
81810 /*
81811 ** Return the length of the token that begins at z[0]. 
81812 ** Store the token type in *tokenType before returning.
81813 */
81814 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
81815   int i, c;
81816   switch( *z ){
81817     case ' ': case '\t': case '\n': case '\f': case '\r': {
81818       for(i=1; isspace(z[i]); i++){}
81819       *tokenType = TK_SPACE;
81820       return i;
81821     }
81822     case '-': {
81823       if( z[1]=='-' ){
81824         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
81825         *tokenType = TK_SPACE;
81826         return i;
81827       }
81828       *tokenType = TK_MINUS;
81829       return 1;
81830     }
81831     case '(': {
81832       *tokenType = TK_LP;
81833       return 1;
81834     }
81835     case ')': {
81836       *tokenType = TK_RP;
81837       return 1;
81838     }
81839     case ';': {
81840       *tokenType = TK_SEMI;
81841       return 1;
81842     }
81843     case '+': {
81844       *tokenType = TK_PLUS;
81845       return 1;
81846     }
81847     case '*': {
81848       *tokenType = TK_STAR;
81849       return 1;
81850     }
81851     case '/': {
81852       if( z[1]!='*' || z[2]==0 ){
81853         *tokenType = TK_SLASH;
81854         return 1;
81855       }
81856       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
81857       if( c ) i++;
81858       *tokenType = TK_SPACE;
81859       return i;
81860     }
81861     case '%': {
81862       *tokenType = TK_REM;
81863       return 1;
81864     }
81865     case '=': {
81866       *tokenType = TK_EQ;
81867       return 1 + (z[1]=='=');
81868     }
81869     case '<': {
81870       if( (c=z[1])=='=' ){
81871         *tokenType = TK_LE;
81872         return 2;
81873       }else if( c=='>' ){
81874         *tokenType = TK_NE;
81875         return 2;
81876       }else if( c=='<' ){
81877         *tokenType = TK_LSHIFT;
81878         return 2;
81879       }else{
81880         *tokenType = TK_LT;
81881         return 1;
81882       }
81883     }
81884     case '>': {
81885       if( (c=z[1])=='=' ){
81886         *tokenType = TK_GE;
81887         return 2;
81888       }else if( c=='>' ){
81889         *tokenType = TK_RSHIFT;
81890         return 2;
81891       }else{
81892         *tokenType = TK_GT;
81893         return 1;
81894       }
81895     }
81896     case '!': {
81897       if( z[1]!='=' ){
81898         *tokenType = TK_ILLEGAL;
81899         return 2;
81900       }else{
81901         *tokenType = TK_NE;
81902         return 2;
81903       }
81904     }
81905     case '|': {
81906       if( z[1]!='|' ){
81907         *tokenType = TK_BITOR;
81908         return 1;
81909       }else{
81910         *tokenType = TK_CONCAT;
81911         return 2;
81912       }
81913     }
81914     case ',': {
81915       *tokenType = TK_COMMA;
81916       return 1;
81917     }
81918     case '&': {
81919       *tokenType = TK_BITAND;
81920       return 1;
81921     }
81922     case '~': {
81923       *tokenType = TK_BITNOT;
81924       return 1;
81925     }
81926     case '`':
81927     case '\'':
81928     case '"': {
81929       int delim = z[0];
81930       for(i=1; (c=z[i])!=0; i++){
81931         if( c==delim ){
81932           if( z[i+1]==delim ){
81933             i++;
81934           }else{
81935             break;
81936           }
81937         }
81938       }
81939       if( c=='\'' ){
81940         *tokenType = TK_STRING;
81941         return i+1;
81942       }else if( c!=0 ){
81943         *tokenType = TK_ID;
81944         return i+1;
81945       }else{
81946         *tokenType = TK_ILLEGAL;
81947         return i;
81948       }
81949     }
81950     case '.': {
81951 #ifndef SQLITE_OMIT_FLOATING_POINT
81952       if( !isdigit(z[1]) )
81953 #endif
81954       {
81955         *tokenType = TK_DOT;
81956         return 1;
81957       }
81958       /* If the next character is a digit, this is a floating point
81959       ** number that begins with ".".  Fall thru into the next case */
81960     }
81961     case '0': case '1': case '2': case '3': case '4':
81962     case '5': case '6': case '7': case '8': case '9': {
81963       *tokenType = TK_INTEGER;
81964       for(i=0; isdigit(z[i]); i++){}
81965 #ifndef SQLITE_OMIT_FLOATING_POINT
81966       if( z[i]=='.' ){
81967         i++;
81968         while( isdigit(z[i]) ){ i++; }
81969         *tokenType = TK_FLOAT;
81970       }
81971       if( (z[i]=='e' || z[i]=='E') &&
81972            ( isdigit(z[i+1]) 
81973             || ((z[i+1]=='+' || z[i+1]=='-') && isdigit(z[i+2]))
81974            )
81975       ){
81976         i += 2;
81977         while( isdigit(z[i]) ){ i++; }
81978         *tokenType = TK_FLOAT;
81979       }
81980 #endif
81981       while( IdChar(z[i]) ){
81982         *tokenType = TK_ILLEGAL;
81983         i++;
81984       }
81985       return i;
81986     }
81987     case '[': {
81988       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
81989       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
81990       return i;
81991     }
81992     case '?': {
81993       *tokenType = TK_VARIABLE;
81994       for(i=1; isdigit(z[i]); i++){}
81995       return i;
81996     }
81997     case '#': {
81998       for(i=1; isdigit(z[i]); i++){}
81999       if( i>1 ){
82000         /* Parameters of the form #NNN (where NNN is a number) are used
82001         ** internally by sqlite3NestedParse.  */
82002         *tokenType = TK_REGISTER;
82003         return i;
82004       }
82005       /* Fall through into the next case if the '#' is not followed by
82006       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
82007     }
82008 #ifndef SQLITE_OMIT_TCL_VARIABLE
82009     case '$':
82010 #endif
82011     case '@':  /* For compatibility with MS SQL Server */
82012     case ':': {
82013       int n = 0;
82014       *tokenType = TK_VARIABLE;
82015       for(i=1; (c=z[i])!=0; i++){
82016         if( IdChar(c) ){
82017           n++;
82018 #ifndef SQLITE_OMIT_TCL_VARIABLE
82019         }else if( c=='(' && n>0 ){
82020           do{
82021             i++;
82022           }while( (c=z[i])!=0 && !isspace(c) && c!=')' );
82023           if( c==')' ){
82024             i++;
82025           }else{
82026             *tokenType = TK_ILLEGAL;
82027           }
82028           break;
82029         }else if( c==':' && z[i+1]==':' ){
82030           i++;
82031 #endif
82032         }else{
82033           break;
82034         }
82035       }
82036       if( n==0 ) *tokenType = TK_ILLEGAL;
82037       return i;
82038     }
82039 #ifndef SQLITE_OMIT_BLOB_LITERAL
82040     case 'x': case 'X': {
82041       if( z[1]=='\'' ){
82042         *tokenType = TK_BLOB;
82043         for(i=2; (c=z[i])!=0 && c!='\''; i++){
82044           if( !isxdigit(c) ){
82045             *tokenType = TK_ILLEGAL;
82046           }
82047         }
82048         if( i%2 || !c ) *tokenType = TK_ILLEGAL;
82049         if( c ) i++;
82050         return i;
82051       }
82052       /* Otherwise fall through to the next case */
82053     }
82054 #endif
82055     default: {
82056       if( !IdChar(*z) ){
82057         break;
82058       }
82059       for(i=1; IdChar(z[i]); i++){}
82060       *tokenType = keywordCode((char*)z, i);
82061       return i;
82062     }
82063   }
82064   *tokenType = TK_ILLEGAL;
82065   return 1;
82066 }
82067
82068 /*
82069 ** Run the parser on the given SQL string.  The parser structure is
82070 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
82071 ** then an and attempt is made to write an error message into 
82072 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
82073 ** error message.
82074 */
82075 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
82076   int nErr = 0;
82077   int i;
82078   void *pEngine;
82079   int tokenType;
82080   int lastTokenParsed = -1;
82081   sqlite3 *db = pParse->db;
82082   int mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
82083
82084   if( db->activeVdbeCnt==0 ){
82085     db->u1.isInterrupted = 0;
82086   }
82087   pParse->rc = SQLITE_OK;
82088   pParse->zTail = pParse->zSql = zSql;
82089   i = 0;
82090   assert( pzErrMsg!=0 );
82091   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
82092   if( pEngine==0 ){
82093     db->mallocFailed = 1;
82094     return SQLITE_NOMEM;
82095   }
82096   assert( pParse->sLastToken.dyn==0 );
82097   assert( pParse->pNewTable==0 );
82098   assert( pParse->pNewTrigger==0 );
82099   assert( pParse->nVar==0 );
82100   assert( pParse->nVarExpr==0 );
82101   assert( pParse->nVarExprAlloc==0 );
82102   assert( pParse->apVarExpr==0 );
82103   while( !db->mallocFailed && zSql[i]!=0 ){
82104     assert( i>=0 );
82105     pParse->sLastToken.z = (u8*)&zSql[i];
82106     assert( pParse->sLastToken.dyn==0 );
82107     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
82108     i += pParse->sLastToken.n;
82109     if( i>mxSqlLen ){
82110       pParse->rc = SQLITE_TOOBIG;
82111       break;
82112     }
82113     switch( tokenType ){
82114       case TK_SPACE: {
82115         if( db->u1.isInterrupted ){
82116           pParse->rc = SQLITE_INTERRUPT;
82117           sqlite3SetString(pzErrMsg, db, "interrupt");
82118           goto abort_parse;
82119         }
82120         break;
82121       }
82122       case TK_ILLEGAL: {
82123         sqlite3DbFree(db, *pzErrMsg);
82124         *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
82125                         &pParse->sLastToken);
82126         nErr++;
82127         goto abort_parse;
82128       }
82129       case TK_SEMI: {
82130         pParse->zTail = &zSql[i];
82131         /* Fall thru into the default case */
82132       }
82133       default: {
82134         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
82135         lastTokenParsed = tokenType;
82136         if( pParse->rc!=SQLITE_OK ){
82137           goto abort_parse;
82138         }
82139         break;
82140       }
82141     }
82142   }
82143 abort_parse:
82144   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
82145     if( lastTokenParsed!=TK_SEMI ){
82146       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
82147       pParse->zTail = &zSql[i];
82148     }
82149     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
82150   }
82151 #ifdef YYTRACKMAXSTACKDEPTH
82152   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
82153       sqlite3ParserStackPeak(pEngine)
82154   );
82155 #endif /* YYDEBUG */
82156   sqlite3ParserFree(pEngine, sqlite3_free);
82157   if( db->mallocFailed ){
82158     pParse->rc = SQLITE_NOMEM;
82159   }
82160   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
82161     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
82162   }
82163   if( pParse->zErrMsg ){
82164     if( *pzErrMsg==0 ){
82165       *pzErrMsg = pParse->zErrMsg;
82166     }else{
82167       sqlite3DbFree(db, pParse->zErrMsg);
82168     }
82169     pParse->zErrMsg = 0;
82170     nErr++;
82171   }
82172   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
82173     sqlite3VdbeDelete(pParse->pVdbe);
82174     pParse->pVdbe = 0;
82175   }
82176 #ifndef SQLITE_OMIT_SHARED_CACHE
82177   if( pParse->nested==0 ){
82178     sqlite3DbFree(db, pParse->aTableLock);
82179     pParse->aTableLock = 0;
82180     pParse->nTableLock = 0;
82181   }
82182 #endif
82183 #ifndef SQLITE_OMIT_VIRTUALTABLE
82184   sqlite3DbFree(db, pParse->apVtabLock);
82185 #endif
82186
82187   if( !IN_DECLARE_VTAB ){
82188     /* If the pParse->declareVtab flag is set, do not delete any table 
82189     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
82190     ** will take responsibility for freeing the Table structure.
82191     */
82192     sqlite3DeleteTable(pParse->pNewTable);
82193   }
82194
82195   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
82196   sqlite3DbFree(db, pParse->apVarExpr);
82197   sqlite3DbFree(db, pParse->aAlias);
82198   while( pParse->pZombieTab ){
82199     Table *p = pParse->pZombieTab;
82200     pParse->pZombieTab = p->pNextZombie;
82201     sqlite3DeleteTable(p);
82202   }
82203   if( nErr>0 && (pParse->rc==SQLITE_OK || pParse->rc==SQLITE_DONE) ){
82204     pParse->rc = SQLITE_ERROR;
82205   }
82206   return nErr;
82207 }
82208
82209 /************** End of tokenize.c ********************************************/
82210 /************** Begin file complete.c ****************************************/
82211 /*
82212 ** 2001 September 15
82213 **
82214 ** The author disclaims copyright to this source code.  In place of
82215 ** a legal notice, here is a blessing:
82216 **
82217 **    May you do good and not evil.
82218 **    May you find forgiveness for yourself and forgive others.
82219 **    May you share freely, never taking more than you give.
82220 **
82221 *************************************************************************
82222 ** An tokenizer for SQL
82223 **
82224 ** This file contains C code that implements the sqlite3_complete() API.
82225 ** This code used to be part of the tokenizer.c source file.  But by
82226 ** separating it out, the code will be automatically omitted from
82227 ** static links that do not use it.
82228 **
82229 ** $Id: complete.c,v 1.7 2008/06/13 18:24:27 drh Exp $
82230 */
82231 #ifndef SQLITE_OMIT_COMPLETE
82232
82233 /*
82234 ** This is defined in tokenize.c.  We just have to import the definition.
82235 */
82236 #ifndef SQLITE_AMALGAMATION
82237 #ifdef SQLITE_ASCII
82238 SQLITE_PRIVATE const char sqlite3IsAsciiIdChar[];
82239 #define IdChar(C)  (((c=C)&0x80)!=0 || (c>0x1f && sqlite3IsAsciiIdChar[c-0x20]))
82240 #endif
82241 #ifdef SQLITE_EBCDIC
82242 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
82243 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
82244 #endif
82245 #endif /* SQLITE_AMALGAMATION */
82246
82247
82248 /*
82249 ** Token types used by the sqlite3_complete() routine.  See the header
82250 ** comments on that procedure for additional information.
82251 */
82252 #define tkSEMI    0
82253 #define tkWS      1
82254 #define tkOTHER   2
82255 #define tkEXPLAIN 3
82256 #define tkCREATE  4
82257 #define tkTEMP    5
82258 #define tkTRIGGER 6
82259 #define tkEND     7
82260
82261 /*
82262 ** Return TRUE if the given SQL string ends in a semicolon.
82263 **
82264 ** Special handling is require for CREATE TRIGGER statements.
82265 ** Whenever the CREATE TRIGGER keywords are seen, the statement
82266 ** must end with ";END;".
82267 **
82268 ** This implementation uses a state machine with 7 states:
82269 **
82270 **   (0) START     At the beginning or end of an SQL statement.  This routine
82271 **                 returns 1 if it ends in the START state and 0 if it ends
82272 **                 in any other state.
82273 **
82274 **   (1) NORMAL    We are in the middle of statement which ends with a single
82275 **                 semicolon.
82276 **
82277 **   (2) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
82278 **                 a statement.
82279 **
82280 **   (3) CREATE    The keyword CREATE has been seen at the beginning of a
82281 **                 statement, possibly preceeded by EXPLAIN and/or followed by
82282 **                 TEMP or TEMPORARY
82283 **
82284 **   (4) TRIGGER   We are in the middle of a trigger definition that must be
82285 **                 ended by a semicolon, the keyword END, and another semicolon.
82286 **
82287 **   (5) SEMI      We've seen the first semicolon in the ";END;" that occurs at
82288 **                 the end of a trigger definition.
82289 **
82290 **   (6) END       We've seen the ";END" of the ";END;" that occurs at the end
82291 **                 of a trigger difinition.
82292 **
82293 ** Transitions between states above are determined by tokens extracted
82294 ** from the input.  The following tokens are significant:
82295 **
82296 **   (0) tkSEMI      A semicolon.
82297 **   (1) tkWS        Whitespace
82298 **   (2) tkOTHER     Any other SQL token.
82299 **   (3) tkEXPLAIN   The "explain" keyword.
82300 **   (4) tkCREATE    The "create" keyword.
82301 **   (5) tkTEMP      The "temp" or "temporary" keyword.
82302 **   (6) tkTRIGGER   The "trigger" keyword.
82303 **   (7) tkEND       The "end" keyword.
82304 **
82305 ** Whitespace never causes a state transition and is always ignored.
82306 **
82307 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
82308 ** to recognize the end of a trigger can be omitted.  All we have to do
82309 ** is look for a semicolon that is not part of an string or comment.
82310 */
82311 SQLITE_API int sqlite3_complete(const char *zSql){
82312   u8 state = 0;   /* Current state, using numbers defined in header comment */
82313   u8 token;       /* Value of the next token */
82314
82315 #ifndef SQLITE_OMIT_TRIGGER
82316   /* A complex statement machine used to detect the end of a CREATE TRIGGER
82317   ** statement.  This is the normal case.
82318   */
82319   static const u8 trans[7][8] = {
82320                      /* Token:                                                */
82321      /* State:       **  SEMI  WS  OTHER EXPLAIN  CREATE  TEMP  TRIGGER  END  */
82322      /* 0   START: */ {    0,  0,     1,      2,      3,    1,       1,   1,  },
82323      /* 1  NORMAL: */ {    0,  1,     1,      1,      1,    1,       1,   1,  },
82324      /* 2 EXPLAIN: */ {    0,  2,     1,      1,      3,    1,       1,   1,  },
82325      /* 3  CREATE: */ {    0,  3,     1,      1,      1,    3,       4,   1,  },
82326      /* 4 TRIGGER: */ {    5,  4,     4,      4,      4,    4,       4,   4,  },
82327      /* 5    SEMI: */ {    5,  5,     4,      4,      4,    4,       4,   6,  },
82328      /* 6     END: */ {    0,  6,     4,      4,      4,    4,       4,   4,  },
82329   };
82330 #else
82331   /* If triggers are not suppored by this compile then the statement machine
82332   ** used to detect the end of a statement is much simplier
82333   */
82334   static const u8 trans[2][3] = {
82335                      /* Token:           */
82336      /* State:       **  SEMI  WS  OTHER */
82337      /* 0   START: */ {    0,  0,     1, },
82338      /* 1  NORMAL: */ {    0,  1,     1, },
82339   };
82340 #endif /* SQLITE_OMIT_TRIGGER */
82341
82342   while( *zSql ){
82343     switch( *zSql ){
82344       case ';': {  /* A semicolon */
82345         token = tkSEMI;
82346         break;
82347       }
82348       case ' ':
82349       case '\r':
82350       case '\t':
82351       case '\n':
82352       case '\f': {  /* White space is ignored */
82353         token = tkWS;
82354         break;
82355       }
82356       case '/': {   /* C-style comments */
82357         if( zSql[1]!='*' ){
82358           token = tkOTHER;
82359           break;
82360         }
82361         zSql += 2;
82362         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
82363         if( zSql[0]==0 ) return 0;
82364         zSql++;
82365         token = tkWS;
82366         break;
82367       }
82368       case '-': {   /* SQL-style comments from "--" to end of line */
82369         if( zSql[1]!='-' ){
82370           token = tkOTHER;
82371           break;
82372         }
82373         while( *zSql && *zSql!='\n' ){ zSql++; }
82374         if( *zSql==0 ) return state==0;
82375         token = tkWS;
82376         break;
82377       }
82378       case '[': {   /* Microsoft-style identifiers in [...] */
82379         zSql++;
82380         while( *zSql && *zSql!=']' ){ zSql++; }
82381         if( *zSql==0 ) return 0;
82382         token = tkOTHER;
82383         break;
82384       }
82385       case '`':     /* Grave-accent quoted symbols used by MySQL */
82386       case '"':     /* single- and double-quoted strings */
82387       case '\'': {
82388         int c = *zSql;
82389         zSql++;
82390         while( *zSql && *zSql!=c ){ zSql++; }
82391         if( *zSql==0 ) return 0;
82392         token = tkOTHER;
82393         break;
82394       }
82395       default: {
82396         int c;
82397         if( IdChar((u8)*zSql) ){
82398           /* Keywords and unquoted identifiers */
82399           int nId;
82400           for(nId=1; IdChar(zSql[nId]); nId++){}
82401 #ifdef SQLITE_OMIT_TRIGGER
82402           token = tkOTHER;
82403 #else
82404           switch( *zSql ){
82405             case 'c': case 'C': {
82406               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
82407                 token = tkCREATE;
82408               }else{
82409                 token = tkOTHER;
82410               }
82411               break;
82412             }
82413             case 't': case 'T': {
82414               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
82415                 token = tkTRIGGER;
82416               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
82417                 token = tkTEMP;
82418               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
82419                 token = tkTEMP;
82420               }else{
82421                 token = tkOTHER;
82422               }
82423               break;
82424             }
82425             case 'e':  case 'E': {
82426               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
82427                 token = tkEND;
82428               }else
82429 #ifndef SQLITE_OMIT_EXPLAIN
82430               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
82431                 token = tkEXPLAIN;
82432               }else
82433 #endif
82434               {
82435                 token = tkOTHER;
82436               }
82437               break;
82438             }
82439             default: {
82440               token = tkOTHER;
82441               break;
82442             }
82443           }
82444 #endif /* SQLITE_OMIT_TRIGGER */
82445           zSql += nId-1;
82446         }else{
82447           /* Operators and special symbols */
82448           token = tkOTHER;
82449         }
82450         break;
82451       }
82452     }
82453     state = trans[state][token];
82454     zSql++;
82455   }
82456   return state==0;
82457 }
82458
82459 #ifndef SQLITE_OMIT_UTF16
82460 /*
82461 ** This routine is the same as the sqlite3_complete() routine described
82462 ** above, except that the parameter is required to be UTF-16 encoded, not
82463 ** UTF-8.
82464 */
82465 SQLITE_API int sqlite3_complete16(const void *zSql){
82466   sqlite3_value *pVal;
82467   char const *zSql8;
82468   int rc = SQLITE_NOMEM;
82469
82470 #ifndef SQLITE_OMIT_AUTOINIT
82471   rc = sqlite3_initialize();
82472   if( rc ) return rc;
82473 #endif
82474   pVal = sqlite3ValueNew(0);
82475   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
82476   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
82477   if( zSql8 ){
82478     rc = sqlite3_complete(zSql8);
82479   }else{
82480     rc = SQLITE_NOMEM;
82481   }
82482   sqlite3ValueFree(pVal);
82483   return sqlite3ApiExit(0, rc);
82484 }
82485 #endif /* SQLITE_OMIT_UTF16 */
82486 #endif /* SQLITE_OMIT_COMPLETE */
82487
82488 /************** End of complete.c ********************************************/
82489 /************** Begin file main.c ********************************************/
82490 /*
82491 ** 2001 September 15
82492 **
82493 ** The author disclaims copyright to this source code.  In place of
82494 ** a legal notice, here is a blessing:
82495 **
82496 **    May you do good and not evil.
82497 **    May you find forgiveness for yourself and forgive others.
82498 **    May you share freely, never taking more than you give.
82499 **
82500 *************************************************************************
82501 ** Main file for the SQLite library.  The routines in this file
82502 ** implement the programmer interface to the library.  Routines in
82503 ** other files are for internal use by SQLite and should not be
82504 ** accessed by users of the library.
82505 **
82506 ** $Id: main.c,v 1.500 2008/09/08 08:08:09 danielk1977 Exp $
82507 */
82508
82509 #ifdef SQLITE_ENABLE_FTS3
82510 /************** Include fts3.h in the middle of main.c ***********************/
82511 /************** Begin file fts3.h ********************************************/
82512 /*
82513 ** 2006 Oct 10
82514 **
82515 ** The author disclaims copyright to this source code.  In place of
82516 ** a legal notice, here is a blessing:
82517 **
82518 **    May you do good and not evil.
82519 **    May you find forgiveness for yourself and forgive others.
82520 **    May you share freely, never taking more than you give.
82521 **
82522 ******************************************************************************
82523 **
82524 ** This header file is used by programs that want to link against the
82525 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
82526 */
82527
82528 #if 0
82529 extern "C" {
82530 #endif  /* __cplusplus */
82531
82532 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
82533
82534 #if 0
82535 }  /* extern "C" */
82536 #endif  /* __cplusplus */
82537
82538 /************** End of fts3.h ************************************************/
82539 /************** Continuing where we left off in main.c ***********************/
82540 #endif
82541 #ifdef SQLITE_ENABLE_RTREE
82542 /************** Include rtree.h in the middle of main.c **********************/
82543 /************** Begin file rtree.h *******************************************/
82544 /*
82545 ** 2008 May 26
82546 **
82547 ** The author disclaims copyright to this source code.  In place of
82548 ** a legal notice, here is a blessing:
82549 **
82550 **    May you do good and not evil.
82551 **    May you find forgiveness for yourself and forgive others.
82552 **    May you share freely, never taking more than you give.
82553 **
82554 ******************************************************************************
82555 **
82556 ** This header file is used by programs that want to link against the
82557 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
82558 */
82559
82560 #if 0
82561 extern "C" {
82562 #endif  /* __cplusplus */
82563
82564 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
82565
82566 #if 0
82567 }  /* extern "C" */
82568 #endif  /* __cplusplus */
82569
82570 /************** End of rtree.h ***********************************************/
82571 /************** Continuing where we left off in main.c ***********************/
82572 #endif
82573 #ifdef SQLITE_ENABLE_ICU
82574 /************** Include sqliteicu.h in the middle of main.c ******************/
82575 /************** Begin file sqliteicu.h ***************************************/
82576 /*
82577 ** 2008 May 26
82578 **
82579 ** The author disclaims copyright to this source code.  In place of
82580 ** a legal notice, here is a blessing:
82581 **
82582 **    May you do good and not evil.
82583 **    May you find forgiveness for yourself and forgive others.
82584 **    May you share freely, never taking more than you give.
82585 **
82586 ******************************************************************************
82587 **
82588 ** This header file is used by programs that want to link against the
82589 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
82590 */
82591
82592 #if 0
82593 extern "C" {
82594 #endif  /* __cplusplus */
82595
82596 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
82597
82598 #if 0
82599 }  /* extern "C" */
82600 #endif  /* __cplusplus */
82601
82602
82603 /************** End of sqliteicu.h *******************************************/
82604 /************** Continuing where we left off in main.c ***********************/
82605 #endif
82606
82607 /*
82608 ** The version of the library
82609 */
82610 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
82611 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
82612 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
82613 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
82614
82615 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
82616 /*
82617 ** If the following function pointer is not NULL and if
82618 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
82619 ** I/O active are written using this function.  These messages
82620 ** are intended for debugging activity only.
82621 */
82622 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
82623 #endif
82624
82625 /*
82626 ** If the following global variable points to a string which is the
82627 ** name of a directory, then that directory will be used to store
82628 ** temporary files.
82629 **
82630 ** See also the "PRAGMA temp_store_directory" SQL command.
82631 */
82632 SQLITE_API char *sqlite3_temp_directory = 0;
82633
82634 /*
82635 ** Initialize SQLite.  
82636 **
82637 ** This routine must be called to initialize the memory allocation,
82638 ** VFS, and mutex subsystems prior to doing any serious work with
82639 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
82640 ** this routine will be called automatically by key routines such as
82641 ** sqlite3_open().  
82642 **
82643 ** This routine is a no-op except on its very first call for the process,
82644 ** or for the first call after a call to sqlite3_shutdown.
82645 **
82646 ** The first thread to call this routine runs the initialization to
82647 ** completion.  If subsequent threads call this routine before the first
82648 ** thread has finished the initialization process, then the subsequent
82649 ** threads must block until the first thread finishes with the initialization.
82650 **
82651 ** The first thread might call this routine recursively.  Recursive
82652 ** calls to this routine should not block, of course.  Otherwise the
82653 ** initialization process would never complete.
82654 **
82655 ** Let X be the first thread to enter this routine.  Let Y be some other
82656 ** thread.  Then while the initial invocation of this routine by X is
82657 ** incomplete, it is required that:
82658 **
82659 **    *  Calls to this routine from Y must block until the outer-most
82660 **       call by X completes.
82661 **
82662 **    *  Recursive calls to this routine from thread X return immediately
82663 **       without blocking.
82664 */
82665 SQLITE_API int sqlite3_initialize(void){
82666   sqlite3_mutex *pMaster;                      /* The main static mutex */
82667   int rc;                                      /* Result code */
82668
82669 #ifdef SQLITE_OMIT_WSD
82670   rc = sqlite3_wsd_init(4096, 24);
82671   if( rc!=SQLITE_OK ){
82672     return rc;
82673   }
82674 #endif
82675
82676   /* If SQLite is already completely initialized, then this call
82677   ** to sqlite3_initialize() should be a no-op.  But the initialization
82678   ** must be complete.  So isInit must not be set until the very end
82679   ** of this routine.
82680   */
82681   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
82682
82683   /* Make sure the mutex subsystem is initialized.  If unable to 
82684   ** initialize the mutex subsystem, return early with the error.
82685   ** If the system is so sick that we are unable to allocate a mutex,
82686   ** there is not much SQLite is going to be able to do.
82687   **
82688   ** The mutex subsystem must take care of serializing its own
82689   ** initialization.
82690   */
82691   rc = sqlite3MutexInit();
82692   if( rc ) return rc;
82693
82694   /* Initialize the malloc() system and the recursive pInitMutex mutex.
82695   ** This operation is protected by the STATIC_MASTER mutex.  Note that
82696   ** MutexAlloc() is called for a static mutex prior to initializing the
82697   ** malloc subsystem - this implies that the allocation of a static
82698   ** mutex must not require support from the malloc subsystem.
82699   */
82700   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
82701   sqlite3_mutex_enter(pMaster);
82702   if( !sqlite3GlobalConfig.isMallocInit ){
82703     rc = sqlite3MallocInit();
82704   }
82705   if( rc==SQLITE_OK ){
82706     sqlite3GlobalConfig.isMallocInit = 1;
82707     if( !sqlite3GlobalConfig.pInitMutex ){
82708       sqlite3GlobalConfig.pInitMutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
82709       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
82710         rc = SQLITE_NOMEM;
82711       }
82712     }
82713     sqlite3GlobalConfig.nRefInitMutex++;
82714   }
82715   sqlite3_mutex_leave(pMaster);
82716
82717   /* If unable to initialize the malloc subsystem, then return early.
82718   ** There is little hope of getting SQLite to run if the malloc
82719   ** subsystem cannot be initialized.
82720   */
82721   if( rc!=SQLITE_OK ){
82722     return rc;
82723   }
82724
82725   /* Do the rest of the initialization under the recursive mutex so
82726   ** that we will be able to handle recursive calls into
82727   ** sqlite3_initialize().  The recursive calls normally come through
82728   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
82729   ** recursive calls might also be possible.
82730   */
82731   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
82732   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
82733     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
82734     sqlite3GlobalConfig.inProgress = 1;
82735     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
82736     sqlite3RegisterGlobalFunctions();
82737     rc = sqlite3_os_init();
82738     if( rc==SQLITE_OK ){
82739       rc = sqlite3PcacheInitialize();
82740       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, 
82741           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
82742     }
82743     sqlite3GlobalConfig.inProgress = 0;
82744     sqlite3GlobalConfig.isInit = (rc==SQLITE_OK ? 1 : 0);
82745   }
82746   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
82747
82748   /* Go back under the static mutex and clean up the recursive
82749   ** mutex to prevent a resource leak.
82750   */
82751   sqlite3_mutex_enter(pMaster);
82752   sqlite3GlobalConfig.nRefInitMutex--;
82753   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
82754     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
82755     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
82756     sqlite3GlobalConfig.pInitMutex = 0;
82757   }
82758   sqlite3_mutex_leave(pMaster);
82759
82760   /* The following is just a sanity check to make sure SQLite has
82761   ** been compiled correctly.  It is important to run this code, but
82762   ** we don't want to run it too often and soak up CPU cycles for no
82763   ** reason.  So we run it once during initialization.
82764   */
82765 #ifndef NDEBUG
82766   /* This section of code's only "output" is via assert() statements. */
82767   if ( rc==SQLITE_OK ){
82768     u64 x = (((u64)1)<<63)-1;
82769     double y;
82770     assert(sizeof(x)==8);
82771     assert(sizeof(x)==sizeof(y));
82772     memcpy(&y, &x, 8);
82773     assert( sqlite3IsNaN(y) );
82774   }
82775 #endif
82776
82777   return rc;
82778 }
82779
82780 /*
82781 ** Undo the effects of sqlite3_initialize().  Must not be called while
82782 ** there are outstanding database connections or memory allocations or
82783 ** while any part of SQLite is otherwise in use in any thread.  This
82784 ** routine is not threadsafe.  Not by a long shot.
82785 */
82786 SQLITE_API int sqlite3_shutdown(void){
82787   sqlite3GlobalConfig.isMallocInit = 0;
82788   sqlite3PcacheShutdown();
82789   if( sqlite3GlobalConfig.isInit ){
82790     sqlite3_os_end();
82791   }
82792   if( sqlite3GlobalConfig.m.xShutdown ){
82793     sqlite3MallocEnd();
82794   }
82795   if( sqlite3GlobalConfig.mutex.xMutexEnd ){
82796     sqlite3MutexEnd();
82797   }
82798   sqlite3GlobalConfig.isInit = 0;
82799   return SQLITE_OK;
82800 }
82801
82802 /*
82803 ** This API allows applications to modify the global configuration of
82804 ** the SQLite library at run-time.
82805 **
82806 ** This routine should only be called when there are no outstanding
82807 ** database connections or memory allocations.  This routine is not
82808 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
82809 ** behavior.
82810 */
82811 SQLITE_API int sqlite3_config(int op, ...){
82812   va_list ap;
82813   int rc = SQLITE_OK;
82814
82815   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
82816   ** the SQLite library is in use. */
82817   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE;
82818
82819   va_start(ap, op);
82820   switch( op ){
82821     case SQLITE_CONFIG_SINGLETHREAD: {
82822       /* Disable all mutexing */
82823       sqlite3GlobalConfig.bCoreMutex = 0;
82824       sqlite3GlobalConfig.bFullMutex = 0;
82825       break;
82826     }
82827     case SQLITE_CONFIG_MULTITHREAD: {
82828       /* Disable mutexing of database connections */
82829       /* Enable mutexing of core data structures */
82830       sqlite3GlobalConfig.bCoreMutex = 1;
82831       sqlite3GlobalConfig.bFullMutex = 0;
82832       break;
82833     }
82834     case SQLITE_CONFIG_SERIALIZED: {
82835       /* Enable all mutexing */
82836       sqlite3GlobalConfig.bCoreMutex = 1;
82837       sqlite3GlobalConfig.bFullMutex = 1;
82838       break;
82839     }
82840     case SQLITE_CONFIG_MALLOC: {
82841       /* Specify an alternative malloc implementation */
82842       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
82843       break;
82844     }
82845     case SQLITE_CONFIG_GETMALLOC: {
82846       /* Retrieve the current malloc() implementation */
82847       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
82848       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
82849       break;
82850     }
82851     case SQLITE_CONFIG_MUTEX: {
82852       /* Specify an alternative mutex implementation */
82853       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
82854       break;
82855     }
82856     case SQLITE_CONFIG_GETMUTEX: {
82857       /* Retrieve the current mutex implementation */
82858       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
82859       break;
82860     }
82861     case SQLITE_CONFIG_MEMSTATUS: {
82862       /* Enable or disable the malloc status collection */
82863       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
82864       break;
82865     }
82866     case SQLITE_CONFIG_SCRATCH: {
82867       /* Designate a buffer for scratch memory space */
82868       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
82869       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
82870       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
82871       break;
82872     }
82873     case SQLITE_CONFIG_PAGECACHE: {
82874       /* Designate a buffer for scratch memory space */
82875       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
82876       sqlite3GlobalConfig.szPage = va_arg(ap, int);
82877       sqlite3GlobalConfig.nPage = va_arg(ap, int);
82878       break;
82879     }
82880
82881 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
82882     case SQLITE_CONFIG_HEAP: {
82883       /* Designate a buffer for heap memory space */
82884       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
82885       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
82886       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
82887
82888       if( sqlite3GlobalConfig.pHeap==0 ){
82889         /* If the heap pointer is NULL, then restore the malloc implementation
82890         ** back to NULL pointers too.  This will cause the malloc to go
82891         ** back to its default implementation when sqlite3_initialize() is
82892         ** run.
82893         */
82894         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
82895       }else{
82896         /* The heap pointer is not NULL, then install one of the
82897         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
82898         ** ENABLE_MEMSYS5 is defined, return an error.
82899         ** the default case and return an error.
82900         */
82901 #ifdef SQLITE_ENABLE_MEMSYS3
82902         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
82903 #endif
82904 #ifdef SQLITE_ENABLE_MEMSYS5
82905         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
82906 #endif
82907       }
82908       break;
82909     }
82910 #endif
82911
82912 #if defined(SQLITE_ENABLE_MEMSYS6)
82913     case SQLITE_CONFIG_CHUNKALLOC: {
82914       sqlite3GlobalConfig.nSmall = va_arg(ap, int);
82915       sqlite3GlobalConfig.m = *sqlite3MemGetMemsys6();
82916       break;
82917     }
82918 #endif
82919
82920     case SQLITE_CONFIG_LOOKASIDE: {
82921       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
82922       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
82923       break;
82924     }
82925
82926     default: {
82927       rc = SQLITE_ERROR;
82928       break;
82929     }
82930   }
82931   va_end(ap);
82932   return rc;
82933 }
82934
82935 /*
82936 ** Set up the lookaside buffers for a database connection.
82937 ** Return SQLITE_OK on success.  
82938 ** If lookaside is already active, return SQLITE_BUSY.
82939 **
82940 ** The sz parameter is the number of bytes in each lookaside slot.
82941 ** The cnt parameter is the number of slots.  If pStart is NULL the
82942 ** space for the lookaside memory is obtained from sqlite3_malloc().
82943 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
82944 ** the lookaside memory.
82945 */
82946 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
82947   void *pStart;
82948   if( db->lookaside.nOut ){
82949     return SQLITE_BUSY;
82950   }
82951   if( sz<0 ) sz = 0;
82952   if( cnt<0 ) cnt = 0;
82953   if( pBuf==0 ){
82954     sz = (sz + 7)&~7;
82955     sqlite3BeginBenignMalloc();
82956     pStart = sqlite3Malloc( sz*cnt );
82957     sqlite3EndBenignMalloc();
82958   }else{
82959     sz = sz&~7;
82960     pStart = pBuf;
82961   }
82962   if( db->lookaside.bMalloced ){
82963     sqlite3_free(db->lookaside.pStart);
82964   }
82965   db->lookaside.pStart = pStart;
82966   db->lookaside.pFree = 0;
82967   db->lookaside.sz = sz;
82968   db->lookaside.bMalloced = pBuf==0;
82969   if( pStart ){
82970     int i;
82971     LookasideSlot *p;
82972     p = (LookasideSlot*)pStart;
82973     for(i=cnt-1; i>=0; i--){
82974       p->pNext = db->lookaside.pFree;
82975       db->lookaside.pFree = p;
82976       p = (LookasideSlot*)&((u8*)p)[sz];
82977     }
82978     db->lookaside.pEnd = p;
82979     db->lookaside.bEnabled = 1;
82980   }else{
82981     db->lookaside.pEnd = 0;
82982     db->lookaside.bEnabled = 0;
82983   }
82984   return SQLITE_OK;
82985 }
82986
82987 /*
82988 ** Configuration settings for an individual database connection
82989 */
82990 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
82991   va_list ap;
82992   int rc;
82993   va_start(ap, op);
82994   switch( op ){
82995     case SQLITE_DBCONFIG_LOOKASIDE: {
82996       void *pBuf = va_arg(ap, void*);
82997       int sz = va_arg(ap, int);
82998       int cnt = va_arg(ap, int);
82999       rc = setupLookaside(db, pBuf, sz, cnt);
83000       break;
83001     }
83002     default: {
83003       rc = SQLITE_ERROR;
83004       break;
83005     }
83006   }
83007   va_end(ap);
83008   return rc;
83009 }
83010
83011 /*
83012 ** Routine needed to support the testcase() macro.
83013 */
83014 #ifdef SQLITE_COVERAGE_TEST
83015 SQLITE_PRIVATE void sqlite3Coverage(int x){
83016   static int dummy = 0;
83017   dummy += x;
83018 }
83019 #endif
83020
83021
83022 /*
83023 ** Return true if the buffer z[0..n-1] contains all spaces.
83024 */
83025 static int allSpaces(const char *z, int n){
83026   while( n>0 && z[n-1]==' ' ){ n--; }
83027   return n==0;
83028 }
83029
83030 /*
83031 ** This is the default collating function named "BINARY" which is always
83032 ** available.
83033 **
83034 ** If the padFlag argument is not NULL then space padding at the end
83035 ** of strings is ignored.  This implements the RTRIM collation.
83036 */
83037 static int binCollFunc(
83038   void *padFlag,
83039   int nKey1, const void *pKey1,
83040   int nKey2, const void *pKey2
83041 ){
83042   int rc, n;
83043   n = nKey1<nKey2 ? nKey1 : nKey2;
83044   rc = memcmp(pKey1, pKey2, n);
83045   if( rc==0 ){
83046     if( padFlag
83047      && allSpaces(((char*)pKey1)+n, nKey1-n)
83048      && allSpaces(((char*)pKey2)+n, nKey2-n)
83049     ){
83050       /* Leave rc unchanged at 0 */
83051     }else{
83052       rc = nKey1 - nKey2;
83053     }
83054   }
83055   return rc;
83056 }
83057
83058 /*
83059 ** Another built-in collating sequence: NOCASE. 
83060 **
83061 ** This collating sequence is intended to be used for "case independant
83062 ** comparison". SQLite's knowledge of upper and lower case equivalents
83063 ** extends only to the 26 characters used in the English language.
83064 **
83065 ** At the moment there is only a UTF-8 implementation.
83066 */
83067 static int nocaseCollatingFunc(
83068   void *NotUsed,
83069   int nKey1, const void *pKey1,
83070   int nKey2, const void *pKey2
83071 ){
83072   int r = sqlite3StrNICmp(
83073       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
83074   if( 0==r ){
83075     r = nKey1-nKey2;
83076   }
83077   return r;
83078 }
83079
83080 /*
83081 ** Return the ROWID of the most recent insert
83082 */
83083 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
83084   return db->lastRowid;
83085 }
83086
83087 /*
83088 ** Return the number of changes in the most recent call to sqlite3_exec().
83089 */
83090 SQLITE_API int sqlite3_changes(sqlite3 *db){
83091   return db->nChange;
83092 }
83093
83094 /*
83095 ** Return the number of changes since the database handle was opened.
83096 */
83097 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
83098   return db->nTotalChange;
83099 }
83100
83101 /*
83102 ** Close an existing SQLite database
83103 */
83104 SQLITE_API int sqlite3_close(sqlite3 *db){
83105   HashElem *i;
83106   int j;
83107
83108   if( !db ){
83109     return SQLITE_OK;
83110   }
83111   if( !sqlite3SafetyCheckSickOrOk(db) ){
83112     return SQLITE_MISUSE;
83113   }
83114   sqlite3_mutex_enter(db->mutex);
83115
83116 #ifdef SQLITE_SSE
83117   {
83118     extern void sqlite3SseCleanup(sqlite3*);
83119     sqlite3SseCleanup(db);
83120   }
83121 #endif 
83122
83123   sqlite3ResetInternalSchema(db, 0);
83124
83125   /* If a transaction is open, the ResetInternalSchema() call above
83126   ** will not have called the xDisconnect() method on any virtual
83127   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
83128   ** call will do so. We need to do this before the check for active
83129   ** SQL statements below, as the v-table implementation may be storing
83130   ** some prepared statements internally.
83131   */
83132   sqlite3VtabRollback(db);
83133
83134   /* If there are any outstanding VMs, return SQLITE_BUSY. */
83135   if( db->pVdbe ){
83136     sqlite3Error(db, SQLITE_BUSY, 
83137         "Unable to close due to unfinalised statements");
83138     sqlite3_mutex_leave(db->mutex);
83139     return SQLITE_BUSY;
83140   }
83141   assert( sqlite3SafetyCheckSickOrOk(db) );
83142
83143   for(j=0; j<db->nDb; j++){
83144     struct Db *pDb = &db->aDb[j];
83145     if( pDb->pBt ){
83146       sqlite3BtreeClose(pDb->pBt);
83147       pDb->pBt = 0;
83148       if( j!=1 ){
83149         pDb->pSchema = 0;
83150       }
83151     }
83152   }
83153   sqlite3ResetInternalSchema(db, 0);
83154   assert( db->nDb<=2 );
83155   assert( db->aDb==db->aDbStatic );
83156   for(j=0; j<ArraySize(db->aFunc.a); j++){
83157     FuncDef *pNext, *pHash, *p;
83158     for(p=db->aFunc.a[j]; p; p=pHash){
83159       pHash = p->pHash;
83160       while( p ){
83161         pNext = p->pNext;
83162         sqlite3DbFree(db, p);
83163         p = pNext;
83164       }
83165     }
83166   }
83167   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
83168     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
83169     /* Invoke any destructors registered for collation sequence user data. */
83170     for(j=0; j<3; j++){
83171       if( pColl[j].xDel ){
83172         pColl[j].xDel(pColl[j].pUser);
83173       }
83174     }
83175     sqlite3DbFree(db, pColl);
83176   }
83177   sqlite3HashClear(&db->aCollSeq);
83178 #ifndef SQLITE_OMIT_VIRTUALTABLE
83179   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
83180     Module *pMod = (Module *)sqliteHashData(i);
83181     if( pMod->xDestroy ){
83182       pMod->xDestroy(pMod->pAux);
83183     }
83184     sqlite3DbFree(db, pMod);
83185   }
83186   sqlite3HashClear(&db->aModule);
83187 #endif
83188
83189   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
83190   if( db->pErr ){
83191     sqlite3ValueFree(db->pErr);
83192   }
83193   sqlite3CloseExtensions(db);
83194
83195   db->magic = SQLITE_MAGIC_ERROR;
83196
83197   /* The temp-database schema is allocated differently from the other schema
83198   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
83199   ** So it needs to be freed here. Todo: Why not roll the temp schema into
83200   ** the same sqliteMalloc() as the one that allocates the database 
83201   ** structure?
83202   */
83203   sqlite3DbFree(db, db->aDb[1].pSchema);
83204   sqlite3_mutex_leave(db->mutex);
83205   db->magic = SQLITE_MAGIC_CLOSED;
83206   sqlite3_mutex_free(db->mutex);
83207   if( db->lookaside.bMalloced ){
83208     sqlite3_free(db->lookaside.pStart);
83209   }
83210   sqlite3_free(db);
83211   return SQLITE_OK;
83212 }
83213
83214 /*
83215 ** Rollback all database files.
83216 */
83217 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
83218   int i;
83219   int inTrans = 0;
83220   assert( sqlite3_mutex_held(db->mutex) );
83221   sqlite3BeginBenignMalloc();
83222   for(i=0; i<db->nDb; i++){
83223     if( db->aDb[i].pBt ){
83224       if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
83225         inTrans = 1;
83226       }
83227       sqlite3BtreeRollback(db->aDb[i].pBt);
83228       db->aDb[i].inTrans = 0;
83229     }
83230   }
83231   sqlite3VtabRollback(db);
83232   sqlite3EndBenignMalloc();
83233
83234   if( db->flags&SQLITE_InternChanges ){
83235     sqlite3ExpirePreparedStatements(db);
83236     sqlite3ResetInternalSchema(db, 0);
83237   }
83238
83239   /* If one has been configured, invoke the rollback-hook callback */
83240   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
83241     db->xRollbackCallback(db->pRollbackArg);
83242   }
83243 }
83244
83245 /*
83246 ** Return a static string that describes the kind of error specified in the
83247 ** argument.
83248 */
83249 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
83250   const char *z;
83251   switch( rc & 0xff ){
83252     case SQLITE_ROW:
83253     case SQLITE_DONE:
83254     case SQLITE_OK:         z = "not an error";                          break;
83255     case SQLITE_ERROR:      z = "SQL logic error or missing database";   break;
83256     case SQLITE_PERM:       z = "access permission denied";              break;
83257     case SQLITE_ABORT:      z = "callback requested query abort";        break;
83258     case SQLITE_BUSY:       z = "database is locked";                    break;
83259     case SQLITE_LOCKED:     z = "database table is locked";              break;
83260     case SQLITE_NOMEM:      z = "out of memory";                         break;
83261     case SQLITE_READONLY:   z = "attempt to write a readonly database";  break;
83262     case SQLITE_INTERRUPT:  z = "interrupted";                           break;
83263     case SQLITE_IOERR:      z = "disk I/O error";                        break;
83264     case SQLITE_CORRUPT:    z = "database disk image is malformed";      break;
83265     case SQLITE_FULL:       z = "database or disk is full";              break;
83266     case SQLITE_CANTOPEN:   z = "unable to open database file";          break;
83267     case SQLITE_EMPTY:      z = "table contains no data";                break;
83268     case SQLITE_SCHEMA:     z = "database schema has changed";           break;
83269     case SQLITE_TOOBIG:     z = "String or BLOB exceeded size limit";    break;
83270     case SQLITE_CONSTRAINT: z = "constraint failed";                     break;
83271     case SQLITE_MISMATCH:   z = "datatype mismatch";                     break;
83272     case SQLITE_MISUSE:     z = "library routine called out of sequence";break;
83273     case SQLITE_NOLFS:      z = "large file support is disabled";        break;
83274     case SQLITE_AUTH:       z = "authorization denied";                  break;
83275     case SQLITE_FORMAT:     z = "auxiliary database format error";       break;
83276     case SQLITE_RANGE:      z = "bind or column index out of range";     break;
83277     case SQLITE_NOTADB:     z = "file is encrypted or is not a database";break;
83278     default:                z = "unknown error";                         break;
83279   }
83280   return z;
83281 }
83282
83283 /*
83284 ** This routine implements a busy callback that sleeps and tries
83285 ** again until a timeout value is reached.  The timeout value is
83286 ** an integer number of milliseconds passed in as the first
83287 ** argument.
83288 */
83289 static int sqliteDefaultBusyCallback(
83290  void *ptr,               /* Database connection */
83291  int count                /* Number of times table has been busy */
83292 ){
83293 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
83294   static const u8 delays[] =
83295      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
83296   static const u8 totals[] =
83297      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
83298 # define NDELAY (sizeof(delays)/sizeof(delays[0]))
83299   sqlite3 *db = (sqlite3 *)ptr;
83300   int timeout = db->busyTimeout;
83301   int delay, prior;
83302
83303   assert( count>=0 );
83304   if( count < NDELAY ){
83305     delay = delays[count];
83306     prior = totals[count];
83307   }else{
83308     delay = delays[NDELAY-1];
83309     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
83310   }
83311   if( prior + delay > timeout ){
83312     delay = timeout - prior;
83313     if( delay<=0 ) return 0;
83314   }
83315   sqlite3OsSleep(db->pVfs, delay*1000);
83316   return 1;
83317 #else
83318   sqlite3 *db = (sqlite3 *)ptr;
83319   int timeout = ((sqlite3 *)ptr)->busyTimeout;
83320   if( (count+1)*1000 > timeout ){
83321     return 0;
83322   }
83323   sqlite3OsSleep(db->pVfs, 1000000);
83324   return 1;
83325 #endif
83326 }
83327
83328 /*
83329 ** Invoke the given busy handler.
83330 **
83331 ** This routine is called when an operation failed with a lock.
83332 ** If this routine returns non-zero, the lock is retried.  If it
83333 ** returns 0, the operation aborts with an SQLITE_BUSY error.
83334 */
83335 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
83336   int rc;
83337   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
83338   rc = p->xFunc(p->pArg, p->nBusy);
83339   if( rc==0 ){
83340     p->nBusy = -1;
83341   }else{
83342     p->nBusy++;
83343   }
83344   return rc; 
83345 }
83346
83347 /*
83348 ** This routine sets the busy callback for an Sqlite database to the
83349 ** given callback function with the given argument.
83350 */
83351 SQLITE_API int sqlite3_busy_handler(
83352   sqlite3 *db,
83353   int (*xBusy)(void*,int),
83354   void *pArg
83355 ){
83356   sqlite3_mutex_enter(db->mutex);
83357   db->busyHandler.xFunc = xBusy;
83358   db->busyHandler.pArg = pArg;
83359   db->busyHandler.nBusy = 0;
83360   sqlite3_mutex_leave(db->mutex);
83361   return SQLITE_OK;
83362 }
83363
83364 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
83365 /*
83366 ** This routine sets the progress callback for an Sqlite database to the
83367 ** given callback function with the given argument. The progress callback will
83368 ** be invoked every nOps opcodes.
83369 */
83370 SQLITE_API void sqlite3_progress_handler(
83371   sqlite3 *db, 
83372   int nOps,
83373   int (*xProgress)(void*), 
83374   void *pArg
83375 ){
83376   sqlite3_mutex_enter(db->mutex);
83377   if( nOps>0 ){
83378     db->xProgress = xProgress;
83379     db->nProgressOps = nOps;
83380     db->pProgressArg = pArg;
83381   }else{
83382     db->xProgress = 0;
83383     db->nProgressOps = 0;
83384     db->pProgressArg = 0;
83385   }
83386   sqlite3_mutex_leave(db->mutex);
83387 }
83388 #endif
83389
83390
83391 /*
83392 ** This routine installs a default busy handler that waits for the
83393 ** specified number of milliseconds before returning 0.
83394 */
83395 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
83396   if( ms>0 ){
83397     db->busyTimeout = ms;
83398     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
83399   }else{
83400     sqlite3_busy_handler(db, 0, 0);
83401   }
83402   return SQLITE_OK;
83403 }
83404
83405 /*
83406 ** Cause any pending operation to stop at its earliest opportunity.
83407 */
83408 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
83409   db->u1.isInterrupted = 1;
83410 }
83411
83412
83413 /*
83414 ** This function is exactly the same as sqlite3_create_function(), except
83415 ** that it is designed to be called by internal code. The difference is
83416 ** that if a malloc() fails in sqlite3_create_function(), an error code
83417 ** is returned and the mallocFailed flag cleared. 
83418 */
83419 SQLITE_PRIVATE int sqlite3CreateFunc(
83420   sqlite3 *db,
83421   const char *zFunctionName,
83422   int nArg,
83423   int enc,
83424   void *pUserData,
83425   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
83426   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
83427   void (*xFinal)(sqlite3_context*)
83428 ){
83429   FuncDef *p;
83430   int nName;
83431
83432   assert( sqlite3_mutex_held(db->mutex) );
83433   if( zFunctionName==0 ||
83434       (xFunc && (xFinal || xStep)) || 
83435       (!xFunc && (xFinal && !xStep)) ||
83436       (!xFunc && (!xFinal && xStep)) ||
83437       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
83438       (255<(nName = sqlite3Strlen(db, zFunctionName))) ){
83439     sqlite3Error(db, SQLITE_ERROR, "bad parameters");
83440     return SQLITE_ERROR;
83441   }
83442   
83443 #ifndef SQLITE_OMIT_UTF16
83444   /* If SQLITE_UTF16 is specified as the encoding type, transform this
83445   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
83446   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
83447   **
83448   ** If SQLITE_ANY is specified, add three versions of the function
83449   ** to the hash table.
83450   */
83451   if( enc==SQLITE_UTF16 ){
83452     enc = SQLITE_UTF16NATIVE;
83453   }else if( enc==SQLITE_ANY ){
83454     int rc;
83455     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
83456          pUserData, xFunc, xStep, xFinal);
83457     if( rc==SQLITE_OK ){
83458       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
83459           pUserData, xFunc, xStep, xFinal);
83460     }
83461     if( rc!=SQLITE_OK ){
83462       return rc;
83463     }
83464     enc = SQLITE_UTF16BE;
83465   }
83466 #else
83467   enc = SQLITE_UTF8;
83468 #endif
83469   
83470   /* Check if an existing function is being overridden or deleted. If so,
83471   ** and there are active VMs, then return SQLITE_BUSY. If a function
83472   ** is being overridden/deleted but there are no active VMs, allow the
83473   ** operation to continue but invalidate all precompiled statements.
83474   */
83475   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 0);
83476   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
83477     if( db->activeVdbeCnt ){
83478       sqlite3Error(db, SQLITE_BUSY, 
83479         "Unable to delete/modify user-function due to active statements");
83480       assert( !db->mallocFailed );
83481       return SQLITE_BUSY;
83482     }else{
83483       sqlite3ExpirePreparedStatements(db);
83484     }
83485   }
83486
83487   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 1);
83488   assert(p || db->mallocFailed);
83489   if( !p ){
83490     return SQLITE_NOMEM;
83491   }
83492   p->flags = 0;
83493   p->xFunc = xFunc;
83494   p->xStep = xStep;
83495   p->xFinalize = xFinal;
83496   p->pUserData = pUserData;
83497   p->nArg = nArg;
83498   return SQLITE_OK;
83499 }
83500
83501 /*
83502 ** Create new user functions.
83503 */
83504 SQLITE_API int sqlite3_create_function(
83505   sqlite3 *db,
83506   const char *zFunctionName,
83507   int nArg,
83508   int enc,
83509   void *p,
83510   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
83511   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
83512   void (*xFinal)(sqlite3_context*)
83513 ){
83514   int rc;
83515   sqlite3_mutex_enter(db->mutex);
83516   rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
83517   rc = sqlite3ApiExit(db, rc);
83518   sqlite3_mutex_leave(db->mutex);
83519   return rc;
83520 }
83521
83522 #ifndef SQLITE_OMIT_UTF16
83523 SQLITE_API int sqlite3_create_function16(
83524   sqlite3 *db,
83525   const void *zFunctionName,
83526   int nArg,
83527   int eTextRep,
83528   void *p,
83529   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
83530   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
83531   void (*xFinal)(sqlite3_context*)
83532 ){
83533   int rc;
83534   char *zFunc8;
83535   sqlite3_mutex_enter(db->mutex);
83536   assert( !db->mallocFailed );
83537   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1);
83538   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
83539   sqlite3DbFree(db, zFunc8);
83540   rc = sqlite3ApiExit(db, rc);
83541   sqlite3_mutex_leave(db->mutex);
83542   return rc;
83543 }
83544 #endif
83545
83546
83547 /*
83548 ** Declare that a function has been overloaded by a virtual table.
83549 **
83550 ** If the function already exists as a regular global function, then
83551 ** this routine is a no-op.  If the function does not exist, then create
83552 ** a new one that always throws a run-time error.  
83553 **
83554 ** When virtual tables intend to provide an overloaded function, they
83555 ** should call this routine to make sure the global function exists.
83556 ** A global function must exist in order for name resolution to work
83557 ** properly.
83558 */
83559 SQLITE_API int sqlite3_overload_function(
83560   sqlite3 *db,
83561   const char *zName,
83562   int nArg
83563 ){
83564   int nName = sqlite3Strlen(db, zName);
83565   int rc;
83566   sqlite3_mutex_enter(db->mutex);
83567   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
83568     sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
83569                       0, sqlite3InvalidFunction, 0, 0);
83570   }
83571   rc = sqlite3ApiExit(db, SQLITE_OK);
83572   sqlite3_mutex_leave(db->mutex);
83573   return rc;
83574 }
83575
83576 #ifndef SQLITE_OMIT_TRACE
83577 /*
83578 ** Register a trace function.  The pArg from the previously registered trace
83579 ** is returned.  
83580 **
83581 ** A NULL trace function means that no tracing is executes.  A non-NULL
83582 ** trace is a pointer to a function that is invoked at the start of each
83583 ** SQL statement.
83584 */
83585 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
83586   void *pOld;
83587   sqlite3_mutex_enter(db->mutex);
83588   pOld = db->pTraceArg;
83589   db->xTrace = xTrace;
83590   db->pTraceArg = pArg;
83591   sqlite3_mutex_leave(db->mutex);
83592   return pOld;
83593 }
83594 /*
83595 ** Register a profile function.  The pArg from the previously registered 
83596 ** profile function is returned.  
83597 **
83598 ** A NULL profile function means that no profiling is executes.  A non-NULL
83599 ** profile is a pointer to a function that is invoked at the conclusion of
83600 ** each SQL statement that is run.
83601 */
83602 SQLITE_API void *sqlite3_profile(
83603   sqlite3 *db,
83604   void (*xProfile)(void*,const char*,sqlite_uint64),
83605   void *pArg
83606 ){
83607   void *pOld;
83608   sqlite3_mutex_enter(db->mutex);
83609   pOld = db->pProfileArg;
83610   db->xProfile = xProfile;
83611   db->pProfileArg = pArg;
83612   sqlite3_mutex_leave(db->mutex);
83613   return pOld;
83614 }
83615 #endif /* SQLITE_OMIT_TRACE */
83616
83617 /*** EXPERIMENTAL ***
83618 **
83619 ** Register a function to be invoked when a transaction comments.
83620 ** If the invoked function returns non-zero, then the commit becomes a
83621 ** rollback.
83622 */
83623 SQLITE_API void *sqlite3_commit_hook(
83624   sqlite3 *db,              /* Attach the hook to this database */
83625   int (*xCallback)(void*),  /* Function to invoke on each commit */
83626   void *pArg                /* Argument to the function */
83627 ){
83628   void *pOld;
83629   sqlite3_mutex_enter(db->mutex);
83630   pOld = db->pCommitArg;
83631   db->xCommitCallback = xCallback;
83632   db->pCommitArg = pArg;
83633   sqlite3_mutex_leave(db->mutex);
83634   return pOld;
83635 }
83636
83637 /*
83638 ** Register a callback to be invoked each time a row is updated,
83639 ** inserted or deleted using this database connection.
83640 */
83641 SQLITE_API void *sqlite3_update_hook(
83642   sqlite3 *db,              /* Attach the hook to this database */
83643   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
83644   void *pArg                /* Argument to the function */
83645 ){
83646   void *pRet;
83647   sqlite3_mutex_enter(db->mutex);
83648   pRet = db->pUpdateArg;
83649   db->xUpdateCallback = xCallback;
83650   db->pUpdateArg = pArg;
83651   sqlite3_mutex_leave(db->mutex);
83652   return pRet;
83653 }
83654
83655 /*
83656 ** Register a callback to be invoked each time a transaction is rolled
83657 ** back by this database connection.
83658 */
83659 SQLITE_API void *sqlite3_rollback_hook(
83660   sqlite3 *db,              /* Attach the hook to this database */
83661   void (*xCallback)(void*), /* Callback function */
83662   void *pArg                /* Argument to the function */
83663 ){
83664   void *pRet;
83665   sqlite3_mutex_enter(db->mutex);
83666   pRet = db->pRollbackArg;
83667   db->xRollbackCallback = xCallback;
83668   db->pRollbackArg = pArg;
83669   sqlite3_mutex_leave(db->mutex);
83670   return pRet;
83671 }
83672
83673 /*
83674 ** This routine is called to create a connection to a database BTree
83675 ** driver.  If zFilename is the name of a file, then that file is
83676 ** opened and used.  If zFilename is the magic name ":memory:" then
83677 ** the database is stored in memory (and is thus forgotten as soon as
83678 ** the connection is closed.)  If zFilename is NULL then the database
83679 ** is a "virtual" database for transient use only and is deleted as
83680 ** soon as the connection is closed.
83681 **
83682 ** A virtual database can be either a disk file (that is automatically
83683 ** deleted when the file is closed) or it an be held entirely in memory,
83684 ** depending on the values of the SQLITE_TEMP_STORE compile-time macro and the
83685 ** db->temp_store variable, according to the following chart:
83686 **
83687 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
83688 **   -----------------     --------------     ------------------------------
83689 **   0                     any                file
83690 **   1                     1                  file
83691 **   1                     2                  memory
83692 **   1                     0                  file
83693 **   2                     1                  file
83694 **   2                     2                  memory
83695 **   2                     0                  memory
83696 **   3                     any                memory
83697 */
83698 SQLITE_PRIVATE int sqlite3BtreeFactory(
83699   const sqlite3 *db,        /* Main database when opening aux otherwise 0 */
83700   const char *zFilename,    /* Name of the file containing the BTree database */
83701   int omitJournal,          /* if TRUE then do not journal this file */
83702   int nCache,               /* How many pages in the page cache */
83703   int vfsFlags,             /* Flags passed through to vfsOpen */
83704   Btree **ppBtree           /* Pointer to new Btree object written here */
83705 ){
83706   int btFlags = 0;
83707   int rc;
83708   
83709   assert( sqlite3_mutex_held(db->mutex) );
83710   assert( ppBtree != 0);
83711   if( omitJournal ){
83712     btFlags |= BTREE_OMIT_JOURNAL;
83713   }
83714   if( db->flags & SQLITE_NoReadlock ){
83715     btFlags |= BTREE_NO_READLOCK;
83716   }
83717   if( zFilename==0 ){
83718 #if SQLITE_TEMP_STORE==0
83719     /* Do nothing */
83720 #endif
83721 #ifndef SQLITE_OMIT_MEMORYDB
83722 #if SQLITE_TEMP_STORE==1
83723     if( db->temp_store==2 ) zFilename = ":memory:";
83724 #endif
83725 #if SQLITE_TEMP_STORE==2
83726     if( db->temp_store!=1 ) zFilename = ":memory:";
83727 #endif
83728 #if SQLITE_TEMP_STORE==3
83729     zFilename = ":memory:";
83730 #endif
83731 #endif /* SQLITE_OMIT_MEMORYDB */
83732   }
83733
83734   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
83735     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
83736   }
83737   rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
83738
83739   /* If the B-Tree was successfully opened, set the pager-cache size to the
83740   ** default value. Except, if the call to BtreeOpen() returned a handle
83741   ** open on an existing shared pager-cache, do not change the pager-cache 
83742   ** size.
83743   */
83744   if( rc==SQLITE_OK && 0==sqlite3BtreeSchema(*ppBtree, 0, 0) ){
83745     sqlite3BtreeSetCacheSize(*ppBtree, nCache);
83746   }
83747   return rc;
83748 }
83749
83750 /*
83751 ** Return UTF-8 encoded English language explanation of the most recent
83752 ** error.
83753 */
83754 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
83755   const char *z;
83756   if( !db ){
83757     return sqlite3ErrStr(SQLITE_NOMEM);
83758   }
83759   if( !sqlite3SafetyCheckSickOrOk(db) ){
83760     return sqlite3ErrStr(SQLITE_MISUSE);
83761   }
83762   sqlite3_mutex_enter(db->mutex);
83763   assert( !db->mallocFailed );
83764   z = (char*)sqlite3_value_text(db->pErr);
83765   assert( !db->mallocFailed );
83766   if( z==0 ){
83767     z = sqlite3ErrStr(db->errCode);
83768   }
83769   sqlite3_mutex_leave(db->mutex);
83770   return z;
83771 }
83772
83773 #ifndef SQLITE_OMIT_UTF16
83774 /*
83775 ** Return UTF-16 encoded English language explanation of the most recent
83776 ** error.
83777 */
83778 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
83779   /* Because all the characters in the string are in the unicode
83780   ** range 0x00-0xFF, if we pad the big-endian string with a 
83781   ** zero byte, we can obtain the little-endian string with
83782   ** &big_endian[1].
83783   */
83784   static const char outOfMemBe[] = {
83785     0, 'o', 0, 'u', 0, 't', 0, ' ', 
83786     0, 'o', 0, 'f', 0, ' ', 
83787     0, 'm', 0, 'e', 0, 'm', 0, 'o', 0, 'r', 0, 'y', 0, 0, 0
83788   };
83789   static const char misuseBe [] = {
83790     0, 'l', 0, 'i', 0, 'b', 0, 'r', 0, 'a', 0, 'r', 0, 'y', 0, ' ', 
83791     0, 'r', 0, 'o', 0, 'u', 0, 't', 0, 'i', 0, 'n', 0, 'e', 0, ' ', 
83792     0, 'c', 0, 'a', 0, 'l', 0, 'l', 0, 'e', 0, 'd', 0, ' ', 
83793     0, 'o', 0, 'u', 0, 't', 0, ' ', 
83794     0, 'o', 0, 'f', 0, ' ', 
83795     0, 's', 0, 'e', 0, 'q', 0, 'u', 0, 'e', 0, 'n', 0, 'c', 0, 'e', 0, 0, 0
83796   };
83797
83798   const void *z;
83799   if( !db ){
83800     return (void *)(&outOfMemBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
83801   }
83802   if( !sqlite3SafetyCheckSickOrOk(db) ){
83803     return (void *)(&misuseBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
83804   }
83805   sqlite3_mutex_enter(db->mutex);
83806   assert( !db->mallocFailed );
83807   z = sqlite3_value_text16(db->pErr);
83808   if( z==0 ){
83809     sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
83810          SQLITE_UTF8, SQLITE_STATIC);
83811     z = sqlite3_value_text16(db->pErr);
83812   }
83813   /* A malloc() may have failed within the call to sqlite3_value_text16()
83814   ** above. If this is the case, then the db->mallocFailed flag needs to
83815   ** be cleared before returning. Do this directly, instead of via
83816   ** sqlite3ApiExit(), to avoid setting the database handle error message.
83817   */
83818   db->mallocFailed = 0;
83819   sqlite3_mutex_leave(db->mutex);
83820   return z;
83821 }
83822 #endif /* SQLITE_OMIT_UTF16 */
83823
83824 /*
83825 ** Return the most recent error code generated by an SQLite routine. If NULL is
83826 ** passed to this function, we assume a malloc() failed during sqlite3_open().
83827 */
83828 SQLITE_API int sqlite3_errcode(sqlite3 *db){
83829   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
83830     return SQLITE_MISUSE;
83831   }
83832   if( !db || db->mallocFailed ){
83833     return SQLITE_NOMEM;
83834   }
83835   return db->errCode & db->errMask;
83836 }
83837
83838 /*
83839 ** Create a new collating function for database "db".  The name is zName
83840 ** and the encoding is enc.
83841 */
83842 static int createCollation(
83843   sqlite3* db, 
83844   const char *zName, 
83845   int enc, 
83846   void* pCtx,
83847   int(*xCompare)(void*,int,const void*,int,const void*),
83848   void(*xDel)(void*)
83849 ){
83850   CollSeq *pColl;
83851   int enc2;
83852   int nName;
83853   
83854   assert( sqlite3_mutex_held(db->mutex) );
83855
83856   /* If SQLITE_UTF16 is specified as the encoding type, transform this
83857   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
83858   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
83859   */
83860   enc2 = enc & ~SQLITE_UTF16_ALIGNED;
83861   if( enc2==SQLITE_UTF16 ){
83862     enc2 = SQLITE_UTF16NATIVE;
83863   }
83864   if( (enc2&~3)!=0 ){
83865     return SQLITE_MISUSE;
83866   }
83867
83868   /* Check if this call is removing or replacing an existing collation 
83869   ** sequence. If so, and there are active VMs, return busy. If there
83870   ** are no active VMs, invalidate any pre-compiled statements.
83871   */
83872   nName = sqlite3Strlen(db, zName);
83873   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, nName, 0);
83874   if( pColl && pColl->xCmp ){
83875     if( db->activeVdbeCnt ){
83876       sqlite3Error(db, SQLITE_BUSY, 
83877         "Unable to delete/modify collation sequence due to active statements");
83878       return SQLITE_BUSY;
83879     }
83880     sqlite3ExpirePreparedStatements(db);
83881
83882     /* If collation sequence pColl was created directly by a call to
83883     ** sqlite3_create_collation, and not generated by synthCollSeq(),
83884     ** then any copies made by synthCollSeq() need to be invalidated.
83885     ** Also, collation destructor - CollSeq.xDel() - function may need
83886     ** to be called.
83887     */ 
83888     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
83889       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
83890       int j;
83891       for(j=0; j<3; j++){
83892         CollSeq *p = &aColl[j];
83893         if( p->enc==pColl->enc ){
83894           if( p->xDel ){
83895             p->xDel(p->pUser);
83896           }
83897           p->xCmp = 0;
83898         }
83899       }
83900     }
83901   }
83902
83903   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, nName, 1);
83904   if( pColl ){
83905     pColl->xCmp = xCompare;
83906     pColl->pUser = pCtx;
83907     pColl->xDel = xDel;
83908     pColl->enc = enc2 | (enc & SQLITE_UTF16_ALIGNED);
83909   }
83910   sqlite3Error(db, SQLITE_OK, 0);
83911   return SQLITE_OK;
83912 }
83913
83914
83915 /*
83916 ** This array defines hard upper bounds on limit values.  The
83917 ** initializer must be kept in sync with the SQLITE_LIMIT_*
83918 ** #defines in sqlite3.h.
83919 */
83920 static const int aHardLimit[] = {
83921   SQLITE_MAX_LENGTH,
83922   SQLITE_MAX_SQL_LENGTH,
83923   SQLITE_MAX_COLUMN,
83924   SQLITE_MAX_EXPR_DEPTH,
83925   SQLITE_MAX_COMPOUND_SELECT,
83926   SQLITE_MAX_VDBE_OP,
83927   SQLITE_MAX_FUNCTION_ARG,
83928   SQLITE_MAX_ATTACHED,
83929   SQLITE_MAX_LIKE_PATTERN_LENGTH,
83930   SQLITE_MAX_VARIABLE_NUMBER,
83931 };
83932
83933 /*
83934 ** Make sure the hard limits are set to reasonable values
83935 */
83936 #if SQLITE_MAX_LENGTH<100
83937 # error SQLITE_MAX_LENGTH must be at least 100
83938 #endif
83939 #if SQLITE_MAX_SQL_LENGTH<100
83940 # error SQLITE_MAX_SQL_LENGTH must be at least 100
83941 #endif
83942 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
83943 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
83944 #endif
83945 #if SQLITE_MAX_COMPOUND_SELECT<2
83946 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
83947 #endif
83948 #if SQLITE_MAX_VDBE_OP<40
83949 # error SQLITE_MAX_VDBE_OP must be at least 40
83950 #endif
83951 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
83952 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
83953 #endif
83954 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>30
83955 # error SQLITE_MAX_ATTACHED must be between 0 and 30
83956 #endif
83957 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
83958 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
83959 #endif
83960 #if SQLITE_MAX_VARIABLE_NUMBER<1
83961 # error SQLITE_MAX_VARIABLE_NUMBER must be at least 1
83962 #endif
83963 #if SQLITE_MAX_COLUMN>32767
83964 # error SQLITE_MAX_COLUMN must not exceed 32767
83965 #endif
83966
83967
83968 /*
83969 ** Change the value of a limit.  Report the old value.
83970 ** If an invalid limit index is supplied, report -1.
83971 ** Make no changes but still report the old value if the
83972 ** new limit is negative.
83973 **
83974 ** A new lower limit does not shrink existing constructs.
83975 ** It merely prevents new constructs that exceed the limit
83976 ** from forming.
83977 */
83978 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
83979   int oldLimit;
83980   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
83981     return -1;
83982   }
83983   oldLimit = db->aLimit[limitId];
83984   if( newLimit>=0 ){
83985     if( newLimit>aHardLimit[limitId] ){
83986       newLimit = aHardLimit[limitId];
83987     }
83988     db->aLimit[limitId] = newLimit;
83989   }
83990   return oldLimit;
83991 }
83992
83993 /*
83994 ** This routine does the work of opening a database on behalf of
83995 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
83996 ** is UTF-8 encoded.
83997 */
83998 static int openDatabase(
83999   const char *zFilename, /* Database filename UTF-8 encoded */
84000   sqlite3 **ppDb,        /* OUT: Returned database handle */
84001   unsigned flags,        /* Operational flags */
84002   const char *zVfs       /* Name of the VFS to use */
84003 ){
84004   sqlite3 *db;
84005   int rc;
84006   CollSeq *pColl;
84007   int isThreadsafe;
84008
84009 #ifndef SQLITE_OMIT_AUTOINIT
84010   rc = sqlite3_initialize();
84011   if( rc ) return rc;
84012 #endif
84013
84014   if( sqlite3GlobalConfig.bCoreMutex==0 ){
84015     isThreadsafe = 0;
84016   }else if( flags & SQLITE_OPEN_NOMUTEX ){
84017     isThreadsafe = 0;
84018   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
84019     isThreadsafe = 1;
84020   }else{
84021     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
84022   }
84023
84024   /* Remove harmful bits from the flags parameter */
84025   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
84026                SQLITE_OPEN_MAIN_DB |
84027                SQLITE_OPEN_TEMP_DB | 
84028                SQLITE_OPEN_TRANSIENT_DB | 
84029                SQLITE_OPEN_MAIN_JOURNAL | 
84030                SQLITE_OPEN_TEMP_JOURNAL | 
84031                SQLITE_OPEN_SUBJOURNAL | 
84032                SQLITE_OPEN_MASTER_JOURNAL |
84033                SQLITE_OPEN_NOMUTEX |
84034                SQLITE_OPEN_FULLMUTEX
84035              );
84036
84037   /* Allocate the sqlite data structure */
84038   db = sqlite3MallocZero( sizeof(sqlite3) );
84039   if( db==0 ) goto opendb_out;
84040   if( isThreadsafe ){
84041     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
84042     if( db->mutex==0 ){
84043       sqlite3_free(db);
84044       db = 0;
84045       goto opendb_out;
84046     }
84047   }
84048   sqlite3_mutex_enter(db->mutex);
84049   db->errMask = 0xff;
84050   db->priorNewRowid = 0;
84051   db->nDb = 2;
84052   db->magic = SQLITE_MAGIC_BUSY;
84053   db->aDb = db->aDbStatic;
84054
84055   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
84056   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
84057   db->autoCommit = 1;
84058   db->nextAutovac = -1;
84059   db->nextPagesize = 0;
84060   db->flags |= SQLITE_ShortColNames
84061 #if SQLITE_DEFAULT_FILE_FORMAT<4
84062                  | SQLITE_LegacyFileFmt
84063 #endif
84064 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
84065                  | SQLITE_LoadExtension
84066 #endif
84067       ;
84068   sqlite3HashInit(&db->aCollSeq, SQLITE_HASH_STRING, 0);
84069 #ifndef SQLITE_OMIT_VIRTUALTABLE
84070   sqlite3HashInit(&db->aModule, SQLITE_HASH_STRING, 0);
84071 #endif
84072
84073   db->pVfs = sqlite3_vfs_find(zVfs);
84074   if( !db->pVfs ){
84075     rc = SQLITE_ERROR;
84076     sqlite3Error(db, rc, "no such vfs: %s", zVfs);
84077     goto opendb_out;
84078   }
84079
84080   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
84081   ** and UTF-16, so add a version for each to avoid any unnecessary
84082   ** conversions. The only error that can occur here is a malloc() failure.
84083   */
84084   createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
84085   createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
84086   createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
84087   createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
84088   if( db->mallocFailed ){
84089     goto opendb_out;
84090   }
84091   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0);
84092   assert( db->pDfltColl!=0 );
84093
84094   /* Also add a UTF-8 case-insensitive collation sequence. */
84095   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
84096
84097   /* Set flags on the built-in collating sequences */
84098   db->pDfltColl->type = SQLITE_COLL_BINARY;
84099   pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "NOCASE", 6, 0);
84100   if( pColl ){
84101     pColl->type = SQLITE_COLL_NOCASE;
84102   }
84103
84104   /* Open the backend database driver */
84105   db->openFlags = flags;
84106   rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE, 
84107                            flags | SQLITE_OPEN_MAIN_DB,
84108                            &db->aDb[0].pBt);
84109   if( rc!=SQLITE_OK ){
84110     sqlite3Error(db, rc, 0);
84111     goto opendb_out;
84112   }
84113   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
84114   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
84115
84116
84117   /* The default safety_level for the main database is 'full'; for the temp
84118   ** database it is 'NONE'. This matches the pager layer defaults.  
84119   */
84120   db->aDb[0].zName = "main";
84121   db->aDb[0].safety_level = 3;
84122 #ifndef SQLITE_OMIT_TEMPDB
84123   db->aDb[1].zName = "temp";
84124   db->aDb[1].safety_level = 1;
84125 #endif
84126
84127   db->magic = SQLITE_MAGIC_OPEN;
84128   if( db->mallocFailed ){
84129     goto opendb_out;
84130   }
84131
84132   /* Register all built-in functions, but do not attempt to read the
84133   ** database schema yet. This is delayed until the first time the database
84134   ** is accessed.
84135   */
84136   sqlite3Error(db, SQLITE_OK, 0);
84137   sqlite3RegisterBuiltinFunctions(db);
84138
84139   /* Load automatic extensions - extensions that have been registered
84140   ** using the sqlite3_automatic_extension() API.
84141   */
84142   (void)sqlite3AutoLoadExtensions(db);
84143   if( sqlite3_errcode(db)!=SQLITE_OK ){
84144     goto opendb_out;
84145   }
84146
84147 #ifdef SQLITE_ENABLE_FTS1
84148   if( !db->mallocFailed ){
84149     extern int sqlite3Fts1Init(sqlite3*);
84150     rc = sqlite3Fts1Init(db);
84151   }
84152 #endif
84153
84154 #ifdef SQLITE_ENABLE_FTS2
84155   if( !db->mallocFailed && rc==SQLITE_OK ){
84156     extern int sqlite3Fts2Init(sqlite3*);
84157     rc = sqlite3Fts2Init(db);
84158   }
84159 #endif
84160
84161 #ifdef SQLITE_ENABLE_FTS3
84162   if( !db->mallocFailed && rc==SQLITE_OK ){
84163     rc = sqlite3Fts3Init(db);
84164   }
84165 #endif
84166
84167 #ifdef SQLITE_ENABLE_ICU
84168   if( !db->mallocFailed && rc==SQLITE_OK ){
84169     rc = sqlite3IcuInit(db);
84170   }
84171 #endif
84172
84173 #ifdef SQLITE_ENABLE_RTREE
84174   if( !db->mallocFailed && rc==SQLITE_OK){
84175     rc = sqlite3RtreeInit(db);
84176   }
84177 #endif
84178
84179   sqlite3Error(db, rc, 0);
84180
84181   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
84182   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
84183   ** mode.  Doing nothing at all also makes NORMAL the default.
84184   */
84185 #ifdef SQLITE_DEFAULT_LOCKING_MODE
84186   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
84187   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
84188                           SQLITE_DEFAULT_LOCKING_MODE);
84189 #endif
84190
84191   /* Enable the lookaside-malloc subsystem */
84192   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside, sqlite3GlobalConfig.nLookaside);
84193
84194 opendb_out:
84195   if( db ){
84196     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
84197     sqlite3_mutex_leave(db->mutex);
84198   }
84199   rc = sqlite3_errcode(db);
84200   if( rc==SQLITE_NOMEM ){
84201     sqlite3_close(db);
84202     db = 0;
84203   }else if( rc!=SQLITE_OK ){
84204     db->magic = SQLITE_MAGIC_SICK;
84205   }
84206   *ppDb = db;
84207   return sqlite3ApiExit(0, rc);
84208 }
84209
84210 /*
84211 ** Open a new database handle.
84212 */
84213 SQLITE_API int sqlite3_open(
84214   const char *zFilename, 
84215   sqlite3 **ppDb 
84216 ){
84217   return openDatabase(zFilename, ppDb,
84218                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
84219 }
84220 SQLITE_API int sqlite3_open_v2(
84221   const char *filename,   /* Database filename (UTF-8) */
84222   sqlite3 **ppDb,         /* OUT: SQLite db handle */
84223   int flags,              /* Flags */
84224   const char *zVfs        /* Name of VFS module to use */
84225 ){
84226   return openDatabase(filename, ppDb, flags, zVfs);
84227 }
84228
84229 #ifndef SQLITE_OMIT_UTF16
84230 /*
84231 ** Open a new database handle.
84232 */
84233 SQLITE_API int sqlite3_open16(
84234   const void *zFilename, 
84235   sqlite3 **ppDb
84236 ){
84237   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
84238   sqlite3_value *pVal;
84239   int rc;
84240
84241   assert( zFilename );
84242   assert( ppDb );
84243   *ppDb = 0;
84244 #ifndef SQLITE_OMIT_AUTOINIT
84245   rc = sqlite3_initialize();
84246   if( rc ) return rc;
84247 #endif
84248   pVal = sqlite3ValueNew(0);
84249   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
84250   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
84251   if( zFilename8 ){
84252     rc = openDatabase(zFilename8, ppDb,
84253                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
84254     assert( *ppDb || rc==SQLITE_NOMEM );
84255     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
84256       ENC(*ppDb) = SQLITE_UTF16NATIVE;
84257     }
84258   }else{
84259     rc = SQLITE_NOMEM;
84260   }
84261   sqlite3ValueFree(pVal);
84262
84263   return sqlite3ApiExit(0, rc);
84264 }
84265 #endif /* SQLITE_OMIT_UTF16 */
84266
84267 /*
84268 ** Register a new collation sequence with the database handle db.
84269 */
84270 SQLITE_API int sqlite3_create_collation(
84271   sqlite3* db, 
84272   const char *zName, 
84273   int enc, 
84274   void* pCtx,
84275   int(*xCompare)(void*,int,const void*,int,const void*)
84276 ){
84277   int rc;
84278   sqlite3_mutex_enter(db->mutex);
84279   assert( !db->mallocFailed );
84280   rc = createCollation(db, zName, enc, pCtx, xCompare, 0);
84281   rc = sqlite3ApiExit(db, rc);
84282   sqlite3_mutex_leave(db->mutex);
84283   return rc;
84284 }
84285
84286 /*
84287 ** Register a new collation sequence with the database handle db.
84288 */
84289 SQLITE_API int sqlite3_create_collation_v2(
84290   sqlite3* db, 
84291   const char *zName, 
84292   int enc, 
84293   void* pCtx,
84294   int(*xCompare)(void*,int,const void*,int,const void*),
84295   void(*xDel)(void*)
84296 ){
84297   int rc;
84298   sqlite3_mutex_enter(db->mutex);
84299   assert( !db->mallocFailed );
84300   rc = createCollation(db, zName, enc, pCtx, xCompare, xDel);
84301   rc = sqlite3ApiExit(db, rc);
84302   sqlite3_mutex_leave(db->mutex);
84303   return rc;
84304 }
84305
84306 #ifndef SQLITE_OMIT_UTF16
84307 /*
84308 ** Register a new collation sequence with the database handle db.
84309 */
84310 SQLITE_API int sqlite3_create_collation16(
84311   sqlite3* db, 
84312   const void *zName,
84313   int enc, 
84314   void* pCtx,
84315   int(*xCompare)(void*,int,const void*,int,const void*)
84316 ){
84317   int rc = SQLITE_OK;
84318   char *zName8;
84319   sqlite3_mutex_enter(db->mutex);
84320   assert( !db->mallocFailed );
84321   zName8 = sqlite3Utf16to8(db, zName, -1);
84322   if( zName8 ){
84323     rc = createCollation(db, zName8, enc, pCtx, xCompare, 0);
84324     sqlite3DbFree(db, zName8);
84325   }
84326   rc = sqlite3ApiExit(db, rc);
84327   sqlite3_mutex_leave(db->mutex);
84328   return rc;
84329 }
84330 #endif /* SQLITE_OMIT_UTF16 */
84331
84332 /*
84333 ** Register a collation sequence factory callback with the database handle
84334 ** db. Replace any previously installed collation sequence factory.
84335 */
84336 SQLITE_API int sqlite3_collation_needed(
84337   sqlite3 *db, 
84338   void *pCollNeededArg, 
84339   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
84340 ){
84341   sqlite3_mutex_enter(db->mutex);
84342   db->xCollNeeded = xCollNeeded;
84343   db->xCollNeeded16 = 0;
84344   db->pCollNeededArg = pCollNeededArg;
84345   sqlite3_mutex_leave(db->mutex);
84346   return SQLITE_OK;
84347 }
84348
84349 #ifndef SQLITE_OMIT_UTF16
84350 /*
84351 ** Register a collation sequence factory callback with the database handle
84352 ** db. Replace any previously installed collation sequence factory.
84353 */
84354 SQLITE_API int sqlite3_collation_needed16(
84355   sqlite3 *db, 
84356   void *pCollNeededArg, 
84357   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
84358 ){
84359   sqlite3_mutex_enter(db->mutex);
84360   db->xCollNeeded = 0;
84361   db->xCollNeeded16 = xCollNeeded16;
84362   db->pCollNeededArg = pCollNeededArg;
84363   sqlite3_mutex_leave(db->mutex);
84364   return SQLITE_OK;
84365 }
84366 #endif /* SQLITE_OMIT_UTF16 */
84367
84368 #ifndef SQLITE_OMIT_GLOBALRECOVER
84369 /*
84370 ** This function is now an anachronism. It used to be used to recover from a
84371 ** malloc() failure, but SQLite now does this automatically.
84372 */
84373 SQLITE_API int sqlite3_global_recover(void){
84374   return SQLITE_OK;
84375 }
84376 #endif
84377
84378 /*
84379 ** Test to see whether or not the database connection is in autocommit
84380 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
84381 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
84382 ** by the next COMMIT or ROLLBACK.
84383 **
84384 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
84385 */
84386 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
84387   return db->autoCommit;
84388 }
84389
84390 #ifdef SQLITE_DEBUG
84391 /*
84392 ** The following routine is subtituted for constant SQLITE_CORRUPT in
84393 ** debugging builds.  This provides a way to set a breakpoint for when
84394 ** corruption is first detected.
84395 */
84396 SQLITE_PRIVATE int sqlite3Corrupt(void){
84397   return SQLITE_CORRUPT;
84398 }
84399 #endif
84400
84401 /*
84402 ** This is a convenience routine that makes sure that all thread-specific
84403 ** data for this thread has been deallocated.
84404 **
84405 ** SQLite no longer uses thread-specific data so this routine is now a
84406 ** no-op.  It is retained for historical compatibility.
84407 */
84408 SQLITE_API void sqlite3_thread_cleanup(void){
84409 }
84410
84411 /*
84412 ** Return meta information about a specific column of a database table.
84413 ** See comment in sqlite3.h (sqlite.h.in) for details.
84414 */
84415 #ifdef SQLITE_ENABLE_COLUMN_METADATA
84416 SQLITE_API int sqlite3_table_column_metadata(
84417   sqlite3 *db,                /* Connection handle */
84418   const char *zDbName,        /* Database name or NULL */
84419   const char *zTableName,     /* Table name */
84420   const char *zColumnName,    /* Column name */
84421   char const **pzDataType,    /* OUTPUT: Declared data type */
84422   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
84423   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
84424   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
84425   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
84426 ){
84427   int rc;
84428   char *zErrMsg = 0;
84429   Table *pTab = 0;
84430   Column *pCol = 0;
84431   int iCol;
84432
84433   char const *zDataType = 0;
84434   char const *zCollSeq = 0;
84435   int notnull = 0;
84436   int primarykey = 0;
84437   int autoinc = 0;
84438
84439   /* Ensure the database schema has been loaded */
84440   sqlite3_mutex_enter(db->mutex);
84441   (void)sqlite3SafetyOn(db);
84442   sqlite3BtreeEnterAll(db);
84443   rc = sqlite3Init(db, &zErrMsg);
84444   sqlite3BtreeLeaveAll(db);
84445   if( SQLITE_OK!=rc ){
84446     goto error_out;
84447   }
84448
84449   /* Locate the table in question */
84450   pTab = sqlite3FindTable(db, zTableName, zDbName);
84451   if( !pTab || pTab->pSelect ){
84452     pTab = 0;
84453     goto error_out;
84454   }
84455
84456   /* Find the column for which info is requested */
84457   if( sqlite3IsRowid(zColumnName) ){
84458     iCol = pTab->iPKey;
84459     if( iCol>=0 ){
84460       pCol = &pTab->aCol[iCol];
84461     }
84462   }else{
84463     for(iCol=0; iCol<pTab->nCol; iCol++){
84464       pCol = &pTab->aCol[iCol];
84465       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
84466         break;
84467       }
84468     }
84469     if( iCol==pTab->nCol ){
84470       pTab = 0;
84471       goto error_out;
84472     }
84473   }
84474
84475   /* The following block stores the meta information that will be returned
84476   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
84477   ** and autoinc. At this point there are two possibilities:
84478   ** 
84479   **     1. The specified column name was rowid", "oid" or "_rowid_" 
84480   **        and there is no explicitly declared IPK column. 
84481   **
84482   **     2. The table is not a view and the column name identified an 
84483   **        explicitly declared column. Copy meta information from *pCol.
84484   */ 
84485   if( pCol ){
84486     zDataType = pCol->zType;
84487     zCollSeq = pCol->zColl;
84488     notnull = pCol->notNull!=0;
84489     primarykey  = pCol->isPrimKey!=0;
84490     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
84491   }else{
84492     zDataType = "INTEGER";
84493     primarykey = 1;
84494   }
84495   if( !zCollSeq ){
84496     zCollSeq = "BINARY";
84497   }
84498
84499 error_out:
84500   (void)sqlite3SafetyOff(db);
84501
84502   /* Whether the function call succeeded or failed, set the output parameters
84503   ** to whatever their local counterparts contain. If an error did occur,
84504   ** this has the effect of zeroing all output parameters.
84505   */
84506   if( pzDataType ) *pzDataType = zDataType;
84507   if( pzCollSeq ) *pzCollSeq = zCollSeq;
84508   if( pNotNull ) *pNotNull = notnull;
84509   if( pPrimaryKey ) *pPrimaryKey = primarykey;
84510   if( pAutoinc ) *pAutoinc = autoinc;
84511
84512   if( SQLITE_OK==rc && !pTab ){
84513     sqlite3DbFree(db, zErrMsg);
84514     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
84515         zColumnName);
84516     rc = SQLITE_ERROR;
84517   }
84518   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
84519   sqlite3DbFree(db, zErrMsg);
84520   rc = sqlite3ApiExit(db, rc);
84521   sqlite3_mutex_leave(db->mutex);
84522   return rc;
84523 }
84524 #endif
84525
84526 /*
84527 ** Sleep for a little while.  Return the amount of time slept.
84528 */
84529 SQLITE_API int sqlite3_sleep(int ms){
84530   sqlite3_vfs *pVfs;
84531   int rc;
84532   pVfs = sqlite3_vfs_find(0);
84533   if( pVfs==0 ) return 0;
84534
84535   /* This function works in milliseconds, but the underlying OsSleep() 
84536   ** API uses microseconds. Hence the 1000's.
84537   */
84538   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
84539   return rc;
84540 }
84541
84542 /*
84543 ** Enable or disable the extended result codes.
84544 */
84545 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
84546   sqlite3_mutex_enter(db->mutex);
84547   db->errMask = onoff ? 0xffffffff : 0xff;
84548   sqlite3_mutex_leave(db->mutex);
84549   return SQLITE_OK;
84550 }
84551
84552 /*
84553 ** Invoke the xFileControl method on a particular database.
84554 */
84555 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
84556   int rc = SQLITE_ERROR;
84557   int iDb;
84558   sqlite3_mutex_enter(db->mutex);
84559   if( zDbName==0 ){
84560     iDb = 0;
84561   }else{
84562     for(iDb=0; iDb<db->nDb; iDb++){
84563       if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
84564     }
84565   }
84566   if( iDb<db->nDb ){
84567     Btree *pBtree = db->aDb[iDb].pBt;
84568     if( pBtree ){
84569       Pager *pPager;
84570       sqlite3_file *fd;
84571       sqlite3BtreeEnter(pBtree);
84572       pPager = sqlite3BtreePager(pBtree);
84573       assert( pPager!=0 );
84574       fd = sqlite3PagerFile(pPager);
84575       assert( fd!=0 );
84576       if( fd->pMethods ){
84577         rc = sqlite3OsFileControl(fd, op, pArg);
84578       }
84579       sqlite3BtreeLeave(pBtree);
84580     }
84581   }
84582   sqlite3_mutex_leave(db->mutex);
84583   return rc;   
84584 }
84585
84586 /*
84587 ** Interface to the testing logic.
84588 */
84589 SQLITE_API int sqlite3_test_control(int op, ...){
84590   int rc = 0;
84591 #ifndef SQLITE_OMIT_BUILTIN_TEST
84592   va_list ap;
84593   va_start(ap, op);
84594   switch( op ){
84595
84596     /*
84597     ** Save the current state of the PRNG.
84598     */
84599     case SQLITE_TESTCTRL_PRNG_SAVE: {
84600       sqlite3PrngSaveState();
84601       break;
84602     }
84603
84604     /*
84605     ** Restore the state of the PRNG to the last state saved using
84606     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
84607     ** this verb acts like PRNG_RESET.
84608     */
84609     case SQLITE_TESTCTRL_PRNG_RESTORE: {
84610       sqlite3PrngRestoreState();
84611       break;
84612     }
84613
84614     /*
84615     ** Reset the PRNG back to its uninitialized state.  The next call
84616     ** to sqlite3_randomness() will reseed the PRNG using a single call
84617     ** to the xRandomness method of the default VFS.
84618     */
84619     case SQLITE_TESTCTRL_PRNG_RESET: {
84620       sqlite3PrngResetState();
84621       break;
84622     }
84623
84624     /*
84625     **  sqlite3_test_control(BITVEC_TEST, size, program)
84626     **
84627     ** Run a test against a Bitvec object of size.  The program argument
84628     ** is an array of integers that defines the test.  Return -1 on a
84629     ** memory allocation error, 0 on success, or non-zero for an error.
84630     ** See the sqlite3BitvecBuiltinTest() for additional information.
84631     */
84632     case SQLITE_TESTCTRL_BITVEC_TEST: {
84633       int sz = va_arg(ap, int);
84634       int *aProg = va_arg(ap, int*);
84635       rc = sqlite3BitvecBuiltinTest(sz, aProg);
84636       break;
84637     }
84638
84639     /*
84640     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
84641     **
84642     ** Register hooks to call to indicate which malloc() failures 
84643     ** are benign.
84644     */
84645     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
84646       typedef void (*void_function)(void);
84647       void_function xBenignBegin;
84648       void_function xBenignEnd;
84649       xBenignBegin = va_arg(ap, void_function);
84650       xBenignEnd = va_arg(ap, void_function);
84651       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
84652       break;
84653     }
84654   }
84655   va_end(ap);
84656 #endif /* SQLITE_OMIT_BUILTIN_TEST */
84657   return rc;
84658 }
84659
84660 /************** End of main.c ************************************************/
84661 /************** Begin file fts3.c ********************************************/
84662 /*
84663 ** 2006 Oct 10
84664 **
84665 ** The author disclaims copyright to this source code.  In place of
84666 ** a legal notice, here is a blessing:
84667 **
84668 **    May you do good and not evil.
84669 **    May you find forgiveness for yourself and forgive others.
84670 **    May you share freely, never taking more than you give.
84671 **
84672 ******************************************************************************
84673 **
84674 ** This is an SQLite module implementing full-text search.
84675 */
84676
84677 /*
84678 ** The code in this file is only compiled if:
84679 **
84680 **     * The FTS3 module is being built as an extension
84681 **       (in which case SQLITE_CORE is not defined), or
84682 **
84683 **     * The FTS3 module is being built into the core of
84684 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
84685 */
84686
84687 /* TODO(shess) Consider exporting this comment to an HTML file or the
84688 ** wiki.
84689 */
84690 /* The full-text index is stored in a series of b+tree (-like)
84691 ** structures called segments which map terms to doclists.  The
84692 ** structures are like b+trees in layout, but are constructed from the
84693 ** bottom up in optimal fashion and are not updatable.  Since trees
84694 ** are built from the bottom up, things will be described from the
84695 ** bottom up.
84696 **
84697 **
84698 **** Varints ****
84699 ** The basic unit of encoding is a variable-length integer called a
84700 ** varint.  We encode variable-length integers in little-endian order
84701 ** using seven bits * per byte as follows:
84702 **
84703 ** KEY:
84704 **         A = 0xxxxxxx    7 bits of data and one flag bit
84705 **         B = 1xxxxxxx    7 bits of data and one flag bit
84706 **
84707 **  7 bits - A
84708 ** 14 bits - BA
84709 ** 21 bits - BBA
84710 ** and so on.
84711 **
84712 ** This is identical to how sqlite encodes varints (see util.c).
84713 **
84714 **
84715 **** Document lists ****
84716 ** A doclist (document list) holds a docid-sorted list of hits for a
84717 ** given term.  Doclists hold docids, and can optionally associate
84718 ** token positions and offsets with docids.
84719 **
84720 ** A DL_POSITIONS_OFFSETS doclist is stored like this:
84721 **
84722 ** array {
84723 **   varint docid;
84724 **   array {                (position list for column 0)
84725 **     varint position;     (delta from previous position plus POS_BASE)
84726 **     varint startOffset;  (delta from previous startOffset)
84727 **     varint endOffset;    (delta from startOffset)
84728 **   }
84729 **   array {
84730 **     varint POS_COLUMN;   (marks start of position list for new column)
84731 **     varint column;       (index of new column)
84732 **     array {
84733 **       varint position;   (delta from previous position plus POS_BASE)
84734 **       varint startOffset;(delta from previous startOffset)
84735 **       varint endOffset;  (delta from startOffset)
84736 **     }
84737 **   }
84738 **   varint POS_END;        (marks end of positions for this document.
84739 ** }
84740 **
84741 ** Here, array { X } means zero or more occurrences of X, adjacent in
84742 ** memory.  A "position" is an index of a token in the token stream
84743 ** generated by the tokenizer, while an "offset" is a byte offset,
84744 ** both based at 0.  Note that POS_END and POS_COLUMN occur in the
84745 ** same logical place as the position element, and act as sentinals
84746 ** ending a position list array.
84747 **
84748 ** A DL_POSITIONS doclist omits the startOffset and endOffset
84749 ** information.  A DL_DOCIDS doclist omits both the position and
84750 ** offset information, becoming an array of varint-encoded docids.
84751 **
84752 ** On-disk data is stored as type DL_DEFAULT, so we don't serialize
84753 ** the type.  Due to how deletion is implemented in the segmentation
84754 ** system, on-disk doclists MUST store at least positions.
84755 **
84756 **
84757 **** Segment leaf nodes ****
84758 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
84759 ** nodes are written using LeafWriter, and read using LeafReader (to
84760 ** iterate through a single leaf node's data) and LeavesReader (to
84761 ** iterate through a segment's entire leaf layer).  Leaf nodes have
84762 ** the format:
84763 **
84764 ** varint iHeight;             (height from leaf level, always 0)
84765 ** varint nTerm;               (length of first term)
84766 ** char pTerm[nTerm];          (content of first term)
84767 ** varint nDoclist;            (length of term's associated doclist)
84768 ** char pDoclist[nDoclist];    (content of doclist)
84769 ** array {
84770 **                             (further terms are delta-encoded)
84771 **   varint nPrefix;           (length of prefix shared with previous term)
84772 **   varint nSuffix;           (length of unshared suffix)
84773 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
84774 **   varint nDoclist;          (length of term's associated doclist)
84775 **   char pDoclist[nDoclist];  (content of doclist)
84776 ** }
84777 **
84778 ** Here, array { X } means zero or more occurrences of X, adjacent in
84779 ** memory.
84780 **
84781 ** Leaf nodes are broken into blocks which are stored contiguously in
84782 ** the %_segments table in sorted order.  This means that when the end
84783 ** of a node is reached, the next term is in the node with the next
84784 ** greater node id.
84785 **
84786 ** New data is spilled to a new leaf node when the current node
84787 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
84788 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
84789 ** node (a leaf node with a single term and doclist).  The goal of
84790 ** these settings is to pack together groups of small doclists while
84791 ** making it efficient to directly access large doclists.  The
84792 ** assumption is that large doclists represent terms which are more
84793 ** likely to be query targets.
84794 **
84795 ** TODO(shess) It may be useful for blocking decisions to be more
84796 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
84797 ** node rather than splitting into 2k and .5k nodes.  My intuition is
84798 ** that this might extend through 2x or 4x the pagesize.
84799 **
84800 **
84801 **** Segment interior nodes ****
84802 ** Segment interior nodes store blockids for subtree nodes and terms
84803 ** to describe what data is stored by the each subtree.  Interior
84804 ** nodes are written using InteriorWriter, and read using
84805 ** InteriorReader.  InteriorWriters are created as needed when
84806 ** SegmentWriter creates new leaf nodes, or when an interior node
84807 ** itself grows too big and must be split.  The format of interior
84808 ** nodes:
84809 **
84810 ** varint iHeight;           (height from leaf level, always >0)
84811 ** varint iBlockid;          (block id of node's leftmost subtree)
84812 ** optional {
84813 **   varint nTerm;           (length of first term)
84814 **   char pTerm[nTerm];      (content of first term)
84815 **   array {
84816 **                                (further terms are delta-encoded)
84817 **     varint nPrefix;            (length of shared prefix with previous term)
84818 **     varint nSuffix;            (length of unshared suffix)
84819 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
84820 **   }
84821 ** }
84822 **
84823 ** Here, optional { X } means an optional element, while array { X }
84824 ** means zero or more occurrences of X, adjacent in memory.
84825 **
84826 ** An interior node encodes n terms separating n+1 subtrees.  The
84827 ** subtree blocks are contiguous, so only the first subtree's blockid
84828 ** is encoded.  The subtree at iBlockid will contain all terms less
84829 ** than the first term encoded (or all terms if no term is encoded).
84830 ** Otherwise, for terms greater than or equal to pTerm[i] but less
84831 ** than pTerm[i+1], the subtree for that term will be rooted at
84832 ** iBlockid+i.  Interior nodes only store enough term data to
84833 ** distinguish adjacent children (if the rightmost term of the left
84834 ** child is "something", and the leftmost term of the right child is
84835 ** "wicked", only "w" is stored).
84836 **
84837 ** New data is spilled to a new interior node at the same height when
84838 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
84839 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
84840 ** interior nodes and making the tree too skinny.  The interior nodes
84841 ** at a given height are naturally tracked by interior nodes at
84842 ** height+1, and so on.
84843 **
84844 **
84845 **** Segment directory ****
84846 ** The segment directory in table %_segdir stores meta-information for
84847 ** merging and deleting segments, and also the root node of the
84848 ** segment's tree.
84849 **
84850 ** The root node is the top node of the segment's tree after encoding
84851 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
84852 ** This could be either a leaf node or an interior node.  If the top
84853 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
84854 ** and a new root interior node is generated (which should always fit
84855 ** within ROOT_MAX because it only needs space for 2 varints, the
84856 ** height and the blockid of the previous root).
84857 **
84858 ** The meta-information in the segment directory is:
84859 **   level               - segment level (see below)
84860 **   idx                 - index within level
84861 **                       - (level,idx uniquely identify a segment)
84862 **   start_block         - first leaf node
84863 **   leaves_end_block    - last leaf node
84864 **   end_block           - last block (including interior nodes)
84865 **   root                - contents of root node
84866 **
84867 ** If the root node is a leaf node, then start_block,
84868 ** leaves_end_block, and end_block are all 0.
84869 **
84870 **
84871 **** Segment merging ****
84872 ** To amortize update costs, segments are groups into levels and
84873 ** merged in matches.  Each increase in level represents exponentially
84874 ** more documents.
84875 **
84876 ** New documents (actually, document updates) are tokenized and
84877 ** written individually (using LeafWriter) to a level 0 segment, with
84878 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
84879 ** level 0 segments are merged into a single level 1 segment.  Level 1
84880 ** is populated like level 0, and eventually MERGE_COUNT level 1
84881 ** segments are merged to a single level 2 segment (representing
84882 ** MERGE_COUNT^2 updates), and so on.
84883 **
84884 ** A segment merge traverses all segments at a given level in
84885 ** parallel, performing a straightforward sorted merge.  Since segment
84886 ** leaf nodes are written in to the %_segments table in order, this
84887 ** merge traverses the underlying sqlite disk structures efficiently.
84888 ** After the merge, all segment blocks from the merged level are
84889 ** deleted.
84890 **
84891 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
84892 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
84893 ** very similar performance numbers to 16 on insertion, though they're
84894 ** a tiny bit slower (perhaps due to more overhead in merge-time
84895 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
84896 ** 16, 2 about 66% slower than 16.
84897 **
84898 ** At query time, high MERGE_COUNT increases the number of segments
84899 ** which need to be scanned and merged.  For instance, with 100k docs
84900 ** inserted:
84901 **
84902 **    MERGE_COUNT   segments
84903 **       16           25
84904 **        8           12
84905 **        4           10
84906 **        2            6
84907 **
84908 ** This appears to have only a moderate impact on queries for very
84909 ** frequent terms (which are somewhat dominated by segment merge
84910 ** costs), and infrequent and non-existent terms still seem to be fast
84911 ** even with many segments.
84912 **
84913 ** TODO(shess) That said, it would be nice to have a better query-side
84914 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
84915 ** optimizations to things like doclist merging will swing the sweet
84916 ** spot around.
84917 **
84918 **
84919 **
84920 **** Handling of deletions and updates ****
84921 ** Since we're using a segmented structure, with no docid-oriented
84922 ** index into the term index, we clearly cannot simply update the term
84923 ** index when a document is deleted or updated.  For deletions, we
84924 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
84925 ** we simply write the new doclist.  Segment merges overwrite older
84926 ** data for a particular docid with newer data, so deletes or updates
84927 ** will eventually overtake the earlier data and knock it out.  The
84928 ** query logic likewise merges doclists so that newer data knocks out
84929 ** older data.
84930 **
84931 ** TODO(shess) Provide a VACUUM type operation to clear out all
84932 ** deletions and duplications.  This would basically be a forced merge
84933 ** into a single segment.
84934 */
84935
84936 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
84937
84938 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
84939 # define SQLITE_CORE 1
84940 #endif
84941
84942
84943 /************** Include fts3_hash.h in the middle of fts3.c ******************/
84944 /************** Begin file fts3_hash.h ***************************************/
84945 /*
84946 ** 2001 September 22
84947 **
84948 ** The author disclaims copyright to this source code.  In place of
84949 ** a legal notice, here is a blessing:
84950 **
84951 **    May you do good and not evil.
84952 **    May you find forgiveness for yourself and forgive others.
84953 **    May you share freely, never taking more than you give.
84954 **
84955 *************************************************************************
84956 ** This is the header file for the generic hash-table implemenation
84957 ** used in SQLite.  We've modified it slightly to serve as a standalone
84958 ** hash table implementation for the full-text indexing module.
84959 **
84960 */
84961 #ifndef _FTS3_HASH_H_
84962 #define _FTS3_HASH_H_
84963
84964 /* Forward declarations of structures. */
84965 typedef struct fts3Hash fts3Hash;
84966 typedef struct fts3HashElem fts3HashElem;
84967
84968 /* A complete hash table is an instance of the following structure.
84969 ** The internals of this structure are intended to be opaque -- client
84970 ** code should not attempt to access or modify the fields of this structure
84971 ** directly.  Change this structure only by using the routines below.
84972 ** However, many of the "procedures" and "functions" for modifying and
84973 ** accessing this structure are really macros, so we can't really make
84974 ** this structure opaque.
84975 */
84976 struct fts3Hash {
84977   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
84978   char copyKey;           /* True if copy of key made on insert */
84979   int count;              /* Number of entries in this table */
84980   fts3HashElem *first;    /* The first element of the array */
84981   int htsize;             /* Number of buckets in the hash table */
84982   struct _fts3ht {        /* the hash table */
84983     int count;               /* Number of entries with this hash */
84984     fts3HashElem *chain;     /* Pointer to first entry with this hash */
84985   } *ht;
84986 };
84987
84988 /* Each element in the hash table is an instance of the following 
84989 ** structure.  All elements are stored on a single doubly-linked list.
84990 **
84991 ** Again, this structure is intended to be opaque, but it can't really
84992 ** be opaque because it is used by macros.
84993 */
84994 struct fts3HashElem {
84995   fts3HashElem *next, *prev; /* Next and previous elements in the table */
84996   void *data;                /* Data associated with this element */
84997   void *pKey; int nKey;      /* Key associated with this element */
84998 };
84999
85000 /*
85001 ** There are 2 different modes of operation for a hash table:
85002 **
85003 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
85004 **                           (including the null-terminator, if any).  Case
85005 **                           is respected in comparisons.
85006 **
85007 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
85008 **                           memcmp() is used to compare keys.
85009 **
85010 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
85011 */
85012 #define FTS3_HASH_STRING    1
85013 #define FTS3_HASH_BINARY    2
85014
85015 /*
85016 ** Access routines.  To delete, insert a NULL pointer.
85017 */
85018 SQLITE_PRIVATE void sqlite3Fts3HashInit(fts3Hash*, int keytype, int copyKey);
85019 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(fts3Hash*, const void *pKey, int nKey, void *pData);
85020 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const fts3Hash*, const void *pKey, int nKey);
85021 SQLITE_PRIVATE void sqlite3Fts3HashClear(fts3Hash*);
85022
85023 /*
85024 ** Shorthand for the functions above
85025 */
85026 #define fts3HashInit   sqlite3Fts3HashInit
85027 #define fts3HashInsert sqlite3Fts3HashInsert
85028 #define fts3HashFind   sqlite3Fts3HashFind
85029 #define fts3HashClear  sqlite3Fts3HashClear
85030
85031 /*
85032 ** Macros for looping over all elements of a hash table.  The idiom is
85033 ** like this:
85034 **
85035 **   fts3Hash h;
85036 **   fts3HashElem *p;
85037 **   ...
85038 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
85039 **     SomeStructure *pData = fts3HashData(p);
85040 **     // do something with pData
85041 **   }
85042 */
85043 #define fts3HashFirst(H)  ((H)->first)
85044 #define fts3HashNext(E)   ((E)->next)
85045 #define fts3HashData(E)   ((E)->data)
85046 #define fts3HashKey(E)    ((E)->pKey)
85047 #define fts3HashKeysize(E) ((E)->nKey)
85048
85049 /*
85050 ** Number of entries in a hash table
85051 */
85052 #define fts3HashCount(H)  ((H)->count)
85053
85054 #endif /* _FTS3_HASH_H_ */
85055
85056 /************** End of fts3_hash.h *******************************************/
85057 /************** Continuing where we left off in fts3.c ***********************/
85058 /************** Include fts3_tokenizer.h in the middle of fts3.c *************/
85059 /************** Begin file fts3_tokenizer.h **********************************/
85060 /*
85061 ** 2006 July 10
85062 **
85063 ** The author disclaims copyright to this source code.
85064 **
85065 *************************************************************************
85066 ** Defines the interface to tokenizers used by fulltext-search.  There
85067 ** are three basic components:
85068 **
85069 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
85070 ** interface functions.  This is essentially the class structure for
85071 ** tokenizers.
85072 **
85073 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
85074 ** including customization information defined at creation time.
85075 **
85076 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
85077 ** tokens from a particular input.
85078 */
85079 #ifndef _FTS3_TOKENIZER_H_
85080 #define _FTS3_TOKENIZER_H_
85081
85082 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
85083 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
85084 ** we will need a way to register the API consistently.
85085 */
85086
85087 /*
85088 ** Structures used by the tokenizer interface. When a new tokenizer
85089 ** implementation is registered, the caller provides a pointer to
85090 ** an sqlite3_tokenizer_module containing pointers to the callback
85091 ** functions that make up an implementation.
85092 **
85093 ** When an fts3 table is created, it passes any arguments passed to
85094 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
85095 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
85096 ** implementation. The xCreate() function in turn returns an 
85097 ** sqlite3_tokenizer structure representing the specific tokenizer to
85098 ** be used for the fts3 table (customized by the tokenizer clause arguments).
85099 **
85100 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
85101 ** method is called. It returns an sqlite3_tokenizer_cursor object
85102 ** that may be used to tokenize a specific input buffer based on
85103 ** the tokenization rules supplied by a specific sqlite3_tokenizer
85104 ** object.
85105 */
85106 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
85107 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
85108 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
85109
85110 struct sqlite3_tokenizer_module {
85111
85112   /*
85113   ** Structure version. Should always be set to 0.
85114   */
85115   int iVersion;
85116
85117   /*
85118   ** Create a new tokenizer. The values in the argv[] array are the
85119   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
85120   ** TABLE statement that created the fts3 table. For example, if
85121   ** the following SQL is executed:
85122   **
85123   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
85124   **
85125   ** then argc is set to 2, and the argv[] array contains pointers
85126   ** to the strings "arg1" and "arg2".
85127   **
85128   ** This method should return either SQLITE_OK (0), or an SQLite error 
85129   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
85130   ** to point at the newly created tokenizer structure. The generic
85131   ** sqlite3_tokenizer.pModule variable should not be initialised by
85132   ** this callback. The caller will do so.
85133   */
85134   int (*xCreate)(
85135     int argc,                           /* Size of argv array */
85136     const char *const*argv,             /* Tokenizer argument strings */
85137     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
85138   );
85139
85140   /*
85141   ** Destroy an existing tokenizer. The fts3 module calls this method
85142   ** exactly once for each successful call to xCreate().
85143   */
85144   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
85145
85146   /*
85147   ** Create a tokenizer cursor to tokenize an input buffer. The caller
85148   ** is responsible for ensuring that the input buffer remains valid
85149   ** until the cursor is closed (using the xClose() method). 
85150   */
85151   int (*xOpen)(
85152     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
85153     const char *pInput, int nBytes,      /* Input buffer */
85154     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
85155   );
85156
85157   /*
85158   ** Destroy an existing tokenizer cursor. The fts3 module calls this 
85159   ** method exactly once for each successful call to xOpen().
85160   */
85161   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
85162
85163   /*
85164   ** Retrieve the next token from the tokenizer cursor pCursor. This
85165   ** method should either return SQLITE_OK and set the values of the
85166   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
85167   ** the end of the buffer has been reached, or an SQLite error code.
85168   **
85169   ** *ppToken should be set to point at a buffer containing the 
85170   ** normalized version of the token (i.e. after any case-folding and/or
85171   ** stemming has been performed). *pnBytes should be set to the length
85172   ** of this buffer in bytes. The input text that generated the token is
85173   ** identified by the byte offsets returned in *piStartOffset and
85174   ** *piEndOffset.
85175   **
85176   ** The buffer *ppToken is set to point at is managed by the tokenizer
85177   ** implementation. It is only required to be valid until the next call
85178   ** to xNext() or xClose(). 
85179   */
85180   /* TODO(shess) current implementation requires pInput to be
85181   ** nul-terminated.  This should either be fixed, or pInput/nBytes
85182   ** should be converted to zInput.
85183   */
85184   int (*xNext)(
85185     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
85186     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
85187     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
85188     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
85189     int *piPosition      /* OUT: Number of tokens returned before this one */
85190   );
85191 };
85192
85193 struct sqlite3_tokenizer {
85194   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
85195   /* Tokenizer implementations will typically add additional fields */
85196 };
85197
85198 struct sqlite3_tokenizer_cursor {
85199   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
85200   /* Tokenizer implementations will typically add additional fields */
85201 };
85202
85203 #endif /* _FTS3_TOKENIZER_H_ */
85204
85205 /************** End of fts3_tokenizer.h **************************************/
85206 /************** Continuing where we left off in fts3.c ***********************/
85207 #ifndef SQLITE_CORE 
85208   SQLITE_EXTENSION_INIT1
85209 #endif
85210
85211
85212 /* TODO(shess) MAN, this thing needs some refactoring.  At minimum, it
85213 ** would be nice to order the file better, perhaps something along the
85214 ** lines of:
85215 **
85216 **  - utility functions
85217 **  - table setup functions
85218 **  - table update functions
85219 **  - table query functions
85220 **
85221 ** Put the query functions last because they're likely to reference
85222 ** typedefs or functions from the table update section.
85223 */
85224
85225 #if 0
85226 # define FTSTRACE(A)  printf A; fflush(stdout)
85227 #else
85228 # define FTSTRACE(A)
85229 #endif
85230
85231 /*
85232 ** Default span for NEAR operators.
85233 */
85234 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
85235
85236 /* It is not safe to call isspace(), tolower(), or isalnum() on
85237 ** hi-bit-set characters.  This is the same solution used in the
85238 ** tokenizer.
85239 */
85240 /* TODO(shess) The snippet-generation code should be using the
85241 ** tokenizer-generated tokens rather than doing its own local
85242 ** tokenization.
85243 */
85244 /* TODO(shess) Is __isascii() a portable version of (c&0x80)==0? */
85245 static int safe_isspace(char c){
85246   return (c&0x80)==0 ? isspace(c) : 0;
85247 }
85248 static int safe_tolower(char c){
85249   return (c&0x80)==0 ? tolower(c) : c;
85250 }
85251 static int safe_isalnum(char c){
85252   return (c&0x80)==0 ? isalnum(c) : 0;
85253 }
85254
85255 typedef enum DocListType {
85256   DL_DOCIDS,              /* docids only */
85257   DL_POSITIONS,           /* docids + positions */
85258   DL_POSITIONS_OFFSETS    /* docids + positions + offsets */
85259 } DocListType;
85260
85261 /*
85262 ** By default, only positions and not offsets are stored in the doclists.
85263 ** To change this so that offsets are stored too, compile with
85264 **
85265 **          -DDL_DEFAULT=DL_POSITIONS_OFFSETS
85266 **
85267 ** If DL_DEFAULT is set to DL_DOCIDS, your table can only be inserted
85268 ** into (no deletes or updates).
85269 */
85270 #ifndef DL_DEFAULT
85271 # define DL_DEFAULT DL_POSITIONS
85272 #endif
85273
85274 enum {
85275   POS_END = 0,        /* end of this position list */
85276   POS_COLUMN,         /* followed by new column number */
85277   POS_BASE
85278 };
85279
85280 /* MERGE_COUNT controls how often we merge segments (see comment at
85281 ** top of file).
85282 */
85283 #define MERGE_COUNT 16
85284
85285 /* utility functions */
85286
85287 /* CLEAR() and SCRAMBLE() abstract memset() on a pointer to a single
85288 ** record to prevent errors of the form:
85289 **
85290 ** my_function(SomeType *b){
85291 **   memset(b, '\0', sizeof(b));  // sizeof(b)!=sizeof(*b)
85292 ** }
85293 */
85294 /* TODO(shess) Obvious candidates for a header file. */
85295 #define CLEAR(b) memset(b, '\0', sizeof(*(b)))
85296
85297 #ifndef NDEBUG
85298 #  define SCRAMBLE(b) memset(b, 0x55, sizeof(*(b)))
85299 #else
85300 #  define SCRAMBLE(b)
85301 #endif
85302
85303 /* We may need up to VARINT_MAX bytes to store an encoded 64-bit integer. */
85304 #define VARINT_MAX 10
85305
85306 /* Write a 64-bit variable-length integer to memory starting at p[0].
85307  * The length of data written will be between 1 and VARINT_MAX bytes.
85308  * The number of bytes written is returned. */
85309 static int fts3PutVarint(char *p, sqlite_int64 v){
85310   unsigned char *q = (unsigned char *) p;
85311   sqlite_uint64 vu = v;
85312   do{
85313     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
85314     vu >>= 7;
85315   }while( vu!=0 );
85316   q[-1] &= 0x7f;  /* turn off high bit in final byte */
85317   assert( q - (unsigned char *)p <= VARINT_MAX );
85318   return (int) (q - (unsigned char *)p);
85319 }
85320
85321 /* Read a 64-bit variable-length integer from memory starting at p[0].
85322  * Return the number of bytes read, or 0 on error.
85323  * The value is stored in *v. */
85324 static int fts3GetVarint(const char *p, sqlite_int64 *v){
85325   const unsigned char *q = (const unsigned char *) p;
85326   sqlite_uint64 x = 0, y = 1;
85327   while( (*q & 0x80) == 0x80 ){
85328     x += y * (*q++ & 0x7f);
85329     y <<= 7;
85330     if( q - (unsigned char *)p >= VARINT_MAX ){  /* bad data */
85331       assert( 0 );
85332       return 0;
85333     }
85334   }
85335   x += y * (*q++);
85336   *v = (sqlite_int64) x;
85337   return (int) (q - (unsigned char *)p);
85338 }
85339
85340 static int fts3GetVarint32(const char *p, int *pi){
85341  sqlite_int64 i;
85342  int ret = fts3GetVarint(p, &i);
85343  *pi = (int) i;
85344  assert( *pi==i );
85345  return ret;
85346 }
85347
85348 /*******************************************************************/
85349 /* DataBuffer is used to collect data into a buffer in piecemeal
85350 ** fashion.  It implements the usual distinction between amount of
85351 ** data currently stored (nData) and buffer capacity (nCapacity).
85352 **
85353 ** dataBufferInit - create a buffer with given initial capacity.
85354 ** dataBufferReset - forget buffer's data, retaining capacity.
85355 ** dataBufferDestroy - free buffer's data.
85356 ** dataBufferSwap - swap contents of two buffers.
85357 ** dataBufferExpand - expand capacity without adding data.
85358 ** dataBufferAppend - append data.
85359 ** dataBufferAppend2 - append two pieces of data at once.
85360 ** dataBufferReplace - replace buffer's data.
85361 */
85362 typedef struct DataBuffer {
85363   char *pData;          /* Pointer to malloc'ed buffer. */
85364   int nCapacity;        /* Size of pData buffer. */
85365   int nData;            /* End of data loaded into pData. */
85366 } DataBuffer;
85367
85368 static void dataBufferInit(DataBuffer *pBuffer, int nCapacity){
85369   assert( nCapacity>=0 );
85370   pBuffer->nData = 0;
85371   pBuffer->nCapacity = nCapacity;
85372   pBuffer->pData = nCapacity==0 ? NULL : sqlite3_malloc(nCapacity);
85373 }
85374 static void dataBufferReset(DataBuffer *pBuffer){
85375   pBuffer->nData = 0;
85376 }
85377 static void dataBufferDestroy(DataBuffer *pBuffer){
85378   if( pBuffer->pData!=NULL ) sqlite3_free(pBuffer->pData);
85379   SCRAMBLE(pBuffer);
85380 }
85381 static void dataBufferSwap(DataBuffer *pBuffer1, DataBuffer *pBuffer2){
85382   DataBuffer tmp = *pBuffer1;
85383   *pBuffer1 = *pBuffer2;
85384   *pBuffer2 = tmp;
85385 }
85386 static void dataBufferExpand(DataBuffer *pBuffer, int nAddCapacity){
85387   assert( nAddCapacity>0 );
85388   /* TODO(shess) Consider expanding more aggressively.  Note that the
85389   ** underlying malloc implementation may take care of such things for
85390   ** us already.
85391   */
85392   if( pBuffer->nData+nAddCapacity>pBuffer->nCapacity ){
85393     pBuffer->nCapacity = pBuffer->nData+nAddCapacity;
85394     pBuffer->pData = sqlite3_realloc(pBuffer->pData, pBuffer->nCapacity);
85395   }
85396 }
85397 static void dataBufferAppend(DataBuffer *pBuffer,
85398                              const char *pSource, int nSource){
85399   assert( nSource>0 && pSource!=NULL );
85400   dataBufferExpand(pBuffer, nSource);
85401   memcpy(pBuffer->pData+pBuffer->nData, pSource, nSource);
85402   pBuffer->nData += nSource;
85403 }
85404 static void dataBufferAppend2(DataBuffer *pBuffer,
85405                               const char *pSource1, int nSource1,
85406                               const char *pSource2, int nSource2){
85407   assert( nSource1>0 && pSource1!=NULL );
85408   assert( nSource2>0 && pSource2!=NULL );
85409   dataBufferExpand(pBuffer, nSource1+nSource2);
85410   memcpy(pBuffer->pData+pBuffer->nData, pSource1, nSource1);
85411   memcpy(pBuffer->pData+pBuffer->nData+nSource1, pSource2, nSource2);
85412   pBuffer->nData += nSource1+nSource2;
85413 }
85414 static void dataBufferReplace(DataBuffer *pBuffer,
85415                               const char *pSource, int nSource){
85416   dataBufferReset(pBuffer);
85417   dataBufferAppend(pBuffer, pSource, nSource);
85418 }
85419
85420 /* StringBuffer is a null-terminated version of DataBuffer. */
85421 typedef struct StringBuffer {
85422   DataBuffer b;            /* Includes null terminator. */
85423 } StringBuffer;
85424
85425 static void initStringBuffer(StringBuffer *sb){
85426   dataBufferInit(&sb->b, 100);
85427   dataBufferReplace(&sb->b, "", 1);
85428 }
85429 static int stringBufferLength(StringBuffer *sb){
85430   return sb->b.nData-1;
85431 }
85432 static char *stringBufferData(StringBuffer *sb){
85433   return sb->b.pData;
85434 }
85435 static void stringBufferDestroy(StringBuffer *sb){
85436   dataBufferDestroy(&sb->b);
85437 }
85438
85439 static void nappend(StringBuffer *sb, const char *zFrom, int nFrom){
85440   assert( sb->b.nData>0 );
85441   if( nFrom>0 ){
85442     sb->b.nData--;
85443     dataBufferAppend2(&sb->b, zFrom, nFrom, "", 1);
85444   }
85445 }
85446 static void append(StringBuffer *sb, const char *zFrom){
85447   nappend(sb, zFrom, strlen(zFrom));
85448 }
85449
85450 /* Append a list of strings separated by commas. */
85451 static void appendList(StringBuffer *sb, int nString, char **azString){
85452   int i;
85453   for(i=0; i<nString; ++i){
85454     if( i>0 ) append(sb, ", ");
85455     append(sb, azString[i]);
85456   }
85457 }
85458
85459 static int endsInWhiteSpace(StringBuffer *p){
85460   return stringBufferLength(p)>0 &&
85461     safe_isspace(stringBufferData(p)[stringBufferLength(p)-1]);
85462 }
85463
85464 /* If the StringBuffer ends in something other than white space, add a
85465 ** single space character to the end.
85466 */
85467 static void appendWhiteSpace(StringBuffer *p){
85468   if( stringBufferLength(p)==0 ) return;
85469   if( !endsInWhiteSpace(p) ) append(p, " ");
85470 }
85471
85472 /* Remove white space from the end of the StringBuffer */
85473 static void trimWhiteSpace(StringBuffer *p){
85474   while( endsInWhiteSpace(p) ){
85475     p->b.pData[--p->b.nData-1] = '\0';
85476   }
85477 }
85478
85479 /*******************************************************************/
85480 /* DLReader is used to read document elements from a doclist.  The
85481 ** current docid is cached, so dlrDocid() is fast.  DLReader does not
85482 ** own the doclist buffer.
85483 **
85484 ** dlrAtEnd - true if there's no more data to read.
85485 ** dlrDocid - docid of current document.
85486 ** dlrDocData - doclist data for current document (including docid).
85487 ** dlrDocDataBytes - length of same.
85488 ** dlrAllDataBytes - length of all remaining data.
85489 ** dlrPosData - position data for current document.
85490 ** dlrPosDataLen - length of pos data for current document (incl POS_END).
85491 ** dlrStep - step to current document.
85492 ** dlrInit - initial for doclist of given type against given data.
85493 ** dlrDestroy - clean up.
85494 **
85495 ** Expected usage is something like:
85496 **
85497 **   DLReader reader;
85498 **   dlrInit(&reader, pData, nData);
85499 **   while( !dlrAtEnd(&reader) ){
85500 **     // calls to dlrDocid() and kin.
85501 **     dlrStep(&reader);
85502 **   }
85503 **   dlrDestroy(&reader);
85504 */
85505 typedef struct DLReader {
85506   DocListType iType;
85507   const char *pData;
85508   int nData;
85509
85510   sqlite_int64 iDocid;
85511   int nElement;
85512 } DLReader;
85513
85514 static int dlrAtEnd(DLReader *pReader){
85515   assert( pReader->nData>=0 );
85516   return pReader->nData==0;
85517 }
85518 static sqlite_int64 dlrDocid(DLReader *pReader){
85519   assert( !dlrAtEnd(pReader) );
85520   return pReader->iDocid;
85521 }
85522 static const char *dlrDocData(DLReader *pReader){
85523   assert( !dlrAtEnd(pReader) );
85524   return pReader->pData;
85525 }
85526 static int dlrDocDataBytes(DLReader *pReader){
85527   assert( !dlrAtEnd(pReader) );
85528   return pReader->nElement;
85529 }
85530 static int dlrAllDataBytes(DLReader *pReader){
85531   assert( !dlrAtEnd(pReader) );
85532   return pReader->nData;
85533 }
85534 /* TODO(shess) Consider adding a field to track iDocid varint length
85535 ** to make these two functions faster.  This might matter (a tiny bit)
85536 ** for queries.
85537 */
85538 static const char *dlrPosData(DLReader *pReader){
85539   sqlite_int64 iDummy;
85540   int n = fts3GetVarint(pReader->pData, &iDummy);
85541   assert( !dlrAtEnd(pReader) );
85542   return pReader->pData+n;
85543 }
85544 static int dlrPosDataLen(DLReader *pReader){
85545   sqlite_int64 iDummy;
85546   int n = fts3GetVarint(pReader->pData, &iDummy);
85547   assert( !dlrAtEnd(pReader) );
85548   return pReader->nElement-n;
85549 }
85550 static void dlrStep(DLReader *pReader){
85551   assert( !dlrAtEnd(pReader) );
85552
85553   /* Skip past current doclist element. */
85554   assert( pReader->nElement<=pReader->nData );
85555   pReader->pData += pReader->nElement;
85556   pReader->nData -= pReader->nElement;
85557
85558   /* If there is more data, read the next doclist element. */
85559   if( pReader->nData!=0 ){
85560     sqlite_int64 iDocidDelta;
85561     int iDummy, n = fts3GetVarint(pReader->pData, &iDocidDelta);
85562     pReader->iDocid += iDocidDelta;
85563     if( pReader->iType>=DL_POSITIONS ){
85564       assert( n<pReader->nData );
85565       while( 1 ){
85566         n += fts3GetVarint32(pReader->pData+n, &iDummy);
85567         assert( n<=pReader->nData );
85568         if( iDummy==POS_END ) break;
85569         if( iDummy==POS_COLUMN ){
85570           n += fts3GetVarint32(pReader->pData+n, &iDummy);
85571           assert( n<pReader->nData );
85572         }else if( pReader->iType==DL_POSITIONS_OFFSETS ){
85573           n += fts3GetVarint32(pReader->pData+n, &iDummy);
85574           n += fts3GetVarint32(pReader->pData+n, &iDummy);
85575           assert( n<pReader->nData );
85576         }
85577       }
85578     }
85579     pReader->nElement = n;
85580     assert( pReader->nElement<=pReader->nData );
85581   }
85582 }
85583 static void dlrInit(DLReader *pReader, DocListType iType,
85584                     const char *pData, int nData){
85585   assert( pData!=NULL && nData!=0 );
85586   pReader->iType = iType;
85587   pReader->pData = pData;
85588   pReader->nData = nData;
85589   pReader->nElement = 0;
85590   pReader->iDocid = 0;
85591
85592   /* Load the first element's data.  There must be a first element. */
85593   dlrStep(pReader);
85594 }
85595 static void dlrDestroy(DLReader *pReader){
85596   SCRAMBLE(pReader);
85597 }
85598
85599 #ifndef NDEBUG
85600 /* Verify that the doclist can be validly decoded.  Also returns the
85601 ** last docid found because it is convenient in other assertions for
85602 ** DLWriter.
85603 */
85604 static void docListValidate(DocListType iType, const char *pData, int nData,
85605                             sqlite_int64 *pLastDocid){
85606   sqlite_int64 iPrevDocid = 0;
85607   assert( nData>0 );
85608   assert( pData!=0 );
85609   assert( pData+nData>pData );
85610   while( nData!=0 ){
85611     sqlite_int64 iDocidDelta;
85612     int n = fts3GetVarint(pData, &iDocidDelta);
85613     iPrevDocid += iDocidDelta;
85614     if( iType>DL_DOCIDS ){
85615       int iDummy;
85616       while( 1 ){
85617         n += fts3GetVarint32(pData+n, &iDummy);
85618         if( iDummy==POS_END ) break;
85619         if( iDummy==POS_COLUMN ){
85620           n += fts3GetVarint32(pData+n, &iDummy);
85621         }else if( iType>DL_POSITIONS ){
85622           n += fts3GetVarint32(pData+n, &iDummy);
85623           n += fts3GetVarint32(pData+n, &iDummy);
85624         }
85625         assert( n<=nData );
85626       }
85627     }
85628     assert( n<=nData );
85629     pData += n;
85630     nData -= n;
85631   }
85632   if( pLastDocid ) *pLastDocid = iPrevDocid;
85633 }
85634 #define ASSERT_VALID_DOCLIST(i, p, n, o) docListValidate(i, p, n, o)
85635 #else
85636 #define ASSERT_VALID_DOCLIST(i, p, n, o) assert( 1 )
85637 #endif
85638
85639 /*******************************************************************/
85640 /* DLWriter is used to write doclist data to a DataBuffer.  DLWriter
85641 ** always appends to the buffer and does not own it.
85642 **
85643 ** dlwInit - initialize to write a given type doclistto a buffer.
85644 ** dlwDestroy - clear the writer's memory.  Does not free buffer.
85645 ** dlwAppend - append raw doclist data to buffer.
85646 ** dlwCopy - copy next doclist from reader to writer.
85647 ** dlwAdd - construct doclist element and append to buffer.
85648 **    Only apply dlwAdd() to DL_DOCIDS doclists (else use PLWriter).
85649 */
85650 typedef struct DLWriter {
85651   DocListType iType;
85652   DataBuffer *b;
85653   sqlite_int64 iPrevDocid;
85654 #ifndef NDEBUG
85655   int has_iPrevDocid;
85656 #endif
85657 } DLWriter;
85658
85659 static void dlwInit(DLWriter *pWriter, DocListType iType, DataBuffer *b){
85660   pWriter->b = b;
85661   pWriter->iType = iType;
85662   pWriter->iPrevDocid = 0;
85663 #ifndef NDEBUG
85664   pWriter->has_iPrevDocid = 0;
85665 #endif
85666 }
85667 static void dlwDestroy(DLWriter *pWriter){
85668   SCRAMBLE(pWriter);
85669 }
85670 /* iFirstDocid is the first docid in the doclist in pData.  It is
85671 ** needed because pData may point within a larger doclist, in which
85672 ** case the first item would be delta-encoded.
85673 **
85674 ** iLastDocid is the final docid in the doclist in pData.  It is
85675 ** needed to create the new iPrevDocid for future delta-encoding.  The
85676 ** code could decode the passed doclist to recreate iLastDocid, but
85677 ** the only current user (docListMerge) already has decoded this
85678 ** information.
85679 */
85680 /* TODO(shess) This has become just a helper for docListMerge.
85681 ** Consider a refactor to make this cleaner.
85682 */
85683 static void dlwAppend(DLWriter *pWriter,
85684                       const char *pData, int nData,
85685                       sqlite_int64 iFirstDocid, sqlite_int64 iLastDocid){
85686   sqlite_int64 iDocid = 0;
85687   char c[VARINT_MAX];
85688   int nFirstOld, nFirstNew;     /* Old and new varint len of first docid. */
85689 #ifndef NDEBUG
85690   sqlite_int64 iLastDocidDelta;
85691 #endif
85692
85693   /* Recode the initial docid as delta from iPrevDocid. */
85694   nFirstOld = fts3GetVarint(pData, &iDocid);
85695   assert( nFirstOld<nData || (nFirstOld==nData && pWriter->iType==DL_DOCIDS) );
85696   nFirstNew = fts3PutVarint(c, iFirstDocid-pWriter->iPrevDocid);
85697
85698   /* Verify that the incoming doclist is valid AND that it ends with
85699   ** the expected docid.  This is essential because we'll trust this
85700   ** docid in future delta-encoding.
85701   */
85702   ASSERT_VALID_DOCLIST(pWriter->iType, pData, nData, &iLastDocidDelta);
85703   assert( iLastDocid==iFirstDocid-iDocid+iLastDocidDelta );
85704
85705   /* Append recoded initial docid and everything else.  Rest of docids
85706   ** should have been delta-encoded from previous initial docid.
85707   */
85708   if( nFirstOld<nData ){
85709     dataBufferAppend2(pWriter->b, c, nFirstNew,
85710                       pData+nFirstOld, nData-nFirstOld);
85711   }else{
85712     dataBufferAppend(pWriter->b, c, nFirstNew);
85713   }
85714   pWriter->iPrevDocid = iLastDocid;
85715 }
85716 static void dlwCopy(DLWriter *pWriter, DLReader *pReader){
85717   dlwAppend(pWriter, dlrDocData(pReader), dlrDocDataBytes(pReader),
85718             dlrDocid(pReader), dlrDocid(pReader));
85719 }
85720 static void dlwAdd(DLWriter *pWriter, sqlite_int64 iDocid){
85721   char c[VARINT_MAX];
85722   int n = fts3PutVarint(c, iDocid-pWriter->iPrevDocid);
85723
85724   /* Docids must ascend. */
85725   assert( !pWriter->has_iPrevDocid || iDocid>pWriter->iPrevDocid );
85726   assert( pWriter->iType==DL_DOCIDS );
85727
85728   dataBufferAppend(pWriter->b, c, n);
85729   pWriter->iPrevDocid = iDocid;
85730 #ifndef NDEBUG
85731   pWriter->has_iPrevDocid = 1;
85732 #endif
85733 }
85734
85735 /*******************************************************************/
85736 /* PLReader is used to read data from a document's position list.  As
85737 ** the caller steps through the list, data is cached so that varints
85738 ** only need to be decoded once.
85739 **
85740 ** plrInit, plrDestroy - create/destroy a reader.
85741 ** plrColumn, plrPosition, plrStartOffset, plrEndOffset - accessors
85742 ** plrAtEnd - at end of stream, only call plrDestroy once true.
85743 ** plrStep - step to the next element.
85744 */
85745 typedef struct PLReader {
85746   /* These refer to the next position's data.  nData will reach 0 when
85747   ** reading the last position, so plrStep() signals EOF by setting
85748   ** pData to NULL.
85749   */
85750   const char *pData;
85751   int nData;
85752
85753   DocListType iType;
85754   int iColumn;         /* the last column read */
85755   int iPosition;       /* the last position read */
85756   int iStartOffset;    /* the last start offset read */
85757   int iEndOffset;      /* the last end offset read */
85758 } PLReader;
85759
85760 static int plrAtEnd(PLReader *pReader){
85761   return pReader->pData==NULL;
85762 }
85763 static int plrColumn(PLReader *pReader){
85764   assert( !plrAtEnd(pReader) );
85765   return pReader->iColumn;
85766 }
85767 static int plrPosition(PLReader *pReader){
85768   assert( !plrAtEnd(pReader) );
85769   return pReader->iPosition;
85770 }
85771 static int plrStartOffset(PLReader *pReader){
85772   assert( !plrAtEnd(pReader) );
85773   return pReader->iStartOffset;
85774 }
85775 static int plrEndOffset(PLReader *pReader){
85776   assert( !plrAtEnd(pReader) );
85777   return pReader->iEndOffset;
85778 }
85779 static void plrStep(PLReader *pReader){
85780   int i, n;
85781
85782   assert( !plrAtEnd(pReader) );
85783
85784   if( pReader->nData==0 ){
85785     pReader->pData = NULL;
85786     return;
85787   }
85788
85789   n = fts3GetVarint32(pReader->pData, &i);
85790   if( i==POS_COLUMN ){
85791     n += fts3GetVarint32(pReader->pData+n, &pReader->iColumn);
85792     pReader->iPosition = 0;
85793     pReader->iStartOffset = 0;
85794     n += fts3GetVarint32(pReader->pData+n, &i);
85795   }
85796   /* Should never see adjacent column changes. */
85797   assert( i!=POS_COLUMN );
85798
85799   if( i==POS_END ){
85800     pReader->nData = 0;
85801     pReader->pData = NULL;
85802     return;
85803   }
85804
85805   pReader->iPosition += i-POS_BASE;
85806   if( pReader->iType==DL_POSITIONS_OFFSETS ){
85807     n += fts3GetVarint32(pReader->pData+n, &i);
85808     pReader->iStartOffset += i;
85809     n += fts3GetVarint32(pReader->pData+n, &i);
85810     pReader->iEndOffset = pReader->iStartOffset+i;
85811   }
85812   assert( n<=pReader->nData );
85813   pReader->pData += n;
85814   pReader->nData -= n;
85815 }
85816
85817 static void plrInit(PLReader *pReader, DLReader *pDLReader){
85818   pReader->pData = dlrPosData(pDLReader);
85819   pReader->nData = dlrPosDataLen(pDLReader);
85820   pReader->iType = pDLReader->iType;
85821   pReader->iColumn = 0;
85822   pReader->iPosition = 0;
85823   pReader->iStartOffset = 0;
85824   pReader->iEndOffset = 0;
85825   plrStep(pReader);
85826 }
85827 static void plrDestroy(PLReader *pReader){
85828   SCRAMBLE(pReader);
85829 }
85830
85831 /*******************************************************************/
85832 /* PLWriter is used in constructing a document's position list.  As a
85833 ** convenience, if iType is DL_DOCIDS, PLWriter becomes a no-op.
85834 ** PLWriter writes to the associated DLWriter's buffer.
85835 **
85836 ** plwInit - init for writing a document's poslist.
85837 ** plwDestroy - clear a writer.
85838 ** plwAdd - append position and offset information.
85839 ** plwCopy - copy next position's data from reader to writer.
85840 ** plwTerminate - add any necessary doclist terminator.
85841 **
85842 ** Calling plwAdd() after plwTerminate() may result in a corrupt
85843 ** doclist.
85844 */
85845 /* TODO(shess) Until we've written the second item, we can cache the
85846 ** first item's information.  Then we'd have three states:
85847 **
85848 ** - initialized with docid, no positions.
85849 ** - docid and one position.
85850 ** - docid and multiple positions.
85851 **
85852 ** Only the last state needs to actually write to dlw->b, which would
85853 ** be an improvement in the DLCollector case.
85854 */
85855 typedef struct PLWriter {
85856   DLWriter *dlw;
85857
85858   int iColumn;    /* the last column written */
85859   int iPos;       /* the last position written */
85860   int iOffset;    /* the last start offset written */
85861 } PLWriter;
85862
85863 /* TODO(shess) In the case where the parent is reading these values
85864 ** from a PLReader, we could optimize to a copy if that PLReader has
85865 ** the same type as pWriter.
85866 */
85867 static void plwAdd(PLWriter *pWriter, int iColumn, int iPos,
85868                    int iStartOffset, int iEndOffset){
85869   /* Worst-case space for POS_COLUMN, iColumn, iPosDelta,
85870   ** iStartOffsetDelta, and iEndOffsetDelta.
85871   */
85872   char c[5*VARINT_MAX];
85873   int n = 0;
85874
85875   /* Ban plwAdd() after plwTerminate(). */
85876   assert( pWriter->iPos!=-1 );
85877
85878   if( pWriter->dlw->iType==DL_DOCIDS ) return;
85879
85880   if( iColumn!=pWriter->iColumn ){
85881     n += fts3PutVarint(c+n, POS_COLUMN);
85882     n += fts3PutVarint(c+n, iColumn);
85883     pWriter->iColumn = iColumn;
85884     pWriter->iPos = 0;
85885     pWriter->iOffset = 0;
85886   }
85887   assert( iPos>=pWriter->iPos );
85888   n += fts3PutVarint(c+n, POS_BASE+(iPos-pWriter->iPos));
85889   pWriter->iPos = iPos;
85890   if( pWriter->dlw->iType==DL_POSITIONS_OFFSETS ){
85891     assert( iStartOffset>=pWriter->iOffset );
85892     n += fts3PutVarint(c+n, iStartOffset-pWriter->iOffset);
85893     pWriter->iOffset = iStartOffset;
85894     assert( iEndOffset>=iStartOffset );
85895     n += fts3PutVarint(c+n, iEndOffset-iStartOffset);
85896   }
85897   dataBufferAppend(pWriter->dlw->b, c, n);
85898 }
85899 static void plwCopy(PLWriter *pWriter, PLReader *pReader){
85900   plwAdd(pWriter, plrColumn(pReader), plrPosition(pReader),
85901          plrStartOffset(pReader), plrEndOffset(pReader));
85902 }
85903 static void plwInit(PLWriter *pWriter, DLWriter *dlw, sqlite_int64 iDocid){
85904   char c[VARINT_MAX];
85905   int n;
85906
85907   pWriter->dlw = dlw;
85908
85909   /* Docids must ascend. */
85910   assert( !pWriter->dlw->has_iPrevDocid || iDocid>pWriter->dlw->iPrevDocid );
85911   n = fts3PutVarint(c, iDocid-pWriter->dlw->iPrevDocid);
85912   dataBufferAppend(pWriter->dlw->b, c, n);
85913   pWriter->dlw->iPrevDocid = iDocid;
85914 #ifndef NDEBUG
85915   pWriter->dlw->has_iPrevDocid = 1;
85916 #endif
85917
85918   pWriter->iColumn = 0;
85919   pWriter->iPos = 0;
85920   pWriter->iOffset = 0;
85921 }
85922 /* TODO(shess) Should plwDestroy() also terminate the doclist?  But
85923 ** then plwDestroy() would no longer be just a destructor, it would
85924 ** also be doing work, which isn't consistent with the overall idiom.
85925 ** Another option would be for plwAdd() to always append any necessary
85926 ** terminator, so that the output is always correct.  But that would
85927 ** add incremental work to the common case with the only benefit being
85928 ** API elegance.  Punt for now.
85929 */
85930 static void plwTerminate(PLWriter *pWriter){
85931   if( pWriter->dlw->iType>DL_DOCIDS ){
85932     char c[VARINT_MAX];
85933     int n = fts3PutVarint(c, POS_END);
85934     dataBufferAppend(pWriter->dlw->b, c, n);
85935   }
85936 #ifndef NDEBUG
85937   /* Mark as terminated for assert in plwAdd(). */
85938   pWriter->iPos = -1;
85939 #endif
85940 }
85941 static void plwDestroy(PLWriter *pWriter){
85942   SCRAMBLE(pWriter);
85943 }
85944
85945 /*******************************************************************/
85946 /* DLCollector wraps PLWriter and DLWriter to provide a
85947 ** dynamically-allocated doclist area to use during tokenization.
85948 **
85949 ** dlcNew - malloc up and initialize a collector.
85950 ** dlcDelete - destroy a collector and all contained items.
85951 ** dlcAddPos - append position and offset information.
85952 ** dlcAddDoclist - add the collected doclist to the given buffer.
85953 ** dlcNext - terminate the current document and open another.
85954 */
85955 typedef struct DLCollector {
85956   DataBuffer b;
85957   DLWriter dlw;
85958   PLWriter plw;
85959 } DLCollector;
85960
85961 /* TODO(shess) This could also be done by calling plwTerminate() and
85962 ** dataBufferAppend().  I tried that, expecting nominal performance
85963 ** differences, but it seemed to pretty reliably be worth 1% to code
85964 ** it this way.  I suspect it is the incremental malloc overhead (some
85965 ** percentage of the plwTerminate() calls will cause a realloc), so
85966 ** this might be worth revisiting if the DataBuffer implementation
85967 ** changes.
85968 */
85969 static void dlcAddDoclist(DLCollector *pCollector, DataBuffer *b){
85970   if( pCollector->dlw.iType>DL_DOCIDS ){
85971     char c[VARINT_MAX];
85972     int n = fts3PutVarint(c, POS_END);
85973     dataBufferAppend2(b, pCollector->b.pData, pCollector->b.nData, c, n);
85974   }else{
85975     dataBufferAppend(b, pCollector->b.pData, pCollector->b.nData);
85976   }
85977 }
85978 static void dlcNext(DLCollector *pCollector, sqlite_int64 iDocid){
85979   plwTerminate(&pCollector->plw);
85980   plwDestroy(&pCollector->plw);
85981   plwInit(&pCollector->plw, &pCollector->dlw, iDocid);
85982 }
85983 static void dlcAddPos(DLCollector *pCollector, int iColumn, int iPos,
85984                       int iStartOffset, int iEndOffset){
85985   plwAdd(&pCollector->plw, iColumn, iPos, iStartOffset, iEndOffset);
85986 }
85987
85988 static DLCollector *dlcNew(sqlite_int64 iDocid, DocListType iType){
85989   DLCollector *pCollector = sqlite3_malloc(sizeof(DLCollector));
85990   dataBufferInit(&pCollector->b, 0);
85991   dlwInit(&pCollector->dlw, iType, &pCollector->b);
85992   plwInit(&pCollector->plw, &pCollector->dlw, iDocid);
85993   return pCollector;
85994 }
85995 static void dlcDelete(DLCollector *pCollector){
85996   plwDestroy(&pCollector->plw);
85997   dlwDestroy(&pCollector->dlw);
85998   dataBufferDestroy(&pCollector->b);
85999   SCRAMBLE(pCollector);
86000   sqlite3_free(pCollector);
86001 }
86002
86003
86004 /* Copy the doclist data of iType in pData/nData into *out, trimming
86005 ** unnecessary data as we go.  Only columns matching iColumn are
86006 ** copied, all columns copied if iColumn is -1.  Elements with no
86007 ** matching columns are dropped.  The output is an iOutType doclist.
86008 */
86009 /* NOTE(shess) This code is only valid after all doclists are merged.
86010 ** If this is run before merges, then doclist items which represent
86011 ** deletion will be trimmed, and will thus not effect a deletion
86012 ** during the merge.
86013 */
86014 static void docListTrim(DocListType iType, const char *pData, int nData,
86015                         int iColumn, DocListType iOutType, DataBuffer *out){
86016   DLReader dlReader;
86017   DLWriter dlWriter;
86018
86019   assert( iOutType<=iType );
86020
86021   dlrInit(&dlReader, iType, pData, nData);
86022   dlwInit(&dlWriter, iOutType, out);
86023
86024   while( !dlrAtEnd(&dlReader) ){
86025     PLReader plReader;
86026     PLWriter plWriter;
86027     int match = 0;
86028
86029     plrInit(&plReader, &dlReader);
86030
86031     while( !plrAtEnd(&plReader) ){
86032       if( iColumn==-1 || plrColumn(&plReader)==iColumn ){
86033         if( !match ){
86034           plwInit(&plWriter, &dlWriter, dlrDocid(&dlReader));
86035           match = 1;
86036         }
86037         plwAdd(&plWriter, plrColumn(&plReader), plrPosition(&plReader),
86038                plrStartOffset(&plReader), plrEndOffset(&plReader));
86039       }
86040       plrStep(&plReader);
86041     }
86042     if( match ){
86043       plwTerminate(&plWriter);
86044       plwDestroy(&plWriter);
86045     }
86046
86047     plrDestroy(&plReader);
86048     dlrStep(&dlReader);
86049   }
86050   dlwDestroy(&dlWriter);
86051   dlrDestroy(&dlReader);
86052 }
86053
86054 /* Used by docListMerge() to keep doclists in the ascending order by
86055 ** docid, then ascending order by age (so the newest comes first).
86056 */
86057 typedef struct OrderedDLReader {
86058   DLReader *pReader;
86059
86060   /* TODO(shess) If we assume that docListMerge pReaders is ordered by
86061   ** age (which we do), then we could use pReader comparisons to break
86062   ** ties.
86063   */
86064   int idx;
86065 } OrderedDLReader;
86066
86067 /* Order eof to end, then by docid asc, idx desc. */
86068 static int orderedDLReaderCmp(OrderedDLReader *r1, OrderedDLReader *r2){
86069   if( dlrAtEnd(r1->pReader) ){
86070     if( dlrAtEnd(r2->pReader) ) return 0;  /* Both atEnd(). */
86071     return 1;                              /* Only r1 atEnd(). */
86072   }
86073   if( dlrAtEnd(r2->pReader) ) return -1;   /* Only r2 atEnd(). */
86074
86075   if( dlrDocid(r1->pReader)<dlrDocid(r2->pReader) ) return -1;
86076   if( dlrDocid(r1->pReader)>dlrDocid(r2->pReader) ) return 1;
86077
86078   /* Descending on idx. */
86079   return r2->idx-r1->idx;
86080 }
86081
86082 /* Bubble p[0] to appropriate place in p[1..n-1].  Assumes that
86083 ** p[1..n-1] is already sorted.
86084 */
86085 /* TODO(shess) Is this frequent enough to warrant a binary search?
86086 ** Before implementing that, instrument the code to check.  In most
86087 ** current usage, I expect that p[0] will be less than p[1] a very
86088 ** high proportion of the time.
86089 */
86090 static void orderedDLReaderReorder(OrderedDLReader *p, int n){
86091   while( n>1 && orderedDLReaderCmp(p, p+1)>0 ){
86092     OrderedDLReader tmp = p[0];
86093     p[0] = p[1];
86094     p[1] = tmp;
86095     n--;
86096     p++;
86097   }
86098 }
86099
86100 /* Given an array of doclist readers, merge their doclist elements
86101 ** into out in sorted order (by docid), dropping elements from older
86102 ** readers when there is a duplicate docid.  pReaders is assumed to be
86103 ** ordered by age, oldest first.
86104 */
86105 /* TODO(shess) nReaders must be <= MERGE_COUNT.  This should probably
86106 ** be fixed.
86107 */
86108 static void docListMerge(DataBuffer *out,
86109                          DLReader *pReaders, int nReaders){
86110   OrderedDLReader readers[MERGE_COUNT];
86111   DLWriter writer;
86112   int i, n;
86113   const char *pStart = 0;
86114   int nStart = 0;
86115   sqlite_int64 iFirstDocid = 0, iLastDocid = 0;
86116
86117   assert( nReaders>0 );
86118   if( nReaders==1 ){
86119     dataBufferAppend(out, dlrDocData(pReaders), dlrAllDataBytes(pReaders));
86120     return;
86121   }
86122
86123   assert( nReaders<=MERGE_COUNT );
86124   n = 0;
86125   for(i=0; i<nReaders; i++){
86126     assert( pReaders[i].iType==pReaders[0].iType );
86127     readers[i].pReader = pReaders+i;
86128     readers[i].idx = i;
86129     n += dlrAllDataBytes(&pReaders[i]);
86130   }
86131   /* Conservatively size output to sum of inputs.  Output should end
86132   ** up strictly smaller than input.
86133   */
86134   dataBufferExpand(out, n);
86135
86136   /* Get the readers into sorted order. */
86137   while( i-->0 ){
86138     orderedDLReaderReorder(readers+i, nReaders-i);
86139   }
86140
86141   dlwInit(&writer, pReaders[0].iType, out);
86142   while( !dlrAtEnd(readers[0].pReader) ){
86143     sqlite_int64 iDocid = dlrDocid(readers[0].pReader);
86144
86145     /* If this is a continuation of the current buffer to copy, extend
86146     ** that buffer.  memcpy() seems to be more efficient if it has a
86147     ** lots of data to copy.
86148     */
86149     if( dlrDocData(readers[0].pReader)==pStart+nStart ){
86150       nStart += dlrDocDataBytes(readers[0].pReader);
86151     }else{
86152       if( pStart!=0 ){
86153         dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid);
86154       }
86155       pStart = dlrDocData(readers[0].pReader);
86156       nStart = dlrDocDataBytes(readers[0].pReader);
86157       iFirstDocid = iDocid;
86158     }
86159     iLastDocid = iDocid;
86160     dlrStep(readers[0].pReader);
86161
86162     /* Drop all of the older elements with the same docid. */
86163     for(i=1; i<nReaders &&
86164              !dlrAtEnd(readers[i].pReader) &&
86165              dlrDocid(readers[i].pReader)==iDocid; i++){
86166       dlrStep(readers[i].pReader);
86167     }
86168
86169     /* Get the readers back into order. */
86170     while( i-->0 ){
86171       orderedDLReaderReorder(readers+i, nReaders-i);
86172     }
86173   }
86174
86175   /* Copy over any remaining elements. */
86176   if( nStart>0 ) dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid);
86177   dlwDestroy(&writer);
86178 }
86179
86180 /* Helper function for posListUnion().  Compares the current position
86181 ** between left and right, returning as standard C idiom of <0 if
86182 ** left<right, >0 if left>right, and 0 if left==right.  "End" always
86183 ** compares greater.
86184 */
86185 static int posListCmp(PLReader *pLeft, PLReader *pRight){
86186   assert( pLeft->iType==pRight->iType );
86187   if( pLeft->iType==DL_DOCIDS ) return 0;
86188
86189   if( plrAtEnd(pLeft) ) return plrAtEnd(pRight) ? 0 : 1;
86190   if( plrAtEnd(pRight) ) return -1;
86191
86192   if( plrColumn(pLeft)<plrColumn(pRight) ) return -1;
86193   if( plrColumn(pLeft)>plrColumn(pRight) ) return 1;
86194
86195   if( plrPosition(pLeft)<plrPosition(pRight) ) return -1;
86196   if( plrPosition(pLeft)>plrPosition(pRight) ) return 1;
86197   if( pLeft->iType==DL_POSITIONS ) return 0;
86198
86199   if( plrStartOffset(pLeft)<plrStartOffset(pRight) ) return -1;
86200   if( plrStartOffset(pLeft)>plrStartOffset(pRight) ) return 1;
86201
86202   if( plrEndOffset(pLeft)<plrEndOffset(pRight) ) return -1;
86203   if( plrEndOffset(pLeft)>plrEndOffset(pRight) ) return 1;
86204
86205   return 0;
86206 }
86207
86208 /* Write the union of position lists in pLeft and pRight to pOut.
86209 ** "Union" in this case meaning "All unique position tuples".  Should
86210 ** work with any doclist type, though both inputs and the output
86211 ** should be the same type.
86212 */
86213 static void posListUnion(DLReader *pLeft, DLReader *pRight, DLWriter *pOut){
86214   PLReader left, right;
86215   PLWriter writer;
86216
86217   assert( dlrDocid(pLeft)==dlrDocid(pRight) );
86218   assert( pLeft->iType==pRight->iType );
86219   assert( pLeft->iType==pOut->iType );
86220
86221   plrInit(&left, pLeft);
86222   plrInit(&right, pRight);
86223   plwInit(&writer, pOut, dlrDocid(pLeft));
86224
86225   while( !plrAtEnd(&left) || !plrAtEnd(&right) ){
86226     int c = posListCmp(&left, &right);
86227     if( c<0 ){
86228       plwCopy(&writer, &left);
86229       plrStep(&left);
86230     }else if( c>0 ){
86231       plwCopy(&writer, &right);
86232       plrStep(&right);
86233     }else{
86234       plwCopy(&writer, &left);
86235       plrStep(&left);
86236       plrStep(&right);
86237     }
86238   }
86239
86240   plwTerminate(&writer);
86241   plwDestroy(&writer);
86242   plrDestroy(&left);
86243   plrDestroy(&right);
86244 }
86245
86246 /* Write the union of doclists in pLeft and pRight to pOut.  For
86247 ** docids in common between the inputs, the union of the position
86248 ** lists is written.  Inputs and outputs are always type DL_DEFAULT.
86249 */
86250 static void docListUnion(
86251   const char *pLeft, int nLeft,
86252   const char *pRight, int nRight,
86253   DataBuffer *pOut      /* Write the combined doclist here */
86254 ){
86255   DLReader left, right;
86256   DLWriter writer;
86257
86258   if( nLeft==0 ){
86259     if( nRight!=0) dataBufferAppend(pOut, pRight, nRight);
86260     return;
86261   }
86262   if( nRight==0 ){
86263     dataBufferAppend(pOut, pLeft, nLeft);
86264     return;
86265   }
86266
86267   dlrInit(&left, DL_DEFAULT, pLeft, nLeft);
86268   dlrInit(&right, DL_DEFAULT, pRight, nRight);
86269   dlwInit(&writer, DL_DEFAULT, pOut);
86270
86271   while( !dlrAtEnd(&left) || !dlrAtEnd(&right) ){
86272     if( dlrAtEnd(&right) ){
86273       dlwCopy(&writer, &left);
86274       dlrStep(&left);
86275     }else if( dlrAtEnd(&left) ){
86276       dlwCopy(&writer, &right);
86277       dlrStep(&right);
86278     }else if( dlrDocid(&left)<dlrDocid(&right) ){
86279       dlwCopy(&writer, &left);
86280       dlrStep(&left);
86281     }else if( dlrDocid(&left)>dlrDocid(&right) ){
86282       dlwCopy(&writer, &right);
86283       dlrStep(&right);
86284     }else{
86285       posListUnion(&left, &right, &writer);
86286       dlrStep(&left);
86287       dlrStep(&right);
86288     }
86289   }
86290
86291   dlrDestroy(&left);
86292   dlrDestroy(&right);
86293   dlwDestroy(&writer);
86294 }
86295
86296 /* 
86297 ** This function is used as part of the implementation of phrase and
86298 ** NEAR matching.
86299 **
86300 ** pLeft and pRight are DLReaders positioned to the same docid in
86301 ** lists of type DL_POSITION. This function writes an entry to the
86302 ** DLWriter pOut for each position in pRight that is less than
86303 ** (nNear+1) greater (but not equal to or smaller) than a position 
86304 ** in pLeft. For example, if nNear is 0, and the positions contained
86305 ** by pLeft and pRight are:
86306 **
86307 **    pLeft:  5 10 15 20
86308 **    pRight: 6  9 17 21
86309 **
86310 ** then the docid is added to pOut. If pOut is of type DL_POSITIONS,
86311 ** then a positionids "6" and "21" are also added to pOut.
86312 **
86313 ** If boolean argument isSaveLeft is true, then positionids are copied
86314 ** from pLeft instead of pRight. In the example above, the positions "5"
86315 ** and "20" would be added instead of "6" and "21".
86316 */
86317 static void posListPhraseMerge(
86318   DLReader *pLeft, 
86319   DLReader *pRight,
86320   int nNear,
86321   int isSaveLeft,
86322   DLWriter *pOut
86323 ){
86324   PLReader left, right;
86325   PLWriter writer;
86326   int match = 0;
86327
86328   assert( dlrDocid(pLeft)==dlrDocid(pRight) );
86329   assert( pOut->iType!=DL_POSITIONS_OFFSETS );
86330
86331   plrInit(&left, pLeft);
86332   plrInit(&right, pRight);
86333
86334   while( !plrAtEnd(&left) && !plrAtEnd(&right) ){
86335     if( plrColumn(&left)<plrColumn(&right) ){
86336       plrStep(&left);
86337     }else if( plrColumn(&left)>plrColumn(&right) ){
86338       plrStep(&right);
86339     }else if( plrPosition(&left)>=plrPosition(&right) ){
86340       plrStep(&right);
86341     }else{
86342       if( (plrPosition(&right)-plrPosition(&left))<=(nNear+1) ){
86343         if( !match ){
86344           plwInit(&writer, pOut, dlrDocid(pLeft));
86345           match = 1;
86346         }
86347         if( !isSaveLeft ){
86348           plwAdd(&writer, plrColumn(&right), plrPosition(&right), 0, 0);
86349         }else{
86350           plwAdd(&writer, plrColumn(&left), plrPosition(&left), 0, 0);
86351         }
86352         plrStep(&right);
86353       }else{
86354         plrStep(&left);
86355       }
86356     }
86357   }
86358
86359   if( match ){
86360     plwTerminate(&writer);
86361     plwDestroy(&writer);
86362   }
86363
86364   plrDestroy(&left);
86365   plrDestroy(&right);
86366 }
86367
86368 /*
86369 ** Compare the values pointed to by the PLReaders passed as arguments. 
86370 ** Return -1 if the value pointed to by pLeft is considered less than
86371 ** the value pointed to by pRight, +1 if it is considered greater
86372 ** than it, or 0 if it is equal. i.e.
86373 **
86374 **     (*pLeft - *pRight)
86375 **
86376 ** A PLReader that is in the EOF condition is considered greater than
86377 ** any other. If neither argument is in EOF state, the return value of
86378 ** plrColumn() is used. If the plrColumn() values are equal, the
86379 ** comparison is on the basis of plrPosition().
86380 */
86381 static int plrCompare(PLReader *pLeft, PLReader *pRight){
86382   assert(!plrAtEnd(pLeft) || !plrAtEnd(pRight));
86383
86384   if( plrAtEnd(pRight) || plrAtEnd(pLeft) ){
86385     return (plrAtEnd(pRight) ? -1 : 1);
86386   }
86387   if( plrColumn(pLeft)!=plrColumn(pRight) ){
86388     return ((plrColumn(pLeft)<plrColumn(pRight)) ? -1 : 1);
86389   }
86390   if( plrPosition(pLeft)!=plrPosition(pRight) ){
86391     return ((plrPosition(pLeft)<plrPosition(pRight)) ? -1 : 1);
86392   }
86393   return 0;
86394 }
86395
86396 /* We have two doclists with positions:  pLeft and pRight. Depending
86397 ** on the value of the nNear parameter, perform either a phrase
86398 ** intersection (if nNear==0) or a NEAR intersection (if nNear>0)
86399 ** and write the results into pOut.
86400 **
86401 ** A phrase intersection means that two documents only match
86402 ** if pLeft.iPos+1==pRight.iPos.
86403 **
86404 ** A NEAR intersection means that two documents only match if 
86405 ** (abs(pLeft.iPos-pRight.iPos)<nNear).
86406 **
86407 ** If a NEAR intersection is requested, then the nPhrase argument should
86408 ** be passed the number of tokens in the two operands to the NEAR operator
86409 ** combined. For example:
86410 **
86411 **       Query syntax               nPhrase
86412 **      ------------------------------------
86413 **       "A B C" NEAR "D E"         5
86414 **       A NEAR B                   2
86415 **
86416 ** iType controls the type of data written to pOut.  If iType is
86417 ** DL_POSITIONS, the positions are those from pRight.
86418 */
86419 static void docListPhraseMerge(
86420   const char *pLeft, int nLeft,
86421   const char *pRight, int nRight,
86422   int nNear,            /* 0 for a phrase merge, non-zero for a NEAR merge */
86423   int nPhrase,          /* Number of tokens in left+right operands to NEAR */
86424   DocListType iType,    /* Type of doclist to write to pOut */
86425   DataBuffer *pOut      /* Write the combined doclist here */
86426 ){
86427   DLReader left, right;
86428   DLWriter writer;
86429
86430   if( nLeft==0 || nRight==0 ) return;
86431
86432   assert( iType!=DL_POSITIONS_OFFSETS );
86433
86434   dlrInit(&left, DL_POSITIONS, pLeft, nLeft);
86435   dlrInit(&right, DL_POSITIONS, pRight, nRight);
86436   dlwInit(&writer, iType, pOut);
86437
86438   while( !dlrAtEnd(&left) && !dlrAtEnd(&right) ){
86439     if( dlrDocid(&left)<dlrDocid(&right) ){
86440       dlrStep(&left);
86441     }else if( dlrDocid(&right)<dlrDocid(&left) ){
86442       dlrStep(&right);
86443     }else{
86444       if( nNear==0 ){
86445         posListPhraseMerge(&left, &right, 0, 0, &writer);
86446       }else{
86447         /* This case occurs when two terms (simple terms or phrases) are
86448          * connected by a NEAR operator, span (nNear+1). i.e.
86449          *
86450          *     '"terrible company" NEAR widget'
86451          */
86452         DataBuffer one = {0, 0, 0};
86453         DataBuffer two = {0, 0, 0};
86454
86455         DLWriter dlwriter2;
86456         DLReader dr1 = {0, 0, 0, 0, 0}; 
86457         DLReader dr2 = {0, 0, 0, 0, 0};
86458
86459         dlwInit(&dlwriter2, iType, &one);
86460         posListPhraseMerge(&right, &left, nNear-3+nPhrase, 1, &dlwriter2);
86461         dlwInit(&dlwriter2, iType, &two);
86462         posListPhraseMerge(&left, &right, nNear-1, 0, &dlwriter2);
86463
86464         if( one.nData) dlrInit(&dr1, iType, one.pData, one.nData);
86465         if( two.nData) dlrInit(&dr2, iType, two.pData, two.nData);
86466
86467         if( !dlrAtEnd(&dr1) || !dlrAtEnd(&dr2) ){
86468           PLReader pr1 = {0};
86469           PLReader pr2 = {0};
86470
86471           PLWriter plwriter;
86472           plwInit(&plwriter, &writer, dlrDocid(dlrAtEnd(&dr1)?&dr2:&dr1));
86473
86474           if( one.nData ) plrInit(&pr1, &dr1);
86475           if( two.nData ) plrInit(&pr2, &dr2);
86476           while( !plrAtEnd(&pr1) || !plrAtEnd(&pr2) ){
86477             int iCompare = plrCompare(&pr1, &pr2);
86478             switch( iCompare ){
86479               case -1:
86480                 plwCopy(&plwriter, &pr1);
86481                 plrStep(&pr1);
86482                 break;
86483               case 1:
86484                 plwCopy(&plwriter, &pr2);
86485                 plrStep(&pr2);
86486                 break;
86487               case 0:
86488                 plwCopy(&plwriter, &pr1);
86489                 plrStep(&pr1);
86490                 plrStep(&pr2);
86491                 break;
86492             }
86493           }
86494           plwTerminate(&plwriter);
86495         }
86496         dataBufferDestroy(&one);
86497         dataBufferDestroy(&two);
86498       }
86499       dlrStep(&left);
86500       dlrStep(&right);
86501     }
86502   }
86503
86504   dlrDestroy(&left);
86505   dlrDestroy(&right);
86506   dlwDestroy(&writer);
86507 }
86508
86509 /* We have two DL_DOCIDS doclists:  pLeft and pRight.
86510 ** Write the intersection of these two doclists into pOut as a
86511 ** DL_DOCIDS doclist.
86512 */
86513 static void docListAndMerge(
86514   const char *pLeft, int nLeft,
86515   const char *pRight, int nRight,
86516   DataBuffer *pOut      /* Write the combined doclist here */
86517 ){
86518   DLReader left, right;
86519   DLWriter writer;
86520
86521   if( nLeft==0 || nRight==0 ) return;
86522
86523   dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
86524   dlrInit(&right, DL_DOCIDS, pRight, nRight);
86525   dlwInit(&writer, DL_DOCIDS, pOut);
86526
86527   while( !dlrAtEnd(&left) && !dlrAtEnd(&right) ){
86528     if( dlrDocid(&left)<dlrDocid(&right) ){
86529       dlrStep(&left);
86530     }else if( dlrDocid(&right)<dlrDocid(&left) ){
86531       dlrStep(&right);
86532     }else{
86533       dlwAdd(&writer, dlrDocid(&left));
86534       dlrStep(&left);
86535       dlrStep(&right);
86536     }
86537   }
86538
86539   dlrDestroy(&left);
86540   dlrDestroy(&right);
86541   dlwDestroy(&writer);
86542 }
86543
86544 /* We have two DL_DOCIDS doclists:  pLeft and pRight.
86545 ** Write the union of these two doclists into pOut as a
86546 ** DL_DOCIDS doclist.
86547 */
86548 static void docListOrMerge(
86549   const char *pLeft, int nLeft,
86550   const char *pRight, int nRight,
86551   DataBuffer *pOut      /* Write the combined doclist here */
86552 ){
86553   DLReader left, right;
86554   DLWriter writer;
86555
86556   if( nLeft==0 ){
86557     if( nRight!=0 ) dataBufferAppend(pOut, pRight, nRight);
86558     return;
86559   }
86560   if( nRight==0 ){
86561     dataBufferAppend(pOut, pLeft, nLeft);
86562     return;
86563   }
86564
86565   dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
86566   dlrInit(&right, DL_DOCIDS, pRight, nRight);
86567   dlwInit(&writer, DL_DOCIDS, pOut);
86568
86569   while( !dlrAtEnd(&left) || !dlrAtEnd(&right) ){
86570     if( dlrAtEnd(&right) ){
86571       dlwAdd(&writer, dlrDocid(&left));
86572       dlrStep(&left);
86573     }else if( dlrAtEnd(&left) ){
86574       dlwAdd(&writer, dlrDocid(&right));
86575       dlrStep(&right);
86576     }else if( dlrDocid(&left)<dlrDocid(&right) ){
86577       dlwAdd(&writer, dlrDocid(&left));
86578       dlrStep(&left);
86579     }else if( dlrDocid(&right)<dlrDocid(&left) ){
86580       dlwAdd(&writer, dlrDocid(&right));
86581       dlrStep(&right);
86582     }else{
86583       dlwAdd(&writer, dlrDocid(&left));
86584       dlrStep(&left);
86585       dlrStep(&right);
86586     }
86587   }
86588
86589   dlrDestroy(&left);
86590   dlrDestroy(&right);
86591   dlwDestroy(&writer);
86592 }
86593
86594 /* We have two DL_DOCIDS doclists:  pLeft and pRight.
86595 ** Write into pOut as DL_DOCIDS doclist containing all documents that
86596 ** occur in pLeft but not in pRight.
86597 */
86598 static void docListExceptMerge(
86599   const char *pLeft, int nLeft,
86600   const char *pRight, int nRight,
86601   DataBuffer *pOut      /* Write the combined doclist here */
86602 ){
86603   DLReader left, right;
86604   DLWriter writer;
86605
86606   if( nLeft==0 ) return;
86607   if( nRight==0 ){
86608     dataBufferAppend(pOut, pLeft, nLeft);
86609     return;
86610   }
86611
86612   dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
86613   dlrInit(&right, DL_DOCIDS, pRight, nRight);
86614   dlwInit(&writer, DL_DOCIDS, pOut);
86615
86616   while( !dlrAtEnd(&left) ){
86617     while( !dlrAtEnd(&right) && dlrDocid(&right)<dlrDocid(&left) ){
86618       dlrStep(&right);
86619     }
86620     if( dlrAtEnd(&right) || dlrDocid(&left)<dlrDocid(&right) ){
86621       dlwAdd(&writer, dlrDocid(&left));
86622     }
86623     dlrStep(&left);
86624   }
86625
86626   dlrDestroy(&left);
86627   dlrDestroy(&right);
86628   dlwDestroy(&writer);
86629 }
86630
86631 static char *string_dup_n(const char *s, int n){
86632   char *str = sqlite3_malloc(n + 1);
86633   memcpy(str, s, n);
86634   str[n] = '\0';
86635   return str;
86636 }
86637
86638 /* Duplicate a string; the caller must free() the returned string.
86639  * (We don't use strdup() since it is not part of the standard C library and
86640  * may not be available everywhere.) */
86641 static char *string_dup(const char *s){
86642   return string_dup_n(s, strlen(s));
86643 }
86644
86645 /* Format a string, replacing each occurrence of the % character with
86646  * zDb.zName.  This may be more convenient than sqlite_mprintf()
86647  * when one string is used repeatedly in a format string.
86648  * The caller must free() the returned string. */
86649 static char *string_format(const char *zFormat,
86650                            const char *zDb, const char *zName){
86651   const char *p;
86652   size_t len = 0;
86653   size_t nDb = strlen(zDb);
86654   size_t nName = strlen(zName);
86655   size_t nFullTableName = nDb+1+nName;
86656   char *result;
86657   char *r;
86658
86659   /* first compute length needed */
86660   for(p = zFormat ; *p ; ++p){
86661     len += (*p=='%' ? nFullTableName : 1);
86662   }
86663   len += 1;  /* for null terminator */
86664
86665   r = result = sqlite3_malloc(len);
86666   for(p = zFormat; *p; ++p){
86667     if( *p=='%' ){
86668       memcpy(r, zDb, nDb);
86669       r += nDb;
86670       *r++ = '.';
86671       memcpy(r, zName, nName);
86672       r += nName;
86673     } else {
86674       *r++ = *p;
86675     }
86676   }
86677   *r++ = '\0';
86678   assert( r == result + len );
86679   return result;
86680 }
86681
86682 static int sql_exec(sqlite3 *db, const char *zDb, const char *zName,
86683                     const char *zFormat){
86684   char *zCommand = string_format(zFormat, zDb, zName);
86685   int rc;
86686   FTSTRACE(("FTS3 sql: %s\n", zCommand));
86687   rc = sqlite3_exec(db, zCommand, NULL, 0, NULL);
86688   sqlite3_free(zCommand);
86689   return rc;
86690 }
86691
86692 static int sql_prepare(sqlite3 *db, const char *zDb, const char *zName,
86693                        sqlite3_stmt **ppStmt, const char *zFormat){
86694   char *zCommand = string_format(zFormat, zDb, zName);
86695   int rc;
86696   FTSTRACE(("FTS3 prepare: %s\n", zCommand));
86697   rc = sqlite3_prepare_v2(db, zCommand, -1, ppStmt, NULL);
86698   sqlite3_free(zCommand);
86699   return rc;
86700 }
86701
86702 /* end utility functions */
86703
86704 /* Forward reference */
86705 typedef struct fulltext_vtab fulltext_vtab;
86706
86707 /* A single term in a query is represented by an instances of
86708 ** the following structure. Each word which may match against
86709 ** document content is a term. Operators, like NEAR or OR, are
86710 ** not terms. Query terms are organized as a flat list stored
86711 ** in the Query.pTerms array.
86712 **
86713 ** If the QueryTerm.nPhrase variable is non-zero, then the QueryTerm
86714 ** is the first in a contiguous string of terms that are either part
86715 ** of the same phrase, or connected by the NEAR operator.
86716 **
86717 ** If the QueryTerm.nNear variable is non-zero, then the token is followed 
86718 ** by a NEAR operator with span set to (nNear-1). For example, the 
86719 ** following query:
86720 **
86721 ** The QueryTerm.iPhrase variable stores the index of the token within
86722 ** its phrase, indexed starting at 1, or 1 if the token is not part 
86723 ** of any phrase.
86724 **
86725 ** For example, the data structure used to represent the following query:
86726 **
86727 **     ... MATCH 'sqlite NEAR/5 google NEAR/2 "search engine"'
86728 **
86729 ** is:
86730 **
86731 **     {nPhrase=4, iPhrase=1, nNear=6, pTerm="sqlite"},
86732 **     {nPhrase=0, iPhrase=1, nNear=3, pTerm="google"},
86733 **     {nPhrase=0, iPhrase=1, nNear=0, pTerm="search"},
86734 **     {nPhrase=0, iPhrase=2, nNear=0, pTerm="engine"},
86735 **
86736 ** compiling the FTS3 syntax to Query structures is done by the parseQuery()
86737 ** function.
86738 */
86739 typedef struct QueryTerm {
86740   short int nPhrase; /* How many following terms are part of the same phrase */
86741   short int iPhrase; /* This is the i-th term of a phrase. */
86742   short int iColumn; /* Column of the index that must match this term */
86743   short int nNear;   /* term followed by a NEAR operator with span=(nNear-1) */
86744   signed char isOr;  /* this term is preceded by "OR" */
86745   signed char isNot; /* this term is preceded by "-" */
86746   signed char isPrefix; /* this term is followed by "*" */
86747   char *pTerm;       /* text of the term.  '\000' terminated.  malloced */
86748   int nTerm;         /* Number of bytes in pTerm[] */
86749 } QueryTerm;
86750
86751
86752 /* A query string is parsed into a Query structure.
86753  *
86754  * We could, in theory, allow query strings to be complicated
86755  * nested expressions with precedence determined by parentheses.
86756  * But none of the major search engines do this.  (Perhaps the
86757  * feeling is that an parenthesized expression is two complex of
86758  * an idea for the average user to grasp.)  Taking our lead from
86759  * the major search engines, we will allow queries to be a list
86760  * of terms (with an implied AND operator) or phrases in double-quotes,
86761  * with a single optional "-" before each non-phrase term to designate
86762  * negation and an optional OR connector.
86763  *
86764  * OR binds more tightly than the implied AND, which is what the
86765  * major search engines seem to do.  So, for example:
86766  * 
86767  *    [one two OR three]     ==>    one AND (two OR three)
86768  *    [one OR two three]     ==>    (one OR two) AND three
86769  *
86770  * A "-" before a term matches all entries that lack that term.
86771  * The "-" must occur immediately before the term with in intervening
86772  * space.  This is how the search engines do it.
86773  *
86774  * A NOT term cannot be the right-hand operand of an OR.  If this
86775  * occurs in the query string, the NOT is ignored:
86776  *
86777  *    [one OR -two]          ==>    one OR two
86778  *
86779  */
86780 typedef struct Query {
86781   fulltext_vtab *pFts;  /* The full text index */
86782   int nTerms;           /* Number of terms in the query */
86783   QueryTerm *pTerms;    /* Array of terms.  Space obtained from malloc() */
86784   int nextIsOr;         /* Set the isOr flag on the next inserted term */
86785   int nextIsNear;       /* Set the isOr flag on the next inserted term */
86786   int nextColumn;       /* Next word parsed must be in this column */
86787   int dfltColumn;       /* The default column */
86788 } Query;
86789
86790
86791 /*
86792 ** An instance of the following structure keeps track of generated
86793 ** matching-word offset information and snippets.
86794 */
86795 typedef struct Snippet {
86796   int nMatch;     /* Total number of matches */
86797   int nAlloc;     /* Space allocated for aMatch[] */
86798   struct snippetMatch { /* One entry for each matching term */
86799     char snStatus;       /* Status flag for use while constructing snippets */
86800     short int iCol;      /* The column that contains the match */
86801     short int iTerm;     /* The index in Query.pTerms[] of the matching term */
86802     int iToken;          /* The index of the matching document token */
86803     short int nByte;     /* Number of bytes in the term */
86804     int iStart;          /* The offset to the first character of the term */
86805   } *aMatch;      /* Points to space obtained from malloc */
86806   char *zOffset;  /* Text rendering of aMatch[] */
86807   int nOffset;    /* strlen(zOffset) */
86808   char *zSnippet; /* Snippet text */
86809   int nSnippet;   /* strlen(zSnippet) */
86810 } Snippet;
86811
86812
86813 typedef enum QueryType {
86814   QUERY_GENERIC,   /* table scan */
86815   QUERY_DOCID,     /* lookup by docid */
86816   QUERY_FULLTEXT   /* QUERY_FULLTEXT + [i] is a full-text search for column i*/
86817 } QueryType;
86818
86819 typedef enum fulltext_statement {
86820   CONTENT_INSERT_STMT,
86821   CONTENT_SELECT_STMT,
86822   CONTENT_UPDATE_STMT,
86823   CONTENT_DELETE_STMT,
86824   CONTENT_EXISTS_STMT,
86825
86826   BLOCK_INSERT_STMT,
86827   BLOCK_SELECT_STMT,
86828   BLOCK_DELETE_STMT,
86829   BLOCK_DELETE_ALL_STMT,
86830
86831   SEGDIR_MAX_INDEX_STMT,
86832   SEGDIR_SET_STMT,
86833   SEGDIR_SELECT_LEVEL_STMT,
86834   SEGDIR_SPAN_STMT,
86835   SEGDIR_DELETE_STMT,
86836   SEGDIR_SELECT_SEGMENT_STMT,
86837   SEGDIR_SELECT_ALL_STMT,
86838   SEGDIR_DELETE_ALL_STMT,
86839   SEGDIR_COUNT_STMT,
86840
86841   MAX_STMT                     /* Always at end! */
86842 } fulltext_statement;
86843
86844 /* These must exactly match the enum above. */
86845 /* TODO(shess): Is there some risk that a statement will be used in two
86846 ** cursors at once, e.g.  if a query joins a virtual table to itself?
86847 ** If so perhaps we should move some of these to the cursor object.
86848 */
86849 static const char *const fulltext_zStatement[MAX_STMT] = {
86850   /* CONTENT_INSERT */ NULL,  /* generated in contentInsertStatement() */
86851   /* CONTENT_SELECT */ NULL,  /* generated in contentSelectStatement() */
86852   /* CONTENT_UPDATE */ NULL,  /* generated in contentUpdateStatement() */
86853   /* CONTENT_DELETE */ "delete from %_content where docid = ?",
86854   /* CONTENT_EXISTS */ "select docid from %_content limit 1",
86855
86856   /* BLOCK_INSERT */
86857   "insert into %_segments (blockid, block) values (null, ?)",
86858   /* BLOCK_SELECT */ "select block from %_segments where blockid = ?",
86859   /* BLOCK_DELETE */ "delete from %_segments where blockid between ? and ?",
86860   /* BLOCK_DELETE_ALL */ "delete from %_segments",
86861
86862   /* SEGDIR_MAX_INDEX */ "select max(idx) from %_segdir where level = ?",
86863   /* SEGDIR_SET */ "insert into %_segdir values (?, ?, ?, ?, ?, ?)",
86864   /* SEGDIR_SELECT_LEVEL */
86865   "select start_block, leaves_end_block, root from %_segdir "
86866   " where level = ? order by idx",
86867   /* SEGDIR_SPAN */
86868   "select min(start_block), max(end_block) from %_segdir "
86869   " where level = ? and start_block <> 0",
86870   /* SEGDIR_DELETE */ "delete from %_segdir where level = ?",
86871
86872   /* NOTE(shess): The first three results of the following two
86873   ** statements must match.
86874   */
86875   /* SEGDIR_SELECT_SEGMENT */
86876   "select start_block, leaves_end_block, root from %_segdir "
86877   " where level = ? and idx = ?",
86878   /* SEGDIR_SELECT_ALL */
86879   "select start_block, leaves_end_block, root from %_segdir "
86880   " order by level desc, idx asc",
86881   /* SEGDIR_DELETE_ALL */ "delete from %_segdir",
86882   /* SEGDIR_COUNT */ "select count(*), ifnull(max(level),0) from %_segdir",
86883 };
86884
86885 /*
86886 ** A connection to a fulltext index is an instance of the following
86887 ** structure.  The xCreate and xConnect methods create an instance
86888 ** of this structure and xDestroy and xDisconnect free that instance.
86889 ** All other methods receive a pointer to the structure as one of their
86890 ** arguments.
86891 */
86892 struct fulltext_vtab {
86893   sqlite3_vtab base;               /* Base class used by SQLite core */
86894   sqlite3 *db;                     /* The database connection */
86895   const char *zDb;                 /* logical database name */
86896   const char *zName;               /* virtual table name */
86897   int nColumn;                     /* number of columns in virtual table */
86898   char **azColumn;                 /* column names.  malloced */
86899   char **azContentColumn;          /* column names in content table; malloced */
86900   sqlite3_tokenizer *pTokenizer;   /* tokenizer for inserts and queries */
86901
86902   /* Precompiled statements which we keep as long as the table is
86903   ** open.
86904   */
86905   sqlite3_stmt *pFulltextStatements[MAX_STMT];
86906
86907   /* Precompiled statements used for segment merges.  We run a
86908   ** separate select across the leaf level of each tree being merged.
86909   */
86910   sqlite3_stmt *pLeafSelectStmts[MERGE_COUNT];
86911   /* The statement used to prepare pLeafSelectStmts. */
86912 #define LEAF_SELECT \
86913   "select block from %_segments where blockid between ? and ? order by blockid"
86914
86915   /* These buffer pending index updates during transactions.
86916   ** nPendingData estimates the memory size of the pending data.  It
86917   ** doesn't include the hash-bucket overhead, nor any malloc
86918   ** overhead.  When nPendingData exceeds kPendingThreshold, the
86919   ** buffer is flushed even before the transaction closes.
86920   ** pendingTerms stores the data, and is only valid when nPendingData
86921   ** is >=0 (nPendingData<0 means pendingTerms has not been
86922   ** initialized).  iPrevDocid is the last docid written, used to make
86923   ** certain we're inserting in sorted order.
86924   */
86925   int nPendingData;
86926 #define kPendingThreshold (1*1024*1024)
86927   sqlite_int64 iPrevDocid;
86928   fts3Hash pendingTerms;
86929 };
86930
86931 /*
86932 ** When the core wants to do a query, it create a cursor using a
86933 ** call to xOpen.  This structure is an instance of a cursor.  It
86934 ** is destroyed by xClose.
86935 */
86936 typedef struct fulltext_cursor {
86937   sqlite3_vtab_cursor base;        /* Base class used by SQLite core */
86938   QueryType iCursorType;           /* Copy of sqlite3_index_info.idxNum */
86939   sqlite3_stmt *pStmt;             /* Prepared statement in use by the cursor */
86940   int eof;                         /* True if at End Of Results */
86941   Query q;                         /* Parsed query string */
86942   Snippet snippet;                 /* Cached snippet for the current row */
86943   int iColumn;                     /* Column being searched */
86944   DataBuffer result;               /* Doclist results from fulltextQuery */
86945   DLReader reader;                 /* Result reader if result not empty */
86946 } fulltext_cursor;
86947
86948 static struct fulltext_vtab *cursor_vtab(fulltext_cursor *c){
86949   return (fulltext_vtab *) c->base.pVtab;
86950 }
86951
86952 static const sqlite3_module fts3Module;   /* forward declaration */
86953
86954 /* Return a dynamically generated statement of the form
86955  *   insert into %_content (docid, ...) values (?, ...)
86956  */
86957 static const char *contentInsertStatement(fulltext_vtab *v){
86958   StringBuffer sb;
86959   int i;
86960
86961   initStringBuffer(&sb);
86962   append(&sb, "insert into %_content (docid, ");
86963   appendList(&sb, v->nColumn, v->azContentColumn);
86964   append(&sb, ") values (?");
86965   for(i=0; i<v->nColumn; ++i)
86966     append(&sb, ", ?");
86967   append(&sb, ")");
86968   return stringBufferData(&sb);
86969 }
86970
86971 /* Return a dynamically generated statement of the form
86972  *   select <content columns> from %_content where docid = ?
86973  */
86974 static const char *contentSelectStatement(fulltext_vtab *v){
86975   StringBuffer sb;
86976   initStringBuffer(&sb);
86977   append(&sb, "SELECT ");
86978   appendList(&sb, v->nColumn, v->azContentColumn);
86979   append(&sb, " FROM %_content WHERE docid = ?");
86980   return stringBufferData(&sb);
86981 }
86982
86983 /* Return a dynamically generated statement of the form
86984  *   update %_content set [col_0] = ?, [col_1] = ?, ...
86985  *                    where docid = ?
86986  */
86987 static const char *contentUpdateStatement(fulltext_vtab *v){
86988   StringBuffer sb;
86989   int i;
86990
86991   initStringBuffer(&sb);
86992   append(&sb, "update %_content set ");
86993   for(i=0; i<v->nColumn; ++i) {
86994     if( i>0 ){
86995       append(&sb, ", ");
86996     }
86997     append(&sb, v->azContentColumn[i]);
86998     append(&sb, " = ?");
86999   }
87000   append(&sb, " where docid = ?");
87001   return stringBufferData(&sb);
87002 }
87003
87004 /* Puts a freshly-prepared statement determined by iStmt in *ppStmt.
87005 ** If the indicated statement has never been prepared, it is prepared
87006 ** and cached, otherwise the cached version is reset.
87007 */
87008 static int sql_get_statement(fulltext_vtab *v, fulltext_statement iStmt,
87009                              sqlite3_stmt **ppStmt){
87010   assert( iStmt<MAX_STMT );
87011   if( v->pFulltextStatements[iStmt]==NULL ){
87012     const char *zStmt;
87013     int rc;
87014     switch( iStmt ){
87015       case CONTENT_INSERT_STMT:
87016         zStmt = contentInsertStatement(v); break;
87017       case CONTENT_SELECT_STMT:
87018         zStmt = contentSelectStatement(v); break;
87019       case CONTENT_UPDATE_STMT:
87020         zStmt = contentUpdateStatement(v); break;
87021       default:
87022         zStmt = fulltext_zStatement[iStmt];
87023     }
87024     rc = sql_prepare(v->db, v->zDb, v->zName, &v->pFulltextStatements[iStmt],
87025                          zStmt);
87026     if( zStmt != fulltext_zStatement[iStmt]) sqlite3_free((void *) zStmt);
87027     if( rc!=SQLITE_OK ) return rc;
87028   } else {
87029     int rc = sqlite3_reset(v->pFulltextStatements[iStmt]);
87030     if( rc!=SQLITE_OK ) return rc;
87031   }
87032
87033   *ppStmt = v->pFulltextStatements[iStmt];
87034   return SQLITE_OK;
87035 }
87036
87037 /* Like sqlite3_step(), but convert SQLITE_DONE to SQLITE_OK and
87038 ** SQLITE_ROW to SQLITE_ERROR.  Useful for statements like UPDATE,
87039 ** where we expect no results.
87040 */
87041 static int sql_single_step(sqlite3_stmt *s){
87042   int rc = sqlite3_step(s);
87043   return (rc==SQLITE_DONE) ? SQLITE_OK : rc;
87044 }
87045
87046 /* Like sql_get_statement(), but for special replicated LEAF_SELECT
87047 ** statements.  idx -1 is a special case for an uncached version of
87048 ** the statement (used in the optimize implementation).
87049 */
87050 /* TODO(shess) Write version for generic statements and then share
87051 ** that between the cached-statement functions.
87052 */
87053 static int sql_get_leaf_statement(fulltext_vtab *v, int idx,
87054                                   sqlite3_stmt **ppStmt){
87055   assert( idx>=-1 && idx<MERGE_COUNT );
87056   if( idx==-1 ){
87057     return sql_prepare(v->db, v->zDb, v->zName, ppStmt, LEAF_SELECT);
87058   }else if( v->pLeafSelectStmts[idx]==NULL ){
87059     int rc = sql_prepare(v->db, v->zDb, v->zName, &v->pLeafSelectStmts[idx],
87060                          LEAF_SELECT);
87061     if( rc!=SQLITE_OK ) return rc;
87062   }else{
87063     int rc = sqlite3_reset(v->pLeafSelectStmts[idx]);
87064     if( rc!=SQLITE_OK ) return rc;
87065   }
87066
87067   *ppStmt = v->pLeafSelectStmts[idx];
87068   return SQLITE_OK;
87069 }
87070
87071 /* insert into %_content (docid, ...) values ([docid], [pValues])
87072 ** If the docid contains SQL NULL, then a unique docid will be
87073 ** generated.
87074 */
87075 static int content_insert(fulltext_vtab *v, sqlite3_value *docid,
87076                           sqlite3_value **pValues){
87077   sqlite3_stmt *s;
87078   int i;
87079   int rc = sql_get_statement(v, CONTENT_INSERT_STMT, &s);
87080   if( rc!=SQLITE_OK ) return rc;
87081
87082   rc = sqlite3_bind_value(s, 1, docid);
87083   if( rc!=SQLITE_OK ) return rc;
87084
87085   for(i=0; i<v->nColumn; ++i){
87086     rc = sqlite3_bind_value(s, 2+i, pValues[i]);
87087     if( rc!=SQLITE_OK ) return rc;
87088   }
87089
87090   return sql_single_step(s);
87091 }
87092
87093 /* update %_content set col0 = pValues[0], col1 = pValues[1], ...
87094  *                  where docid = [iDocid] */
87095 static int content_update(fulltext_vtab *v, sqlite3_value **pValues,
87096                           sqlite_int64 iDocid){
87097   sqlite3_stmt *s;
87098   int i;
87099   int rc = sql_get_statement(v, CONTENT_UPDATE_STMT, &s);
87100   if( rc!=SQLITE_OK ) return rc;
87101
87102   for(i=0; i<v->nColumn; ++i){
87103     rc = sqlite3_bind_value(s, 1+i, pValues[i]);
87104     if( rc!=SQLITE_OK ) return rc;
87105   }
87106
87107   rc = sqlite3_bind_int64(s, 1+v->nColumn, iDocid);
87108   if( rc!=SQLITE_OK ) return rc;
87109
87110   return sql_single_step(s);
87111 }
87112
87113 static void freeStringArray(int nString, const char **pString){
87114   int i;
87115
87116   for (i=0 ; i < nString ; ++i) {
87117     if( pString[i]!=NULL ) sqlite3_free((void *) pString[i]);
87118   }
87119   sqlite3_free((void *) pString);
87120 }
87121
87122 /* select * from %_content where docid = [iDocid]
87123  * The caller must delete the returned array and all strings in it.
87124  * null fields will be NULL in the returned array.
87125  *
87126  * TODO: Perhaps we should return pointer/length strings here for consistency
87127  * with other code which uses pointer/length. */
87128 static int content_select(fulltext_vtab *v, sqlite_int64 iDocid,
87129                           const char ***pValues){
87130   sqlite3_stmt *s;
87131   const char **values;
87132   int i;
87133   int rc;
87134
87135   *pValues = NULL;
87136
87137   rc = sql_get_statement(v, CONTENT_SELECT_STMT, &s);
87138   if( rc!=SQLITE_OK ) return rc;
87139
87140   rc = sqlite3_bind_int64(s, 1, iDocid);
87141   if( rc!=SQLITE_OK ) return rc;
87142
87143   rc = sqlite3_step(s);
87144   if( rc!=SQLITE_ROW ) return rc;
87145
87146   values = (const char **) sqlite3_malloc(v->nColumn * sizeof(const char *));
87147   for(i=0; i<v->nColumn; ++i){
87148     if( sqlite3_column_type(s, i)==SQLITE_NULL ){
87149       values[i] = NULL;
87150     }else{
87151       values[i] = string_dup((char*)sqlite3_column_text(s, i));
87152     }
87153   }
87154
87155   /* We expect only one row.  We must execute another sqlite3_step()
87156    * to complete the iteration; otherwise the table will remain locked. */
87157   rc = sqlite3_step(s);
87158   if( rc==SQLITE_DONE ){
87159     *pValues = values;
87160     return SQLITE_OK;
87161   }
87162
87163   freeStringArray(v->nColumn, values);
87164   return rc;
87165 }
87166
87167 /* delete from %_content where docid = [iDocid ] */
87168 static int content_delete(fulltext_vtab *v, sqlite_int64 iDocid){
87169   sqlite3_stmt *s;
87170   int rc = sql_get_statement(v, CONTENT_DELETE_STMT, &s);
87171   if( rc!=SQLITE_OK ) return rc;
87172
87173   rc = sqlite3_bind_int64(s, 1, iDocid);
87174   if( rc!=SQLITE_OK ) return rc;
87175
87176   return sql_single_step(s);
87177 }
87178
87179 /* Returns SQLITE_ROW if any rows exist in %_content, SQLITE_DONE if
87180 ** no rows exist, and any error in case of failure.
87181 */
87182 static int content_exists(fulltext_vtab *v){
87183   sqlite3_stmt *s;
87184   int rc = sql_get_statement(v, CONTENT_EXISTS_STMT, &s);
87185   if( rc!=SQLITE_OK ) return rc;
87186
87187   rc = sqlite3_step(s);
87188   if( rc!=SQLITE_ROW ) return rc;
87189
87190   /* We expect only one row.  We must execute another sqlite3_step()
87191    * to complete the iteration; otherwise the table will remain locked. */
87192   rc = sqlite3_step(s);
87193   if( rc==SQLITE_DONE ) return SQLITE_ROW;
87194   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
87195   return rc;
87196 }
87197
87198 /* insert into %_segments values ([pData])
87199 **   returns assigned blockid in *piBlockid
87200 */
87201 static int block_insert(fulltext_vtab *v, const char *pData, int nData,
87202                         sqlite_int64 *piBlockid){
87203   sqlite3_stmt *s;
87204   int rc = sql_get_statement(v, BLOCK_INSERT_STMT, &s);
87205   if( rc!=SQLITE_OK ) return rc;
87206
87207   rc = sqlite3_bind_blob(s, 1, pData, nData, SQLITE_STATIC);
87208   if( rc!=SQLITE_OK ) return rc;
87209
87210   rc = sqlite3_step(s);
87211   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
87212   if( rc!=SQLITE_DONE ) return rc;
87213
87214   /* blockid column is an alias for rowid. */
87215   *piBlockid = sqlite3_last_insert_rowid(v->db);
87216   return SQLITE_OK;
87217 }
87218
87219 /* delete from %_segments
87220 **   where blockid between [iStartBlockid] and [iEndBlockid]
87221 **
87222 ** Deletes the range of blocks, inclusive, used to delete the blocks
87223 ** which form a segment.
87224 */
87225 static int block_delete(fulltext_vtab *v,
87226                         sqlite_int64 iStartBlockid, sqlite_int64 iEndBlockid){
87227   sqlite3_stmt *s;
87228   int rc = sql_get_statement(v, BLOCK_DELETE_STMT, &s);
87229   if( rc!=SQLITE_OK ) return rc;
87230
87231   rc = sqlite3_bind_int64(s, 1, iStartBlockid);
87232   if( rc!=SQLITE_OK ) return rc;
87233
87234   rc = sqlite3_bind_int64(s, 2, iEndBlockid);
87235   if( rc!=SQLITE_OK ) return rc;
87236
87237   return sql_single_step(s);
87238 }
87239
87240 /* Returns SQLITE_ROW with *pidx set to the maximum segment idx found
87241 ** at iLevel.  Returns SQLITE_DONE if there are no segments at
87242 ** iLevel.  Otherwise returns an error.
87243 */
87244 static int segdir_max_index(fulltext_vtab *v, int iLevel, int *pidx){
87245   sqlite3_stmt *s;
87246   int rc = sql_get_statement(v, SEGDIR_MAX_INDEX_STMT, &s);
87247   if( rc!=SQLITE_OK ) return rc;
87248
87249   rc = sqlite3_bind_int(s, 1, iLevel);
87250   if( rc!=SQLITE_OK ) return rc;
87251
87252   rc = sqlite3_step(s);
87253   /* Should always get at least one row due to how max() works. */
87254   if( rc==SQLITE_DONE ) return SQLITE_DONE;
87255   if( rc!=SQLITE_ROW ) return rc;
87256
87257   /* NULL means that there were no inputs to max(). */
87258   if( SQLITE_NULL==sqlite3_column_type(s, 0) ){
87259     rc = sqlite3_step(s);
87260     if( rc==SQLITE_ROW ) return SQLITE_ERROR;
87261     return rc;
87262   }
87263
87264   *pidx = sqlite3_column_int(s, 0);
87265
87266   /* We expect only one row.  We must execute another sqlite3_step()
87267    * to complete the iteration; otherwise the table will remain locked. */
87268   rc = sqlite3_step(s);
87269   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
87270   if( rc!=SQLITE_DONE ) return rc;
87271   return SQLITE_ROW;
87272 }
87273
87274 /* insert into %_segdir values (
87275 **   [iLevel], [idx],
87276 **   [iStartBlockid], [iLeavesEndBlockid], [iEndBlockid],
87277 **   [pRootData]
87278 ** )
87279 */
87280 static int segdir_set(fulltext_vtab *v, int iLevel, int idx,
87281                       sqlite_int64 iStartBlockid,
87282                       sqlite_int64 iLeavesEndBlockid,
87283                       sqlite_int64 iEndBlockid,
87284                       const char *pRootData, int nRootData){
87285   sqlite3_stmt *s;
87286   int rc = sql_get_statement(v, SEGDIR_SET_STMT, &s);
87287   if( rc!=SQLITE_OK ) return rc;
87288
87289   rc = sqlite3_bind_int(s, 1, iLevel);
87290   if( rc!=SQLITE_OK ) return rc;
87291
87292   rc = sqlite3_bind_int(s, 2, idx);
87293   if( rc!=SQLITE_OK ) return rc;
87294
87295   rc = sqlite3_bind_int64(s, 3, iStartBlockid);
87296   if( rc!=SQLITE_OK ) return rc;
87297
87298   rc = sqlite3_bind_int64(s, 4, iLeavesEndBlockid);
87299   if( rc!=SQLITE_OK ) return rc;
87300
87301   rc = sqlite3_bind_int64(s, 5, iEndBlockid);
87302   if( rc!=SQLITE_OK ) return rc;
87303
87304   rc = sqlite3_bind_blob(s, 6, pRootData, nRootData, SQLITE_STATIC);
87305   if( rc!=SQLITE_OK ) return rc;
87306
87307   return sql_single_step(s);
87308 }
87309
87310 /* Queries %_segdir for the block span of the segments in level
87311 ** iLevel.  Returns SQLITE_DONE if there are no blocks for iLevel,
87312 ** SQLITE_ROW if there are blocks, else an error.
87313 */
87314 static int segdir_span(fulltext_vtab *v, int iLevel,
87315                        sqlite_int64 *piStartBlockid,
87316                        sqlite_int64 *piEndBlockid){
87317   sqlite3_stmt *s;
87318   int rc = sql_get_statement(v, SEGDIR_SPAN_STMT, &s);
87319   if( rc!=SQLITE_OK ) return rc;
87320
87321   rc = sqlite3_bind_int(s, 1, iLevel);
87322   if( rc!=SQLITE_OK ) return rc;
87323
87324   rc = sqlite3_step(s);
87325   if( rc==SQLITE_DONE ) return SQLITE_DONE;  /* Should never happen */
87326   if( rc!=SQLITE_ROW ) return rc;
87327
87328   /* This happens if all segments at this level are entirely inline. */
87329   if( SQLITE_NULL==sqlite3_column_type(s, 0) ){
87330     /* We expect only one row.  We must execute another sqlite3_step()
87331      * to complete the iteration; otherwise the table will remain locked. */
87332     int rc2 = sqlite3_step(s);
87333     if( rc2==SQLITE_ROW ) return SQLITE_ERROR;
87334     return rc2;
87335   }
87336
87337   *piStartBlockid = sqlite3_column_int64(s, 0);
87338   *piEndBlockid = sqlite3_column_int64(s, 1);
87339
87340   /* We expect only one row.  We must execute another sqlite3_step()
87341    * to complete the iteration; otherwise the table will remain locked. */
87342   rc = sqlite3_step(s);
87343   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
87344   if( rc!=SQLITE_DONE ) return rc;
87345   return SQLITE_ROW;
87346 }
87347
87348 /* Delete the segment blocks and segment directory records for all
87349 ** segments at iLevel.
87350 */
87351 static int segdir_delete(fulltext_vtab *v, int iLevel){
87352   sqlite3_stmt *s;
87353   sqlite_int64 iStartBlockid, iEndBlockid;
87354   int rc = segdir_span(v, iLevel, &iStartBlockid, &iEndBlockid);
87355   if( rc!=SQLITE_ROW && rc!=SQLITE_DONE ) return rc;
87356
87357   if( rc==SQLITE_ROW ){
87358     rc = block_delete(v, iStartBlockid, iEndBlockid);
87359     if( rc!=SQLITE_OK ) return rc;
87360   }
87361
87362   /* Delete the segment directory itself. */
87363   rc = sql_get_statement(v, SEGDIR_DELETE_STMT, &s);
87364   if( rc!=SQLITE_OK ) return rc;
87365
87366   rc = sqlite3_bind_int64(s, 1, iLevel);
87367   if( rc!=SQLITE_OK ) return rc;
87368
87369   return sql_single_step(s);
87370 }
87371
87372 /* Delete entire fts index, SQLITE_OK on success, relevant error on
87373 ** failure.
87374 */
87375 static int segdir_delete_all(fulltext_vtab *v){
87376   sqlite3_stmt *s;
87377   int rc = sql_get_statement(v, SEGDIR_DELETE_ALL_STMT, &s);
87378   if( rc!=SQLITE_OK ) return rc;
87379
87380   rc = sql_single_step(s);
87381   if( rc!=SQLITE_OK ) return rc;
87382
87383   rc = sql_get_statement(v, BLOCK_DELETE_ALL_STMT, &s);
87384   if( rc!=SQLITE_OK ) return rc;
87385
87386   return sql_single_step(s);
87387 }
87388
87389 /* Returns SQLITE_OK with *pnSegments set to the number of entries in
87390 ** %_segdir and *piMaxLevel set to the highest level which has a
87391 ** segment.  Otherwise returns the SQLite error which caused failure.
87392 */
87393 static int segdir_count(fulltext_vtab *v, int *pnSegments, int *piMaxLevel){
87394   sqlite3_stmt *s;
87395   int rc = sql_get_statement(v, SEGDIR_COUNT_STMT, &s);
87396   if( rc!=SQLITE_OK ) return rc;
87397
87398   rc = sqlite3_step(s);
87399   /* TODO(shess): This case should not be possible?  Should stronger
87400   ** measures be taken if it happens?
87401   */
87402   if( rc==SQLITE_DONE ){
87403     *pnSegments = 0;
87404     *piMaxLevel = 0;
87405     return SQLITE_OK;
87406   }
87407   if( rc!=SQLITE_ROW ) return rc;
87408
87409   *pnSegments = sqlite3_column_int(s, 0);
87410   *piMaxLevel = sqlite3_column_int(s, 1);
87411
87412   /* We expect only one row.  We must execute another sqlite3_step()
87413    * to complete the iteration; otherwise the table will remain locked. */
87414   rc = sqlite3_step(s);
87415   if( rc==SQLITE_DONE ) return SQLITE_OK;
87416   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
87417   return rc;
87418 }
87419
87420 /* TODO(shess) clearPendingTerms() is far down the file because
87421 ** writeZeroSegment() is far down the file because LeafWriter is far
87422 ** down the file.  Consider refactoring the code to move the non-vtab
87423 ** code above the vtab code so that we don't need this forward
87424 ** reference.
87425 */
87426 static int clearPendingTerms(fulltext_vtab *v);
87427
87428 /*
87429 ** Free the memory used to contain a fulltext_vtab structure.
87430 */
87431 static void fulltext_vtab_destroy(fulltext_vtab *v){
87432   int iStmt, i;
87433
87434   FTSTRACE(("FTS3 Destroy %p\n", v));
87435   for( iStmt=0; iStmt<MAX_STMT; iStmt++ ){
87436     if( v->pFulltextStatements[iStmt]!=NULL ){
87437       sqlite3_finalize(v->pFulltextStatements[iStmt]);
87438       v->pFulltextStatements[iStmt] = NULL;
87439     }
87440   }
87441
87442   for( i=0; i<MERGE_COUNT; i++ ){
87443     if( v->pLeafSelectStmts[i]!=NULL ){
87444       sqlite3_finalize(v->pLeafSelectStmts[i]);
87445       v->pLeafSelectStmts[i] = NULL;
87446     }
87447   }
87448
87449   if( v->pTokenizer!=NULL ){
87450     v->pTokenizer->pModule->xDestroy(v->pTokenizer);
87451     v->pTokenizer = NULL;
87452   }
87453
87454   clearPendingTerms(v);
87455
87456   sqlite3_free(v->azColumn);
87457   for(i = 0; i < v->nColumn; ++i) {
87458     sqlite3_free(v->azContentColumn[i]);
87459   }
87460   sqlite3_free(v->azContentColumn);
87461   sqlite3_free(v);
87462 }
87463
87464 /*
87465 ** Token types for parsing the arguments to xConnect or xCreate.
87466 */
87467 #define TOKEN_EOF         0    /* End of file */
87468 #define TOKEN_SPACE       1    /* Any kind of whitespace */
87469 #define TOKEN_ID          2    /* An identifier */
87470 #define TOKEN_STRING      3    /* A string literal */
87471 #define TOKEN_PUNCT       4    /* A single punctuation character */
87472
87473 /*
87474 ** If X is a character that can be used in an identifier then
87475 ** ftsIdChar(X) will be true.  Otherwise it is false.
87476 **
87477 ** For ASCII, any character with the high-order bit set is
87478 ** allowed in an identifier.  For 7-bit characters, 
87479 ** isFtsIdChar[X] must be 1.
87480 **
87481 ** Ticket #1066.  the SQL standard does not allow '$' in the
87482 ** middle of identfiers.  But many SQL implementations do. 
87483 ** SQLite will allow '$' in identifiers for compatibility.
87484 ** But the feature is undocumented.
87485 */
87486 static const char isFtsIdChar[] = {
87487 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
87488     0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
87489     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
87490     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
87491     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
87492     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
87493     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
87494 };
87495 #define ftsIdChar(C)  (((c=C)&0x80)!=0 || (c>0x1f && isFtsIdChar[c-0x20]))
87496
87497
87498 /*
87499 ** Return the length of the token that begins at z[0]. 
87500 ** Store the token type in *tokenType before returning.
87501 */
87502 static int ftsGetToken(const char *z, int *tokenType){
87503   int i, c;
87504   switch( *z ){
87505     case 0: {
87506       *tokenType = TOKEN_EOF;
87507       return 0;
87508     }
87509     case ' ': case '\t': case '\n': case '\f': case '\r': {
87510       for(i=1; safe_isspace(z[i]); i++){}
87511       *tokenType = TOKEN_SPACE;
87512       return i;
87513     }
87514     case '`':
87515     case '\'':
87516     case '"': {
87517       int delim = z[0];
87518       for(i=1; (c=z[i])!=0; i++){
87519         if( c==delim ){
87520           if( z[i+1]==delim ){
87521             i++;
87522           }else{
87523             break;
87524           }
87525         }
87526       }
87527       *tokenType = TOKEN_STRING;
87528       return i + (c!=0);
87529     }
87530     case '[': {
87531       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
87532       *tokenType = TOKEN_ID;
87533       return i;
87534     }
87535     default: {
87536       if( !ftsIdChar(*z) ){
87537         break;
87538       }
87539       for(i=1; ftsIdChar(z[i]); i++){}
87540       *tokenType = TOKEN_ID;
87541       return i;
87542     }
87543   }
87544   *tokenType = TOKEN_PUNCT;
87545   return 1;
87546 }
87547
87548 /*
87549 ** A token extracted from a string is an instance of the following
87550 ** structure.
87551 */
87552 typedef struct FtsToken {
87553   const char *z;       /* Pointer to token text.  Not '\000' terminated */
87554   short int n;         /* Length of the token text in bytes. */
87555 } FtsToken;
87556
87557 /*
87558 ** Given a input string (which is really one of the argv[] parameters
87559 ** passed into xConnect or xCreate) split the string up into tokens.
87560 ** Return an array of pointers to '\000' terminated strings, one string
87561 ** for each non-whitespace token.
87562 **
87563 ** The returned array is terminated by a single NULL pointer.
87564 **
87565 ** Space to hold the returned array is obtained from a single
87566 ** malloc and should be freed by passing the return value to free().
87567 ** The individual strings within the token list are all a part of
87568 ** the single memory allocation and will all be freed at once.
87569 */
87570 static char **tokenizeString(const char *z, int *pnToken){
87571   int nToken = 0;
87572   FtsToken *aToken = sqlite3_malloc( strlen(z) * sizeof(aToken[0]) );
87573   int n = 1;
87574   int e, i;
87575   int totalSize = 0;
87576   char **azToken;
87577   char *zCopy;
87578   while( n>0 ){
87579     n = ftsGetToken(z, &e);
87580     if( e!=TOKEN_SPACE ){
87581       aToken[nToken].z = z;
87582       aToken[nToken].n = n;
87583       nToken++;
87584       totalSize += n+1;
87585     }
87586     z += n;
87587   }
87588   azToken = (char**)sqlite3_malloc( nToken*sizeof(char*) + totalSize );
87589   zCopy = (char*)&azToken[nToken];
87590   nToken--;
87591   for(i=0; i<nToken; i++){
87592     azToken[i] = zCopy;
87593     n = aToken[i].n;
87594     memcpy(zCopy, aToken[i].z, n);
87595     zCopy[n] = 0;
87596     zCopy += n+1;
87597   }
87598   azToken[nToken] = 0;
87599   sqlite3_free(aToken);
87600   *pnToken = nToken;
87601   return azToken;
87602 }
87603
87604 /*
87605 ** Convert an SQL-style quoted string into a normal string by removing
87606 ** the quote characters.  The conversion is done in-place.  If the
87607 ** input does not begin with a quote character, then this routine
87608 ** is a no-op.
87609 **
87610 ** Examples:
87611 **
87612 **     "abc"   becomes   abc
87613 **     'xyz'   becomes   xyz
87614 **     [pqr]   becomes   pqr
87615 **     `mno`   becomes   mno
87616 */
87617 static void dequoteString(char *z){
87618   int quote;
87619   int i, j;
87620   if( z==0 ) return;
87621   quote = z[0];
87622   switch( quote ){
87623     case '\'':  break;
87624     case '"':   break;
87625     case '`':   break;                /* For MySQL compatibility */
87626     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
87627     default:    return;
87628   }
87629   for(i=1, j=0; z[i]; i++){
87630     if( z[i]==quote ){
87631       if( z[i+1]==quote ){
87632         z[j++] = quote;
87633         i++;
87634       }else{
87635         z[j++] = 0;
87636         break;
87637       }
87638     }else{
87639       z[j++] = z[i];
87640     }
87641   }
87642 }
87643
87644 /*
87645 ** The input azIn is a NULL-terminated list of tokens.  Remove the first
87646 ** token and all punctuation tokens.  Remove the quotes from
87647 ** around string literal tokens.
87648 **
87649 ** Example:
87650 **
87651 **     input:      tokenize chinese ( 'simplifed' , 'mixed' )
87652 **     output:     chinese simplifed mixed
87653 **
87654 ** Another example:
87655 **
87656 **     input:      delimiters ( '[' , ']' , '...' )
87657 **     output:     [ ] ...
87658 */
87659 static void tokenListToIdList(char **azIn){
87660   int i, j;
87661   if( azIn ){
87662     for(i=0, j=-1; azIn[i]; i++){
87663       if( safe_isalnum(azIn[i][0]) || azIn[i][1] ){
87664         dequoteString(azIn[i]);
87665         if( j>=0 ){
87666           azIn[j] = azIn[i];
87667         }
87668         j++;
87669       }
87670     }
87671     azIn[j] = 0;
87672   }
87673 }
87674
87675
87676 /*
87677 ** Find the first alphanumeric token in the string zIn.  Null-terminate
87678 ** this token.  Remove any quotation marks.  And return a pointer to
87679 ** the result.
87680 */
87681 static char *firstToken(char *zIn, char **pzTail){
87682   int n, ttype;
87683   while(1){
87684     n = ftsGetToken(zIn, &ttype);
87685     if( ttype==TOKEN_SPACE ){
87686       zIn += n;
87687     }else if( ttype==TOKEN_EOF ){
87688       *pzTail = zIn;
87689       return 0;
87690     }else{
87691       zIn[n] = 0;
87692       *pzTail = &zIn[1];
87693       dequoteString(zIn);
87694       return zIn;
87695     }
87696   }
87697   /*NOTREACHED*/
87698 }
87699
87700 /* Return true if...
87701 **
87702 **   *  s begins with the string t, ignoring case
87703 **   *  s is longer than t
87704 **   *  The first character of s beyond t is not a alphanumeric
87705 ** 
87706 ** Ignore leading space in *s.
87707 **
87708 ** To put it another way, return true if the first token of
87709 ** s[] is t[].
87710 */
87711 static int startsWith(const char *s, const char *t){
87712   while( safe_isspace(*s) ){ s++; }
87713   while( *t ){
87714     if( safe_tolower(*s++)!=safe_tolower(*t++) ) return 0;
87715   }
87716   return *s!='_' && !safe_isalnum(*s);
87717 }
87718
87719 /*
87720 ** An instance of this structure defines the "spec" of a
87721 ** full text index.  This structure is populated by parseSpec
87722 ** and use by fulltextConnect and fulltextCreate.
87723 */
87724 typedef struct TableSpec {
87725   const char *zDb;         /* Logical database name */
87726   const char *zName;       /* Name of the full-text index */
87727   int nColumn;             /* Number of columns to be indexed */
87728   char **azColumn;         /* Original names of columns to be indexed */
87729   char **azContentColumn;  /* Column names for %_content */
87730   char **azTokenizer;      /* Name of tokenizer and its arguments */
87731 } TableSpec;
87732
87733 /*
87734 ** Reclaim all of the memory used by a TableSpec
87735 */
87736 static void clearTableSpec(TableSpec *p) {
87737   sqlite3_free(p->azColumn);
87738   sqlite3_free(p->azContentColumn);
87739   sqlite3_free(p->azTokenizer);
87740 }
87741
87742 /* Parse a CREATE VIRTUAL TABLE statement, which looks like this:
87743  *
87744  * CREATE VIRTUAL TABLE email
87745  *        USING fts3(subject, body, tokenize mytokenizer(myarg))
87746  *
87747  * We return parsed information in a TableSpec structure.
87748  * 
87749  */
87750 static int parseSpec(TableSpec *pSpec, int argc, const char *const*argv,
87751                      char**pzErr){
87752   int i, n;
87753   char *z, *zDummy;
87754   char **azArg;
87755   const char *zTokenizer = 0;    /* argv[] entry describing the tokenizer */
87756
87757   assert( argc>=3 );
87758   /* Current interface:
87759   ** argv[0] - module name
87760   ** argv[1] - database name
87761   ** argv[2] - table name
87762   ** argv[3..] - columns, optionally followed by tokenizer specification
87763   **             and snippet delimiters specification.
87764   */
87765
87766   /* Make a copy of the complete argv[][] array in a single allocation.
87767   ** The argv[][] array is read-only and transient.  We can write to the
87768   ** copy in order to modify things and the copy is persistent.
87769   */
87770   CLEAR(pSpec);
87771   for(i=n=0; i<argc; i++){
87772     n += strlen(argv[i]) + 1;
87773   }
87774   azArg = sqlite3_malloc( sizeof(char*)*argc + n );
87775   if( azArg==0 ){
87776     return SQLITE_NOMEM;
87777   }
87778   z = (char*)&azArg[argc];
87779   for(i=0; i<argc; i++){
87780     azArg[i] = z;
87781     strcpy(z, argv[i]);
87782     z += strlen(z)+1;
87783   }
87784
87785   /* Identify the column names and the tokenizer and delimiter arguments
87786   ** in the argv[][] array.
87787   */
87788   pSpec->zDb = azArg[1];
87789   pSpec->zName = azArg[2];
87790   pSpec->nColumn = 0;
87791   pSpec->azColumn = azArg;
87792   zTokenizer = "tokenize simple";
87793   for(i=3; i<argc; ++i){
87794     if( startsWith(azArg[i],"tokenize") ){
87795       zTokenizer = azArg[i];
87796     }else{
87797       z = azArg[pSpec->nColumn] = firstToken(azArg[i], &zDummy);
87798       pSpec->nColumn++;
87799     }
87800   }
87801   if( pSpec->nColumn==0 ){
87802     azArg[0] = "content";
87803     pSpec->nColumn = 1;
87804   }
87805
87806   /*
87807   ** Construct the list of content column names.
87808   **
87809   ** Each content column name will be of the form cNNAAAA
87810   ** where NN is the column number and AAAA is the sanitized
87811   ** column name.  "sanitized" means that special characters are
87812   ** converted to "_".  The cNN prefix guarantees that all column
87813   ** names are unique.
87814   **
87815   ** The AAAA suffix is not strictly necessary.  It is included
87816   ** for the convenience of people who might examine the generated
87817   ** %_content table and wonder what the columns are used for.
87818   */
87819   pSpec->azContentColumn = sqlite3_malloc( pSpec->nColumn * sizeof(char *) );
87820   if( pSpec->azContentColumn==0 ){
87821     clearTableSpec(pSpec);
87822     return SQLITE_NOMEM;
87823   }
87824   for(i=0; i<pSpec->nColumn; i++){
87825     char *p;
87826     pSpec->azContentColumn[i] = sqlite3_mprintf("c%d%s", i, azArg[i]);
87827     for (p = pSpec->azContentColumn[i]; *p ; ++p) {
87828       if( !safe_isalnum(*p) ) *p = '_';
87829     }
87830   }
87831
87832   /*
87833   ** Parse the tokenizer specification string.
87834   */
87835   pSpec->azTokenizer = tokenizeString(zTokenizer, &n);
87836   tokenListToIdList(pSpec->azTokenizer);
87837
87838   return SQLITE_OK;
87839 }
87840
87841 /*
87842 ** Generate a CREATE TABLE statement that describes the schema of
87843 ** the virtual table.  Return a pointer to this schema string.
87844 **
87845 ** Space is obtained from sqlite3_mprintf() and should be freed
87846 ** using sqlite3_free().
87847 */
87848 static char *fulltextSchema(
87849   int nColumn,                  /* Number of columns */
87850   const char *const* azColumn,  /* List of columns */
87851   const char *zTableName        /* Name of the table */
87852 ){
87853   int i;
87854   char *zSchema, *zNext;
87855   const char *zSep = "(";
87856   zSchema = sqlite3_mprintf("CREATE TABLE x");
87857   for(i=0; i<nColumn; i++){
87858     zNext = sqlite3_mprintf("%s%s%Q", zSchema, zSep, azColumn[i]);
87859     sqlite3_free(zSchema);
87860     zSchema = zNext;
87861     zSep = ",";
87862   }
87863   zNext = sqlite3_mprintf("%s,%Q HIDDEN", zSchema, zTableName);
87864   sqlite3_free(zSchema);
87865   zSchema = zNext;
87866   zNext = sqlite3_mprintf("%s,docid HIDDEN)", zSchema);
87867   sqlite3_free(zSchema);
87868   return zNext;
87869 }
87870
87871 /*
87872 ** Build a new sqlite3_vtab structure that will describe the
87873 ** fulltext index defined by spec.
87874 */
87875 static int constructVtab(
87876   sqlite3 *db,              /* The SQLite database connection */
87877   fts3Hash *pHash,          /* Hash table containing tokenizers */
87878   TableSpec *spec,          /* Parsed spec information from parseSpec() */
87879   sqlite3_vtab **ppVTab,    /* Write the resulting vtab structure here */
87880   char **pzErr              /* Write any error message here */
87881 ){
87882   int rc;
87883   int n;
87884   fulltext_vtab *v = 0;
87885   const sqlite3_tokenizer_module *m = NULL;
87886   char *schema;
87887
87888   char const *zTok;         /* Name of tokenizer to use for this fts table */
87889   int nTok;                 /* Length of zTok, including nul terminator */
87890
87891   v = (fulltext_vtab *) sqlite3_malloc(sizeof(fulltext_vtab));
87892   if( v==0 ) return SQLITE_NOMEM;
87893   CLEAR(v);
87894   /* sqlite will initialize v->base */
87895   v->db = db;
87896   v->zDb = spec->zDb;       /* Freed when azColumn is freed */
87897   v->zName = spec->zName;   /* Freed when azColumn is freed */
87898   v->nColumn = spec->nColumn;
87899   v->azContentColumn = spec->azContentColumn;
87900   spec->azContentColumn = 0;
87901   v->azColumn = spec->azColumn;
87902   spec->azColumn = 0;
87903
87904   if( spec->azTokenizer==0 ){
87905     return SQLITE_NOMEM;
87906   }
87907
87908   zTok = spec->azTokenizer[0]; 
87909   if( !zTok ){
87910     zTok = "simple";
87911   }
87912   nTok = strlen(zTok)+1;
87913
87914   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zTok, nTok);
87915   if( !m ){
87916     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", spec->azTokenizer[0]);
87917     rc = SQLITE_ERROR;
87918     goto err;
87919   }
87920
87921   for(n=0; spec->azTokenizer[n]; n++){}
87922   if( n ){
87923     rc = m->xCreate(n-1, (const char*const*)&spec->azTokenizer[1],
87924                     &v->pTokenizer);
87925   }else{
87926     rc = m->xCreate(0, 0, &v->pTokenizer);
87927   }
87928   if( rc!=SQLITE_OK ) goto err;
87929   v->pTokenizer->pModule = m;
87930
87931   /* TODO: verify the existence of backing tables foo_content, foo_term */
87932
87933   schema = fulltextSchema(v->nColumn, (const char*const*)v->azColumn,
87934                           spec->zName);
87935   rc = sqlite3_declare_vtab(db, schema);
87936   sqlite3_free(schema);
87937   if( rc!=SQLITE_OK ) goto err;
87938
87939   memset(v->pFulltextStatements, 0, sizeof(v->pFulltextStatements));
87940
87941   /* Indicate that the buffer is not live. */
87942   v->nPendingData = -1;
87943
87944   *ppVTab = &v->base;
87945   FTSTRACE(("FTS3 Connect %p\n", v));
87946
87947   return rc;
87948
87949 err:
87950   fulltext_vtab_destroy(v);
87951   return rc;
87952 }
87953
87954 static int fulltextConnect(
87955   sqlite3 *db,
87956   void *pAux,
87957   int argc, const char *const*argv,
87958   sqlite3_vtab **ppVTab,
87959   char **pzErr
87960 ){
87961   TableSpec spec;
87962   int rc = parseSpec(&spec, argc, argv, pzErr);
87963   if( rc!=SQLITE_OK ) return rc;
87964
87965   rc = constructVtab(db, (fts3Hash *)pAux, &spec, ppVTab, pzErr);
87966   clearTableSpec(&spec);
87967   return rc;
87968 }
87969
87970 /* The %_content table holds the text of each document, with
87971 ** the docid column exposed as the SQLite rowid for the table.
87972 */
87973 /* TODO(shess) This comment needs elaboration to match the updated
87974 ** code.  Work it into the top-of-file comment at that time.
87975 */
87976 static int fulltextCreate(sqlite3 *db, void *pAux,
87977                           int argc, const char * const *argv,
87978                           sqlite3_vtab **ppVTab, char **pzErr){
87979   int rc;
87980   TableSpec spec;
87981   StringBuffer schema;
87982   FTSTRACE(("FTS3 Create\n"));
87983
87984   rc = parseSpec(&spec, argc, argv, pzErr);
87985   if( rc!=SQLITE_OK ) return rc;
87986
87987   initStringBuffer(&schema);
87988   append(&schema, "CREATE TABLE %_content(");
87989   append(&schema, "  docid INTEGER PRIMARY KEY,");
87990   appendList(&schema, spec.nColumn, spec.azContentColumn);
87991   append(&schema, ")");
87992   rc = sql_exec(db, spec.zDb, spec.zName, stringBufferData(&schema));
87993   stringBufferDestroy(&schema);
87994   if( rc!=SQLITE_OK ) goto out;
87995
87996   rc = sql_exec(db, spec.zDb, spec.zName,
87997                 "create table %_segments("
87998                 "  blockid INTEGER PRIMARY KEY,"
87999                 "  block blob"
88000                 ");"
88001                 );
88002   if( rc!=SQLITE_OK ) goto out;
88003
88004   rc = sql_exec(db, spec.zDb, spec.zName,
88005                 "create table %_segdir("
88006                 "  level integer,"
88007                 "  idx integer,"
88008                 "  start_block integer,"
88009                 "  leaves_end_block integer,"
88010                 "  end_block integer,"
88011                 "  root blob,"
88012                 "  primary key(level, idx)"
88013                 ");");
88014   if( rc!=SQLITE_OK ) goto out;
88015
88016   rc = constructVtab(db, (fts3Hash *)pAux, &spec, ppVTab, pzErr);
88017
88018 out:
88019   clearTableSpec(&spec);
88020   return rc;
88021 }
88022
88023 /* Decide how to handle an SQL query. */
88024 static int fulltextBestIndex(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
88025   fulltext_vtab *v = (fulltext_vtab *)pVTab;
88026   int i;
88027   FTSTRACE(("FTS3 BestIndex\n"));
88028
88029   for(i=0; i<pInfo->nConstraint; ++i){
88030     const struct sqlite3_index_constraint *pConstraint;
88031     pConstraint = &pInfo->aConstraint[i];
88032     if( pConstraint->usable ) {
88033       if( (pConstraint->iColumn==-1 || pConstraint->iColumn==v->nColumn+1) &&
88034           pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
88035         pInfo->idxNum = QUERY_DOCID;      /* lookup by docid */
88036         FTSTRACE(("FTS3 QUERY_DOCID\n"));
88037       } else if( pConstraint->iColumn>=0 && pConstraint->iColumn<=v->nColumn &&
88038                  pConstraint->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
88039         /* full-text search */
88040         pInfo->idxNum = QUERY_FULLTEXT + pConstraint->iColumn;
88041         FTSTRACE(("FTS3 QUERY_FULLTEXT %d\n", pConstraint->iColumn));
88042       } else continue;
88043
88044       pInfo->aConstraintUsage[i].argvIndex = 1;
88045       pInfo->aConstraintUsage[i].omit = 1;
88046
88047       /* An arbitrary value for now.
88048        * TODO: Perhaps docid matches should be considered cheaper than
88049        * full-text searches. */
88050       pInfo->estimatedCost = 1.0;   
88051
88052       return SQLITE_OK;
88053     }
88054   }
88055   pInfo->idxNum = QUERY_GENERIC;
88056   return SQLITE_OK;
88057 }
88058
88059 static int fulltextDisconnect(sqlite3_vtab *pVTab){
88060   FTSTRACE(("FTS3 Disconnect %p\n", pVTab));
88061   fulltext_vtab_destroy((fulltext_vtab *)pVTab);
88062   return SQLITE_OK;
88063 }
88064
88065 static int fulltextDestroy(sqlite3_vtab *pVTab){
88066   fulltext_vtab *v = (fulltext_vtab *)pVTab;
88067   int rc;
88068
88069   FTSTRACE(("FTS3 Destroy %p\n", pVTab));
88070   rc = sql_exec(v->db, v->zDb, v->zName,
88071                 "drop table if exists %_content;"
88072                 "drop table if exists %_segments;"
88073                 "drop table if exists %_segdir;"
88074                 );
88075   if( rc!=SQLITE_OK ) return rc;
88076
88077   fulltext_vtab_destroy((fulltext_vtab *)pVTab);
88078   return SQLITE_OK;
88079 }
88080
88081 static int fulltextOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
88082   fulltext_cursor *c;
88083
88084   c = (fulltext_cursor *) sqlite3_malloc(sizeof(fulltext_cursor));
88085   if( c ){
88086     memset(c, 0, sizeof(fulltext_cursor));
88087     /* sqlite will initialize c->base */
88088     *ppCursor = &c->base;
88089     FTSTRACE(("FTS3 Open %p: %p\n", pVTab, c));
88090     return SQLITE_OK;
88091   }else{
88092     return SQLITE_NOMEM;
88093   }
88094 }
88095
88096
88097 /* Free all of the dynamically allocated memory held by *q
88098 */
88099 static void queryClear(Query *q){
88100   int i;
88101   for(i = 0; i < q->nTerms; ++i){
88102     sqlite3_free(q->pTerms[i].pTerm);
88103   }
88104   sqlite3_free(q->pTerms);
88105   CLEAR(q);
88106 }
88107
88108 /* Free all of the dynamically allocated memory held by the
88109 ** Snippet
88110 */
88111 static void snippetClear(Snippet *p){
88112   sqlite3_free(p->aMatch);
88113   sqlite3_free(p->zOffset);
88114   sqlite3_free(p->zSnippet);
88115   CLEAR(p);
88116 }
88117 /*
88118 ** Append a single entry to the p->aMatch[] log.
88119 */
88120 static void snippetAppendMatch(
88121   Snippet *p,               /* Append the entry to this snippet */
88122   int iCol, int iTerm,      /* The column and query term */
88123   int iToken,               /* Matching token in document */
88124   int iStart, int nByte     /* Offset and size of the match */
88125 ){
88126   int i;
88127   struct snippetMatch *pMatch;
88128   if( p->nMatch+1>=p->nAlloc ){
88129     p->nAlloc = p->nAlloc*2 + 10;
88130     p->aMatch = sqlite3_realloc(p->aMatch, p->nAlloc*sizeof(p->aMatch[0]) );
88131     if( p->aMatch==0 ){
88132       p->nMatch = 0;
88133       p->nAlloc = 0;
88134       return;
88135     }
88136   }
88137   i = p->nMatch++;
88138   pMatch = &p->aMatch[i];
88139   pMatch->iCol = iCol;
88140   pMatch->iTerm = iTerm;
88141   pMatch->iToken = iToken;
88142   pMatch->iStart = iStart;
88143   pMatch->nByte = nByte;
88144 }
88145
88146 /*
88147 ** Sizing information for the circular buffer used in snippetOffsetsOfColumn()
88148 */
88149 #define FTS3_ROTOR_SZ   (32)
88150 #define FTS3_ROTOR_MASK (FTS3_ROTOR_SZ-1)
88151
88152 /*
88153 ** Add entries to pSnippet->aMatch[] for every match that occurs against
88154 ** document zDoc[0..nDoc-1] which is stored in column iColumn.
88155 */
88156 static void snippetOffsetsOfColumn(
88157   Query *pQuery,
88158   Snippet *pSnippet,
88159   int iColumn,
88160   const char *zDoc,
88161   int nDoc
88162 ){
88163   const sqlite3_tokenizer_module *pTModule;  /* The tokenizer module */
88164   sqlite3_tokenizer *pTokenizer;             /* The specific tokenizer */
88165   sqlite3_tokenizer_cursor *pTCursor;        /* Tokenizer cursor */
88166   fulltext_vtab *pVtab;                /* The full text index */
88167   int nColumn;                         /* Number of columns in the index */
88168   const QueryTerm *aTerm;              /* Query string terms */
88169   int nTerm;                           /* Number of query string terms */  
88170   int i, j;                            /* Loop counters */
88171   int rc;                              /* Return code */
88172   unsigned int match, prevMatch;       /* Phrase search bitmasks */
88173   const char *zToken;                  /* Next token from the tokenizer */
88174   int nToken;                          /* Size of zToken */
88175   int iBegin, iEnd, iPos;              /* Offsets of beginning and end */
88176
88177   /* The following variables keep a circular buffer of the last
88178   ** few tokens */
88179   unsigned int iRotor = 0;             /* Index of current token */
88180   int iRotorBegin[FTS3_ROTOR_SZ];      /* Beginning offset of token */
88181   int iRotorLen[FTS3_ROTOR_SZ];        /* Length of token */
88182
88183   pVtab = pQuery->pFts;
88184   nColumn = pVtab->nColumn;
88185   pTokenizer = pVtab->pTokenizer;
88186   pTModule = pTokenizer->pModule;
88187   rc = pTModule->xOpen(pTokenizer, zDoc, nDoc, &pTCursor);
88188   if( rc ) return;
88189   pTCursor->pTokenizer = pTokenizer;
88190   aTerm = pQuery->pTerms;
88191   nTerm = pQuery->nTerms;
88192   if( nTerm>=FTS3_ROTOR_SZ ){
88193     nTerm = FTS3_ROTOR_SZ - 1;
88194   }
88195   prevMatch = 0;
88196   while(1){
88197     rc = pTModule->xNext(pTCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
88198     if( rc ) break;
88199     iRotorBegin[iRotor&FTS3_ROTOR_MASK] = iBegin;
88200     iRotorLen[iRotor&FTS3_ROTOR_MASK] = iEnd-iBegin;
88201     match = 0;
88202     for(i=0; i<nTerm; i++){
88203       int iCol;
88204       iCol = aTerm[i].iColumn;
88205       if( iCol>=0 && iCol<nColumn && iCol!=iColumn ) continue;
88206       if( aTerm[i].nTerm>nToken ) continue;
88207       if( !aTerm[i].isPrefix && aTerm[i].nTerm<nToken ) continue;
88208       assert( aTerm[i].nTerm<=nToken );
88209       if( memcmp(aTerm[i].pTerm, zToken, aTerm[i].nTerm) ) continue;
88210       if( aTerm[i].iPhrase>1 && (prevMatch & (1<<i))==0 ) continue;
88211       match |= 1<<i;
88212       if( i==nTerm-1 || aTerm[i+1].iPhrase==1 ){
88213         for(j=aTerm[i].iPhrase-1; j>=0; j--){
88214           int k = (iRotor-j) & FTS3_ROTOR_MASK;
88215           snippetAppendMatch(pSnippet, iColumn, i-j, iPos-j,
88216                 iRotorBegin[k], iRotorLen[k]);
88217         }
88218       }
88219     }
88220     prevMatch = match<<1;
88221     iRotor++;
88222   }
88223   pTModule->xClose(pTCursor);  
88224 }
88225
88226 /*
88227 ** Remove entries from the pSnippet structure to account for the NEAR
88228 ** operator. When this is called, pSnippet contains the list of token 
88229 ** offsets produced by treating all NEAR operators as AND operators.
88230 ** This function removes any entries that should not be present after
88231 ** accounting for the NEAR restriction. For example, if the queried
88232 ** document is:
88233 **
88234 **     "A B C D E A"
88235 **
88236 ** and the query is:
88237 ** 
88238 **     A NEAR/0 E
88239 **
88240 ** then when this function is called the Snippet contains token offsets
88241 ** 0, 4 and 5. This function removes the "0" entry (because the first A
88242 ** is not near enough to an E).
88243 */
88244 static void trimSnippetOffsetsForNear(Query *pQuery, Snippet *pSnippet){
88245   int ii;
88246   int iDir = 1;
88247
88248   while(iDir>-2) {
88249     assert( iDir==1 || iDir==-1 );
88250     for(ii=0; ii<pSnippet->nMatch; ii++){
88251       int jj;
88252       int nNear;
88253       struct snippetMatch *pMatch = &pSnippet->aMatch[ii];
88254       QueryTerm *pQueryTerm = &pQuery->pTerms[pMatch->iTerm];
88255
88256       if( (pMatch->iTerm+iDir)<0 
88257        || (pMatch->iTerm+iDir)>=pQuery->nTerms
88258       ){
88259         continue;
88260       }
88261      
88262       nNear = pQueryTerm->nNear;
88263       if( iDir<0 ){
88264         nNear = pQueryTerm[-1].nNear;
88265       }
88266   
88267       if( pMatch->iTerm>=0 && nNear ){
88268         int isOk = 0;
88269         int iNextTerm = pMatch->iTerm+iDir;
88270         int iPrevTerm = iNextTerm;
88271
88272         int iEndToken;
88273         int iStartToken;
88274
88275         if( iDir<0 ){
88276           int nPhrase = 1;
88277           iStartToken = pMatch->iToken;
88278           while( (pMatch->iTerm+nPhrase)<pQuery->nTerms 
88279               && pQuery->pTerms[pMatch->iTerm+nPhrase].iPhrase>1 
88280           ){
88281             nPhrase++;
88282           }
88283           iEndToken = iStartToken + nPhrase - 1;
88284         }else{
88285           iEndToken   = pMatch->iToken;
88286           iStartToken = pMatch->iToken+1-pQueryTerm->iPhrase;
88287         }
88288
88289         while( pQuery->pTerms[iNextTerm].iPhrase>1 ){
88290           iNextTerm--;
88291         }
88292         while( (iPrevTerm+1)<pQuery->nTerms && 
88293                pQuery->pTerms[iPrevTerm+1].iPhrase>1 
88294         ){
88295           iPrevTerm++;
88296         }
88297   
88298         for(jj=0; isOk==0 && jj<pSnippet->nMatch; jj++){
88299           struct snippetMatch *p = &pSnippet->aMatch[jj];
88300           if( p->iCol==pMatch->iCol && ((
88301                p->iTerm==iNextTerm && 
88302                p->iToken>iEndToken && 
88303                p->iToken<=iEndToken+nNear
88304           ) || (
88305                p->iTerm==iPrevTerm && 
88306                p->iToken<iStartToken && 
88307                p->iToken>=iStartToken-nNear
88308           ))){
88309             isOk = 1;
88310           }
88311         }
88312         if( !isOk ){
88313           for(jj=1-pQueryTerm->iPhrase; jj<=0; jj++){
88314             pMatch[jj].iTerm = -1;
88315           }
88316           ii = -1;
88317           iDir = 1;
88318         }
88319       }
88320     }
88321     iDir -= 2;
88322   }
88323 }
88324
88325 /*
88326 ** Compute all offsets for the current row of the query.  
88327 ** If the offsets have already been computed, this routine is a no-op.
88328 */
88329 static void snippetAllOffsets(fulltext_cursor *p){
88330   int nColumn;
88331   int iColumn, i;
88332   int iFirst, iLast;
88333   fulltext_vtab *pFts;
88334
88335   if( p->snippet.nMatch ) return;
88336   if( p->q.nTerms==0 ) return;
88337   pFts = p->q.pFts;
88338   nColumn = pFts->nColumn;
88339   iColumn = (p->iCursorType - QUERY_FULLTEXT);
88340   if( iColumn<0 || iColumn>=nColumn ){
88341     iFirst = 0;
88342     iLast = nColumn-1;
88343   }else{
88344     iFirst = iColumn;
88345     iLast = iColumn;
88346   }
88347   for(i=iFirst; i<=iLast; i++){
88348     const char *zDoc;
88349     int nDoc;
88350     zDoc = (const char*)sqlite3_column_text(p->pStmt, i+1);
88351     nDoc = sqlite3_column_bytes(p->pStmt, i+1);
88352     snippetOffsetsOfColumn(&p->q, &p->snippet, i, zDoc, nDoc);
88353   }
88354
88355   trimSnippetOffsetsForNear(&p->q, &p->snippet);
88356 }
88357
88358 /*
88359 ** Convert the information in the aMatch[] array of the snippet
88360 ** into the string zOffset[0..nOffset-1].
88361 */
88362 static void snippetOffsetText(Snippet *p){
88363   int i;
88364   int cnt = 0;
88365   StringBuffer sb;
88366   char zBuf[200];
88367   if( p->zOffset ) return;
88368   initStringBuffer(&sb);
88369   for(i=0; i<p->nMatch; i++){
88370     struct snippetMatch *pMatch = &p->aMatch[i];
88371     if( pMatch->iTerm>=0 ){
88372       /* If snippetMatch.iTerm is less than 0, then the match was 
88373       ** discarded as part of processing the NEAR operator (see the 
88374       ** trimSnippetOffsetsForNear() function for details). Ignore 
88375       ** it in this case
88376       */
88377       zBuf[0] = ' ';
88378       sqlite3_snprintf(sizeof(zBuf)-1, &zBuf[cnt>0], "%d %d %d %d",
88379           pMatch->iCol, pMatch->iTerm, pMatch->iStart, pMatch->nByte);
88380       append(&sb, zBuf);
88381       cnt++;
88382     }
88383   }
88384   p->zOffset = stringBufferData(&sb);
88385   p->nOffset = stringBufferLength(&sb);
88386 }
88387
88388 /*
88389 ** zDoc[0..nDoc-1] is phrase of text.  aMatch[0..nMatch-1] are a set
88390 ** of matching words some of which might be in zDoc.  zDoc is column
88391 ** number iCol.
88392 **
88393 ** iBreak is suggested spot in zDoc where we could begin or end an
88394 ** excerpt.  Return a value similar to iBreak but possibly adjusted
88395 ** to be a little left or right so that the break point is better.
88396 */
88397 static int wordBoundary(
88398   int iBreak,                   /* The suggested break point */
88399   const char *zDoc,             /* Document text */
88400   int nDoc,                     /* Number of bytes in zDoc[] */
88401   struct snippetMatch *aMatch,  /* Matching words */
88402   int nMatch,                   /* Number of entries in aMatch[] */
88403   int iCol                      /* The column number for zDoc[] */
88404 ){
88405   int i;
88406   if( iBreak<=10 ){
88407     return 0;
88408   }
88409   if( iBreak>=nDoc-10 ){
88410     return nDoc;
88411   }
88412   for(i=0; i<nMatch && aMatch[i].iCol<iCol; i++){}
88413   while( i<nMatch && aMatch[i].iStart+aMatch[i].nByte<iBreak ){ i++; }
88414   if( i<nMatch ){
88415     if( aMatch[i].iStart<iBreak+10 ){
88416       return aMatch[i].iStart;
88417     }
88418     if( i>0 && aMatch[i-1].iStart+aMatch[i-1].nByte>=iBreak ){
88419       return aMatch[i-1].iStart;
88420     }
88421   }
88422   for(i=1; i<=10; i++){
88423     if( safe_isspace(zDoc[iBreak-i]) ){
88424       return iBreak - i + 1;
88425     }
88426     if( safe_isspace(zDoc[iBreak+i]) ){
88427       return iBreak + i + 1;
88428     }
88429   }
88430   return iBreak;
88431 }
88432
88433
88434
88435 /*
88436 ** Allowed values for Snippet.aMatch[].snStatus
88437 */
88438 #define SNIPPET_IGNORE  0   /* It is ok to omit this match from the snippet */
88439 #define SNIPPET_DESIRED 1   /* We want to include this match in the snippet */
88440
88441 /*
88442 ** Generate the text of a snippet.
88443 */
88444 static void snippetText(
88445   fulltext_cursor *pCursor,   /* The cursor we need the snippet for */
88446   const char *zStartMark,     /* Markup to appear before each match */
88447   const char *zEndMark,       /* Markup to appear after each match */
88448   const char *zEllipsis       /* Ellipsis mark */
88449 ){
88450   int i, j;
88451   struct snippetMatch *aMatch;
88452   int nMatch;
88453   int nDesired;
88454   StringBuffer sb;
88455   int tailCol;
88456   int tailOffset;
88457   int iCol;
88458   int nDoc;
88459   const char *zDoc;
88460   int iStart, iEnd;
88461   int tailEllipsis = 0;
88462   int iMatch;
88463   
88464
88465   sqlite3_free(pCursor->snippet.zSnippet);
88466   pCursor->snippet.zSnippet = 0;
88467   aMatch = pCursor->snippet.aMatch;
88468   nMatch = pCursor->snippet.nMatch;
88469   initStringBuffer(&sb);
88470
88471   for(i=0; i<nMatch; i++){
88472     aMatch[i].snStatus = SNIPPET_IGNORE;
88473   }
88474   nDesired = 0;
88475   for(i=0; i<pCursor->q.nTerms; i++){
88476     for(j=0; j<nMatch; j++){
88477       if( aMatch[j].iTerm==i ){
88478         aMatch[j].snStatus = SNIPPET_DESIRED;
88479         nDesired++;
88480         break;
88481       }
88482     }
88483   }
88484
88485   iMatch = 0;
88486   tailCol = -1;
88487   tailOffset = 0;
88488   for(i=0; i<nMatch && nDesired>0; i++){
88489     if( aMatch[i].snStatus!=SNIPPET_DESIRED ) continue;
88490     nDesired--;
88491     iCol = aMatch[i].iCol;
88492     zDoc = (const char*)sqlite3_column_text(pCursor->pStmt, iCol+1);
88493     nDoc = sqlite3_column_bytes(pCursor->pStmt, iCol+1);
88494     iStart = aMatch[i].iStart - 40;
88495     iStart = wordBoundary(iStart, zDoc, nDoc, aMatch, nMatch, iCol);
88496     if( iStart<=10 ){
88497       iStart = 0;
88498     }
88499     if( iCol==tailCol && iStart<=tailOffset+20 ){
88500       iStart = tailOffset;
88501     }
88502     if( (iCol!=tailCol && tailCol>=0) || iStart!=tailOffset ){
88503       trimWhiteSpace(&sb);
88504       appendWhiteSpace(&sb);
88505       append(&sb, zEllipsis);
88506       appendWhiteSpace(&sb);
88507     }
88508     iEnd = aMatch[i].iStart + aMatch[i].nByte + 40;
88509     iEnd = wordBoundary(iEnd, zDoc, nDoc, aMatch, nMatch, iCol);
88510     if( iEnd>=nDoc-10 ){
88511       iEnd = nDoc;
88512       tailEllipsis = 0;
88513     }else{
88514       tailEllipsis = 1;
88515     }
88516     while( iMatch<nMatch && aMatch[iMatch].iCol<iCol ){ iMatch++; }
88517     while( iStart<iEnd ){
88518       while( iMatch<nMatch && aMatch[iMatch].iStart<iStart
88519              && aMatch[iMatch].iCol<=iCol ){
88520         iMatch++;
88521       }
88522       if( iMatch<nMatch && aMatch[iMatch].iStart<iEnd
88523              && aMatch[iMatch].iCol==iCol ){
88524         nappend(&sb, &zDoc[iStart], aMatch[iMatch].iStart - iStart);
88525         iStart = aMatch[iMatch].iStart;
88526         append(&sb, zStartMark);
88527         nappend(&sb, &zDoc[iStart], aMatch[iMatch].nByte);
88528         append(&sb, zEndMark);
88529         iStart += aMatch[iMatch].nByte;
88530         for(j=iMatch+1; j<nMatch; j++){
88531           if( aMatch[j].iTerm==aMatch[iMatch].iTerm
88532               && aMatch[j].snStatus==SNIPPET_DESIRED ){
88533             nDesired--;
88534             aMatch[j].snStatus = SNIPPET_IGNORE;
88535           }
88536         }
88537       }else{
88538         nappend(&sb, &zDoc[iStart], iEnd - iStart);
88539         iStart = iEnd;
88540       }
88541     }
88542     tailCol = iCol;
88543     tailOffset = iEnd;
88544   }
88545   trimWhiteSpace(&sb);
88546   if( tailEllipsis ){
88547     appendWhiteSpace(&sb);
88548     append(&sb, zEllipsis);
88549   }
88550   pCursor->snippet.zSnippet = stringBufferData(&sb);
88551   pCursor->snippet.nSnippet = stringBufferLength(&sb);
88552 }
88553
88554
88555 /*
88556 ** Close the cursor.  For additional information see the documentation
88557 ** on the xClose method of the virtual table interface.
88558 */
88559 static int fulltextClose(sqlite3_vtab_cursor *pCursor){
88560   fulltext_cursor *c = (fulltext_cursor *) pCursor;
88561   FTSTRACE(("FTS3 Close %p\n", c));
88562   sqlite3_finalize(c->pStmt);
88563   queryClear(&c->q);
88564   snippetClear(&c->snippet);
88565   if( c->result.nData!=0 ) dlrDestroy(&c->reader);
88566   dataBufferDestroy(&c->result);
88567   sqlite3_free(c);
88568   return SQLITE_OK;
88569 }
88570
88571 static int fulltextNext(sqlite3_vtab_cursor *pCursor){
88572   fulltext_cursor *c = (fulltext_cursor *) pCursor;
88573   int rc;
88574
88575   FTSTRACE(("FTS3 Next %p\n", pCursor));
88576   snippetClear(&c->snippet);
88577   if( c->iCursorType < QUERY_FULLTEXT ){
88578     /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
88579     rc = sqlite3_step(c->pStmt);
88580     switch( rc ){
88581       case SQLITE_ROW:
88582         c->eof = 0;
88583         return SQLITE_OK;
88584       case SQLITE_DONE:
88585         c->eof = 1;
88586         return SQLITE_OK;
88587       default:
88588         c->eof = 1;
88589         return rc;
88590     }
88591   } else {  /* full-text query */
88592     rc = sqlite3_reset(c->pStmt);
88593     if( rc!=SQLITE_OK ) return rc;
88594
88595     if( c->result.nData==0 || dlrAtEnd(&c->reader) ){
88596       c->eof = 1;
88597       return SQLITE_OK;
88598     }
88599     rc = sqlite3_bind_int64(c->pStmt, 1, dlrDocid(&c->reader));
88600     dlrStep(&c->reader);
88601     if( rc!=SQLITE_OK ) return rc;
88602     /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
88603     rc = sqlite3_step(c->pStmt);
88604     if( rc==SQLITE_ROW ){   /* the case we expect */
88605       c->eof = 0;
88606       return SQLITE_OK;
88607     }
88608     /* an error occurred; abort */
88609     return rc==SQLITE_DONE ? SQLITE_ERROR : rc;
88610   }
88611 }
88612
88613
88614 /* TODO(shess) If we pushed LeafReader to the top of the file, or to
88615 ** another file, term_select() could be pushed above
88616 ** docListOfTerm().
88617 */
88618 static int termSelect(fulltext_vtab *v, int iColumn,
88619                       const char *pTerm, int nTerm, int isPrefix,
88620                       DocListType iType, DataBuffer *out);
88621
88622 /* Return a DocList corresponding to the query term *pTerm.  If *pTerm
88623 ** is the first term of a phrase query, go ahead and evaluate the phrase
88624 ** query and return the doclist for the entire phrase query.
88625 **
88626 ** The resulting DL_DOCIDS doclist is stored in pResult, which is
88627 ** overwritten.
88628 */
88629 static int docListOfTerm(
88630   fulltext_vtab *v,    /* The full text index */
88631   int iColumn,         /* column to restrict to.  No restriction if >=nColumn */
88632   QueryTerm *pQTerm,   /* Term we are looking for, or 1st term of a phrase */
88633   DataBuffer *pResult  /* Write the result here */
88634 ){
88635   DataBuffer left, right, new;
88636   int i, rc;
88637
88638   /* No phrase search if no position info. */
88639   assert( pQTerm->nPhrase==0 || DL_DEFAULT!=DL_DOCIDS );
88640
88641   /* This code should never be called with buffered updates. */
88642   assert( v->nPendingData<0 );
88643
88644   dataBufferInit(&left, 0);
88645   rc = termSelect(v, iColumn, pQTerm->pTerm, pQTerm->nTerm, pQTerm->isPrefix,
88646                   (0<pQTerm->nPhrase ? DL_POSITIONS : DL_DOCIDS), &left);
88647   if( rc ) return rc;
88648   for(i=1; i<=pQTerm->nPhrase && left.nData>0; i++){
88649     /* If this token is connected to the next by a NEAR operator, and
88650     ** the next token is the start of a phrase, then set nPhraseRight
88651     ** to the number of tokens in the phrase. Otherwise leave it at 1.
88652     */
88653     int nPhraseRight = 1;
88654     while( (i+nPhraseRight)<=pQTerm->nPhrase 
88655         && pQTerm[i+nPhraseRight].nNear==0 
88656     ){
88657       nPhraseRight++;
88658     }
88659
88660     dataBufferInit(&right, 0);
88661     rc = termSelect(v, iColumn, pQTerm[i].pTerm, pQTerm[i].nTerm,
88662                     pQTerm[i].isPrefix, DL_POSITIONS, &right);
88663     if( rc ){
88664       dataBufferDestroy(&left);
88665       return rc;
88666     }
88667     dataBufferInit(&new, 0);
88668     docListPhraseMerge(left.pData, left.nData, right.pData, right.nData,
88669                        pQTerm[i-1].nNear, pQTerm[i-1].iPhrase + nPhraseRight,
88670                        ((i<pQTerm->nPhrase) ? DL_POSITIONS : DL_DOCIDS),
88671                        &new);
88672     dataBufferDestroy(&left);
88673     dataBufferDestroy(&right);
88674     left = new;
88675   }
88676   *pResult = left;
88677   return SQLITE_OK;
88678 }
88679
88680 /* Add a new term pTerm[0..nTerm-1] to the query *q.
88681 */
88682 static void queryAdd(Query *q, const char *pTerm, int nTerm){
88683   QueryTerm *t;
88684   ++q->nTerms;
88685   q->pTerms = sqlite3_realloc(q->pTerms, q->nTerms * sizeof(q->pTerms[0]));
88686   if( q->pTerms==0 ){
88687     q->nTerms = 0;
88688     return;
88689   }
88690   t = &q->pTerms[q->nTerms - 1];
88691   CLEAR(t);
88692   t->pTerm = sqlite3_malloc(nTerm+1);
88693   memcpy(t->pTerm, pTerm, nTerm);
88694   t->pTerm[nTerm] = 0;
88695   t->nTerm = nTerm;
88696   t->isOr = q->nextIsOr;
88697   t->isPrefix = 0;
88698   q->nextIsOr = 0;
88699   t->iColumn = q->nextColumn;
88700   q->nextColumn = q->dfltColumn;
88701 }
88702
88703 /*
88704 ** Check to see if the string zToken[0...nToken-1] matches any
88705 ** column name in the virtual table.   If it does,
88706 ** return the zero-indexed column number.  If not, return -1.
88707 */
88708 static int checkColumnSpecifier(
88709   fulltext_vtab *pVtab,    /* The virtual table */
88710   const char *zToken,      /* Text of the token */
88711   int nToken               /* Number of characters in the token */
88712 ){
88713   int i;
88714   for(i=0; i<pVtab->nColumn; i++){
88715     if( memcmp(pVtab->azColumn[i], zToken, nToken)==0
88716         && pVtab->azColumn[i][nToken]==0 ){
88717       return i;
88718     }
88719   }
88720   return -1;
88721 }
88722
88723 /*
88724 ** Parse the text at zSegment[0..nSegment-1].  Add additional terms
88725 ** to the query being assemblied in pQuery.
88726 **
88727 ** inPhrase is true if zSegment[0..nSegement-1] is contained within
88728 ** double-quotes.  If inPhrase is true, then the first term
88729 ** is marked with the number of terms in the phrase less one and
88730 ** OR and "-" syntax is ignored.  If inPhrase is false, then every
88731 ** term found is marked with nPhrase=0 and OR and "-" syntax is significant.
88732 */
88733 static int tokenizeSegment(
88734   sqlite3_tokenizer *pTokenizer,          /* The tokenizer to use */
88735   const char *zSegment, int nSegment,     /* Query expression being parsed */
88736   int inPhrase,                           /* True if within "..." */
88737   Query *pQuery                           /* Append results here */
88738 ){
88739   const sqlite3_tokenizer_module *pModule = pTokenizer->pModule;
88740   sqlite3_tokenizer_cursor *pCursor;
88741   int firstIndex = pQuery->nTerms;
88742   int iCol;
88743   int nTerm = 1;
88744   
88745   int rc = pModule->xOpen(pTokenizer, zSegment, nSegment, &pCursor);
88746   if( rc!=SQLITE_OK ) return rc;
88747   pCursor->pTokenizer = pTokenizer;
88748
88749   while( 1 ){
88750     const char *zToken;
88751     int nToken, iBegin, iEnd, iPos;
88752
88753     rc = pModule->xNext(pCursor,
88754                         &zToken, &nToken,
88755                         &iBegin, &iEnd, &iPos);
88756     if( rc!=SQLITE_OK ) break;
88757     if( !inPhrase &&
88758         zSegment[iEnd]==':' &&
88759          (iCol = checkColumnSpecifier(pQuery->pFts, zToken, nToken))>=0 ){
88760       pQuery->nextColumn = iCol;
88761       continue;
88762     }
88763     if( !inPhrase && pQuery->nTerms>0 && nToken==2 
88764      && zSegment[iBegin+0]=='O'
88765      && zSegment[iBegin+1]=='R' 
88766     ){
88767       pQuery->nextIsOr = 1;
88768       continue;
88769     }
88770     if( !inPhrase && pQuery->nTerms>0 && !pQuery->nextIsOr && nToken==4 
88771       && memcmp(&zSegment[iBegin], "NEAR", 4)==0
88772     ){
88773       QueryTerm *pTerm = &pQuery->pTerms[pQuery->nTerms-1];
88774       if( (iBegin+6)<nSegment 
88775        && zSegment[iBegin+4] == '/'
88776        && isdigit(zSegment[iBegin+5])
88777       ){
88778         int k;
88779         pTerm->nNear = 0;
88780         for(k=5; (iBegin+k)<=nSegment && isdigit(zSegment[iBegin+k]); k++){
88781           pTerm->nNear = pTerm->nNear*10 + (zSegment[iBegin+k] - '0');
88782         }
88783         pModule->xNext(pCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
88784       } else {
88785         pTerm->nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
88786       }
88787       pTerm->nNear++;
88788       continue;
88789     }
88790
88791     queryAdd(pQuery, zToken, nToken);
88792     if( !inPhrase && iBegin>0 && zSegment[iBegin-1]=='-' ){
88793       pQuery->pTerms[pQuery->nTerms-1].isNot = 1;
88794     }
88795     if( iEnd<nSegment && zSegment[iEnd]=='*' ){
88796       pQuery->pTerms[pQuery->nTerms-1].isPrefix = 1;
88797     }
88798     pQuery->pTerms[pQuery->nTerms-1].iPhrase = nTerm;
88799     if( inPhrase ){
88800       nTerm++;
88801     }
88802   }
88803
88804   if( inPhrase && pQuery->nTerms>firstIndex ){
88805     pQuery->pTerms[firstIndex].nPhrase = pQuery->nTerms - firstIndex - 1;
88806   }
88807
88808   return pModule->xClose(pCursor);
88809 }
88810
88811 /* Parse a query string, yielding a Query object pQuery.
88812 **
88813 ** The calling function will need to queryClear() to clean up
88814 ** the dynamically allocated memory held by pQuery.
88815 */
88816 static int parseQuery(
88817   fulltext_vtab *v,        /* The fulltext index */
88818   const char *zInput,      /* Input text of the query string */
88819   int nInput,              /* Size of the input text */
88820   int dfltColumn,          /* Default column of the index to match against */
88821   Query *pQuery            /* Write the parse results here. */
88822 ){
88823   int iInput, inPhrase = 0;
88824   int ii;
88825   QueryTerm *aTerm;
88826
88827   if( zInput==0 ) nInput = 0;
88828   if( nInput<0 ) nInput = strlen(zInput);
88829   pQuery->nTerms = 0;
88830   pQuery->pTerms = NULL;
88831   pQuery->nextIsOr = 0;
88832   pQuery->nextColumn = dfltColumn;
88833   pQuery->dfltColumn = dfltColumn;
88834   pQuery->pFts = v;
88835
88836   for(iInput=0; iInput<nInput; ++iInput){
88837     int i;
88838     for(i=iInput; i<nInput && zInput[i]!='"'; ++i){}
88839     if( i>iInput ){
88840       tokenizeSegment(v->pTokenizer, zInput+iInput, i-iInput, inPhrase,
88841                        pQuery);
88842     }
88843     iInput = i;
88844     if( i<nInput ){
88845       assert( zInput[i]=='"' );
88846       inPhrase = !inPhrase;
88847     }
88848   }
88849
88850   if( inPhrase ){
88851     /* unmatched quote */
88852     queryClear(pQuery);
88853     return SQLITE_ERROR;
88854   }
88855
88856   /* Modify the values of the QueryTerm.nPhrase variables to account for
88857   ** the NEAR operator. For the purposes of QueryTerm.nPhrase, phrases
88858   ** and tokens connected by the NEAR operator are handled as a single
88859   ** phrase. See comments above the QueryTerm structure for details.
88860   */
88861   aTerm = pQuery->pTerms;
88862   for(ii=0; ii<pQuery->nTerms; ii++){
88863     if( aTerm[ii].nNear || aTerm[ii].nPhrase ){
88864       while (aTerm[ii+aTerm[ii].nPhrase].nNear) {
88865         aTerm[ii].nPhrase += (1 + aTerm[ii+aTerm[ii].nPhrase+1].nPhrase);
88866       }
88867     }
88868   }
88869
88870   return SQLITE_OK;
88871 }
88872
88873 /* TODO(shess) Refactor the code to remove this forward decl. */
88874 static int flushPendingTerms(fulltext_vtab *v);
88875
88876 /* Perform a full-text query using the search expression in
88877 ** zInput[0..nInput-1].  Return a list of matching documents
88878 ** in pResult.
88879 **
88880 ** Queries must match column iColumn.  Or if iColumn>=nColumn
88881 ** they are allowed to match against any column.
88882 */
88883 static int fulltextQuery(
88884   fulltext_vtab *v,      /* The full text index */
88885   int iColumn,           /* Match against this column by default */
88886   const char *zInput,    /* The query string */
88887   int nInput,            /* Number of bytes in zInput[] */
88888   DataBuffer *pResult,   /* Write the result doclist here */
88889   Query *pQuery          /* Put parsed query string here */
88890 ){
88891   int i, iNext, rc;
88892   DataBuffer left, right, or, new;
88893   int nNot = 0;
88894   QueryTerm *aTerm;
88895
88896   /* TODO(shess) Instead of flushing pendingTerms, we could query for
88897   ** the relevant term and merge the doclist into what we receive from
88898   ** the database.  Wait and see if this is a common issue, first.
88899   **
88900   ** A good reason not to flush is to not generate update-related
88901   ** error codes from here.
88902   */
88903
88904   /* Flush any buffered updates before executing the query. */
88905   rc = flushPendingTerms(v);
88906   if( rc!=SQLITE_OK ) return rc;
88907
88908   /* TODO(shess) I think that the queryClear() calls below are not
88909   ** necessary, because fulltextClose() already clears the query.
88910   */
88911   rc = parseQuery(v, zInput, nInput, iColumn, pQuery);
88912   if( rc!=SQLITE_OK ) return rc;
88913
88914   /* Empty or NULL queries return no results. */
88915   if( pQuery->nTerms==0 ){
88916     dataBufferInit(pResult, 0);
88917     return SQLITE_OK;
88918   }
88919
88920   /* Merge AND terms. */
88921   /* TODO(shess) I think we can early-exit if( i>nNot && left.nData==0 ). */
88922   aTerm = pQuery->pTerms;
88923   for(i = 0; i<pQuery->nTerms; i=iNext){
88924     if( aTerm[i].isNot ){
88925       /* Handle all NOT terms in a separate pass */
88926       nNot++;
88927       iNext = i + aTerm[i].nPhrase+1;
88928       continue;
88929     }
88930     iNext = i + aTerm[i].nPhrase + 1;
88931     rc = docListOfTerm(v, aTerm[i].iColumn, &aTerm[i], &right);
88932     if( rc ){
88933       if( i!=nNot ) dataBufferDestroy(&left);
88934       queryClear(pQuery);
88935       return rc;
88936     }
88937     while( iNext<pQuery->nTerms && aTerm[iNext].isOr ){
88938       rc = docListOfTerm(v, aTerm[iNext].iColumn, &aTerm[iNext], &or);
88939       iNext += aTerm[iNext].nPhrase + 1;
88940       if( rc ){
88941         if( i!=nNot ) dataBufferDestroy(&left);
88942         dataBufferDestroy(&right);
88943         queryClear(pQuery);
88944         return rc;
88945       }
88946       dataBufferInit(&new, 0);
88947       docListOrMerge(right.pData, right.nData, or.pData, or.nData, &new);
88948       dataBufferDestroy(&right);
88949       dataBufferDestroy(&or);
88950       right = new;
88951     }
88952     if( i==nNot ){           /* first term processed. */
88953       left = right;
88954     }else{
88955       dataBufferInit(&new, 0);
88956       docListAndMerge(left.pData, left.nData, right.pData, right.nData, &new);
88957       dataBufferDestroy(&right);
88958       dataBufferDestroy(&left);
88959       left = new;
88960     }
88961   }
88962
88963   if( nNot==pQuery->nTerms ){
88964     /* We do not yet know how to handle a query of only NOT terms */
88965     return SQLITE_ERROR;
88966   }
88967
88968   /* Do the EXCEPT terms */
88969   for(i=0; i<pQuery->nTerms;  i += aTerm[i].nPhrase + 1){
88970     if( !aTerm[i].isNot ) continue;
88971     rc = docListOfTerm(v, aTerm[i].iColumn, &aTerm[i], &right);
88972     if( rc ){
88973       queryClear(pQuery);
88974       dataBufferDestroy(&left);
88975       return rc;
88976     }
88977     dataBufferInit(&new, 0);
88978     docListExceptMerge(left.pData, left.nData, right.pData, right.nData, &new);
88979     dataBufferDestroy(&right);
88980     dataBufferDestroy(&left);
88981     left = new;
88982   }
88983
88984   *pResult = left;
88985   return rc;
88986 }
88987
88988 /*
88989 ** This is the xFilter interface for the virtual table.  See
88990 ** the virtual table xFilter method documentation for additional
88991 ** information.
88992 **
88993 ** If idxNum==QUERY_GENERIC then do a full table scan against
88994 ** the %_content table.
88995 **
88996 ** If idxNum==QUERY_DOCID then do a docid lookup for a single entry
88997 ** in the %_content table.
88998 **
88999 ** If idxNum>=QUERY_FULLTEXT then use the full text index.  The
89000 ** column on the left-hand side of the MATCH operator is column
89001 ** number idxNum-QUERY_FULLTEXT, 0 indexed.  argv[0] is the right-hand
89002 ** side of the MATCH operator.
89003 */
89004 /* TODO(shess) Upgrade the cursor initialization and destruction to
89005 ** account for fulltextFilter() being called multiple times on the
89006 ** same cursor.  The current solution is very fragile.  Apply fix to
89007 ** fts3 as appropriate.
89008 */
89009 static int fulltextFilter(
89010   sqlite3_vtab_cursor *pCursor,     /* The cursor used for this query */
89011   int idxNum, const char *idxStr,   /* Which indexing scheme to use */
89012   int argc, sqlite3_value **argv    /* Arguments for the indexing scheme */
89013 ){
89014   fulltext_cursor *c = (fulltext_cursor *) pCursor;
89015   fulltext_vtab *v = cursor_vtab(c);
89016   int rc;
89017
89018   FTSTRACE(("FTS3 Filter %p\n",pCursor));
89019
89020   /* If the cursor has a statement that was not prepared according to
89021   ** idxNum, clear it.  I believe all calls to fulltextFilter with a
89022   ** given cursor will have the same idxNum , but in this case it's
89023   ** easy to be safe.
89024   */
89025   if( c->pStmt && c->iCursorType!=idxNum ){
89026     sqlite3_finalize(c->pStmt);
89027     c->pStmt = NULL;
89028   }
89029
89030   /* Get a fresh statement appropriate to idxNum. */
89031   /* TODO(shess): Add a prepared-statement cache in the vt structure.
89032   ** The cache must handle multiple open cursors.  Easier to cache the
89033   ** statement variants at the vt to reduce malloc/realloc/free here.
89034   ** Or we could have a StringBuffer variant which allowed stack
89035   ** construction for small values.
89036   */
89037   if( !c->pStmt ){
89038     StringBuffer sb;
89039     initStringBuffer(&sb);
89040     append(&sb, "SELECT docid, ");
89041     appendList(&sb, v->nColumn, v->azContentColumn);
89042     append(&sb, " FROM %_content");
89043     if( idxNum!=QUERY_GENERIC ) append(&sb, " WHERE docid = ?");
89044     rc = sql_prepare(v->db, v->zDb, v->zName, &c->pStmt,
89045                      stringBufferData(&sb));
89046     stringBufferDestroy(&sb);
89047     if( rc!=SQLITE_OK ) return rc;
89048     c->iCursorType = idxNum;
89049   }else{
89050     sqlite3_reset(c->pStmt);
89051     assert( c->iCursorType==idxNum );
89052   }
89053
89054   switch( idxNum ){
89055     case QUERY_GENERIC:
89056       break;
89057
89058     case QUERY_DOCID:
89059       rc = sqlite3_bind_int64(c->pStmt, 1, sqlite3_value_int64(argv[0]));
89060       if( rc!=SQLITE_OK ) return rc;
89061       break;
89062
89063     default:   /* full-text search */
89064     {
89065       const char *zQuery = (const char *)sqlite3_value_text(argv[0]);
89066       assert( idxNum<=QUERY_FULLTEXT+v->nColumn);
89067       assert( argc==1 );
89068       queryClear(&c->q);
89069       if( c->result.nData!=0 ){
89070         /* This case happens if the same cursor is used repeatedly. */
89071         dlrDestroy(&c->reader);
89072         dataBufferReset(&c->result);
89073       }else{
89074         dataBufferInit(&c->result, 0);
89075       }
89076       rc = fulltextQuery(v, idxNum-QUERY_FULLTEXT, zQuery, -1, &c->result, &c->q);
89077       if( rc!=SQLITE_OK ) return rc;
89078       if( c->result.nData!=0 ){
89079         dlrInit(&c->reader, DL_DOCIDS, c->result.pData, c->result.nData);
89080       }
89081       break;
89082     }
89083   }
89084
89085   return fulltextNext(pCursor);
89086 }
89087
89088 /* This is the xEof method of the virtual table.  The SQLite core
89089 ** calls this routine to find out if it has reached the end of
89090 ** a query's results set.
89091 */
89092 static int fulltextEof(sqlite3_vtab_cursor *pCursor){
89093   fulltext_cursor *c = (fulltext_cursor *) pCursor;
89094   return c->eof;
89095 }
89096
89097 /* This is the xColumn method of the virtual table.  The SQLite
89098 ** core calls this method during a query when it needs the value
89099 ** of a column from the virtual table.  This method needs to use
89100 ** one of the sqlite3_result_*() routines to store the requested
89101 ** value back in the pContext.
89102 */
89103 static int fulltextColumn(sqlite3_vtab_cursor *pCursor,
89104                           sqlite3_context *pContext, int idxCol){
89105   fulltext_cursor *c = (fulltext_cursor *) pCursor;
89106   fulltext_vtab *v = cursor_vtab(c);
89107
89108   if( idxCol<v->nColumn ){
89109     sqlite3_value *pVal = sqlite3_column_value(c->pStmt, idxCol+1);
89110     sqlite3_result_value(pContext, pVal);
89111   }else if( idxCol==v->nColumn ){
89112     /* The extra column whose name is the same as the table.
89113     ** Return a blob which is a pointer to the cursor
89114     */
89115     sqlite3_result_blob(pContext, &c, sizeof(c), SQLITE_TRANSIENT);
89116   }else if( idxCol==v->nColumn+1 ){
89117     /* The docid column, which is an alias for rowid. */
89118     sqlite3_value *pVal = sqlite3_column_value(c->pStmt, 0);
89119     sqlite3_result_value(pContext, pVal);
89120   }
89121   return SQLITE_OK;
89122 }
89123
89124 /* This is the xRowid method.  The SQLite core calls this routine to
89125 ** retrieve the rowid for the current row of the result set.  fts3
89126 ** exposes %_content.docid as the rowid for the virtual table.  The
89127 ** rowid should be written to *pRowid.
89128 */
89129 static int fulltextRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
89130   fulltext_cursor *c = (fulltext_cursor *) pCursor;
89131
89132   *pRowid = sqlite3_column_int64(c->pStmt, 0);
89133   return SQLITE_OK;
89134 }
89135
89136 /* Add all terms in [zText] to pendingTerms table.  If [iColumn] > 0,
89137 ** we also store positions and offsets in the hash table using that
89138 ** column number.
89139 */
89140 static int buildTerms(fulltext_vtab *v, sqlite_int64 iDocid,
89141                       const char *zText, int iColumn){
89142   sqlite3_tokenizer *pTokenizer = v->pTokenizer;
89143   sqlite3_tokenizer_cursor *pCursor;
89144   const char *pToken;
89145   int nTokenBytes;
89146   int iStartOffset, iEndOffset, iPosition;
89147   int rc;
89148
89149   rc = pTokenizer->pModule->xOpen(pTokenizer, zText, -1, &pCursor);
89150   if( rc!=SQLITE_OK ) return rc;
89151
89152   pCursor->pTokenizer = pTokenizer;
89153   while( SQLITE_OK==(rc=pTokenizer->pModule->xNext(pCursor,
89154                                                    &pToken, &nTokenBytes,
89155                                                    &iStartOffset, &iEndOffset,
89156                                                    &iPosition)) ){
89157     DLCollector *p;
89158     int nData;                   /* Size of doclist before our update. */
89159
89160     /* Positions can't be negative; we use -1 as a terminator
89161      * internally.  Token can't be NULL or empty. */
89162     if( iPosition<0 || pToken == NULL || nTokenBytes == 0 ){
89163       rc = SQLITE_ERROR;
89164       break;
89165     }
89166
89167     p = fts3HashFind(&v->pendingTerms, pToken, nTokenBytes);
89168     if( p==NULL ){
89169       nData = 0;
89170       p = dlcNew(iDocid, DL_DEFAULT);
89171       fts3HashInsert(&v->pendingTerms, pToken, nTokenBytes, p);
89172
89173       /* Overhead for our hash table entry, the key, and the value. */
89174       v->nPendingData += sizeof(struct fts3HashElem)+sizeof(*p)+nTokenBytes;
89175     }else{
89176       nData = p->b.nData;
89177       if( p->dlw.iPrevDocid!=iDocid ) dlcNext(p, iDocid);
89178     }
89179     if( iColumn>=0 ){
89180       dlcAddPos(p, iColumn, iPosition, iStartOffset, iEndOffset);
89181     }
89182
89183     /* Accumulate data added by dlcNew or dlcNext, and dlcAddPos. */
89184     v->nPendingData += p->b.nData-nData;
89185   }
89186
89187   /* TODO(shess) Check return?  Should this be able to cause errors at
89188   ** this point?  Actually, same question about sqlite3_finalize(),
89189   ** though one could argue that failure there means that the data is
89190   ** not durable.  *ponder*
89191   */
89192   pTokenizer->pModule->xClose(pCursor);
89193   if( SQLITE_DONE == rc ) return SQLITE_OK;
89194   return rc;
89195 }
89196
89197 /* Add doclists for all terms in [pValues] to pendingTerms table. */
89198 static int insertTerms(fulltext_vtab *v, sqlite_int64 iDocid,
89199                        sqlite3_value **pValues){
89200   int i;
89201   for(i = 0; i < v->nColumn ; ++i){
89202     char *zText = (char*)sqlite3_value_text(pValues[i]);
89203     int rc = buildTerms(v, iDocid, zText, i);
89204     if( rc!=SQLITE_OK ) return rc;
89205   }
89206   return SQLITE_OK;
89207 }
89208
89209 /* Add empty doclists for all terms in the given row's content to
89210 ** pendingTerms.
89211 */
89212 static int deleteTerms(fulltext_vtab *v, sqlite_int64 iDocid){
89213   const char **pValues;
89214   int i, rc;
89215
89216   /* TODO(shess) Should we allow such tables at all? */
89217   if( DL_DEFAULT==DL_DOCIDS ) return SQLITE_ERROR;
89218
89219   rc = content_select(v, iDocid, &pValues);
89220   if( rc!=SQLITE_OK ) return rc;
89221
89222   for(i = 0 ; i < v->nColumn; ++i) {
89223     rc = buildTerms(v, iDocid, pValues[i], -1);
89224     if( rc!=SQLITE_OK ) break;
89225   }
89226
89227   freeStringArray(v->nColumn, pValues);
89228   return SQLITE_OK;
89229 }
89230
89231 /* TODO(shess) Refactor the code to remove this forward decl. */
89232 static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid);
89233
89234 /* Insert a row into the %_content table; set *piDocid to be the ID of the
89235 ** new row.  Add doclists for terms to pendingTerms.
89236 */
89237 static int index_insert(fulltext_vtab *v, sqlite3_value *pRequestDocid,
89238                         sqlite3_value **pValues, sqlite_int64 *piDocid){
89239   int rc;
89240
89241   rc = content_insert(v, pRequestDocid, pValues);  /* execute an SQL INSERT */
89242   if( rc!=SQLITE_OK ) return rc;
89243
89244   /* docid column is an alias for rowid. */
89245   *piDocid = sqlite3_last_insert_rowid(v->db);
89246   rc = initPendingTerms(v, *piDocid);
89247   if( rc!=SQLITE_OK ) return rc;
89248
89249   return insertTerms(v, *piDocid, pValues);
89250 }
89251
89252 /* Delete a row from the %_content table; add empty doclists for terms
89253 ** to pendingTerms.
89254 */
89255 static int index_delete(fulltext_vtab *v, sqlite_int64 iRow){
89256   int rc = initPendingTerms(v, iRow);
89257   if( rc!=SQLITE_OK ) return rc;
89258
89259   rc = deleteTerms(v, iRow);
89260   if( rc!=SQLITE_OK ) return rc;
89261
89262   return content_delete(v, iRow);  /* execute an SQL DELETE */
89263 }
89264
89265 /* Update a row in the %_content table; add delete doclists to
89266 ** pendingTerms for old terms not in the new data, add insert doclists
89267 ** to pendingTerms for terms in the new data.
89268 */
89269 static int index_update(fulltext_vtab *v, sqlite_int64 iRow,
89270                         sqlite3_value **pValues){
89271   int rc = initPendingTerms(v, iRow);
89272   if( rc!=SQLITE_OK ) return rc;
89273
89274   /* Generate an empty doclist for each term that previously appeared in this
89275    * row. */
89276   rc = deleteTerms(v, iRow);
89277   if( rc!=SQLITE_OK ) return rc;
89278
89279   rc = content_update(v, pValues, iRow);  /* execute an SQL UPDATE */
89280   if( rc!=SQLITE_OK ) return rc;
89281
89282   /* Now add positions for terms which appear in the updated row. */
89283   return insertTerms(v, iRow, pValues);
89284 }
89285
89286 /*******************************************************************/
89287 /* InteriorWriter is used to collect terms and block references into
89288 ** interior nodes in %_segments.  See commentary at top of file for
89289 ** format.
89290 */
89291
89292 /* How large interior nodes can grow. */
89293 #define INTERIOR_MAX 2048
89294
89295 /* Minimum number of terms per interior node (except the root). This
89296 ** prevents large terms from making the tree too skinny - must be >0
89297 ** so that the tree always makes progress.  Note that the min tree
89298 ** fanout will be INTERIOR_MIN_TERMS+1.
89299 */
89300 #define INTERIOR_MIN_TERMS 7
89301 #if INTERIOR_MIN_TERMS<1
89302 # error INTERIOR_MIN_TERMS must be greater than 0.
89303 #endif
89304
89305 /* ROOT_MAX controls how much data is stored inline in the segment
89306 ** directory.
89307 */
89308 /* TODO(shess) Push ROOT_MAX down to whoever is writing things.  It's
89309 ** only here so that interiorWriterRootInfo() and leafWriterRootInfo()
89310 ** can both see it, but if the caller passed it in, we wouldn't even
89311 ** need a define.
89312 */
89313 #define ROOT_MAX 1024
89314 #if ROOT_MAX<VARINT_MAX*2
89315 # error ROOT_MAX must have enough space for a header.
89316 #endif
89317
89318 /* InteriorBlock stores a linked-list of interior blocks while a lower
89319 ** layer is being constructed.
89320 */
89321 typedef struct InteriorBlock {
89322   DataBuffer term;           /* Leftmost term in block's subtree. */
89323   DataBuffer data;           /* Accumulated data for the block. */
89324   struct InteriorBlock *next;
89325 } InteriorBlock;
89326
89327 static InteriorBlock *interiorBlockNew(int iHeight, sqlite_int64 iChildBlock,
89328                                        const char *pTerm, int nTerm){
89329   InteriorBlock *block = sqlite3_malloc(sizeof(InteriorBlock));
89330   char c[VARINT_MAX+VARINT_MAX];
89331   int n;
89332
89333   if( block ){
89334     memset(block, 0, sizeof(*block));
89335     dataBufferInit(&block->term, 0);
89336     dataBufferReplace(&block->term, pTerm, nTerm);
89337
89338     n = fts3PutVarint(c, iHeight);
89339     n += fts3PutVarint(c+n, iChildBlock);
89340     dataBufferInit(&block->data, INTERIOR_MAX);
89341     dataBufferReplace(&block->data, c, n);
89342   }
89343   return block;
89344 }
89345
89346 #ifndef NDEBUG
89347 /* Verify that the data is readable as an interior node. */
89348 static void interiorBlockValidate(InteriorBlock *pBlock){
89349   const char *pData = pBlock->data.pData;
89350   int nData = pBlock->data.nData;
89351   int n, iDummy;
89352   sqlite_int64 iBlockid;
89353
89354   assert( nData>0 );
89355   assert( pData!=0 );
89356   assert( pData+nData>pData );
89357
89358   /* Must lead with height of node as a varint(n), n>0 */
89359   n = fts3GetVarint32(pData, &iDummy);
89360   assert( n>0 );
89361   assert( iDummy>0 );
89362   assert( n<nData );
89363   pData += n;
89364   nData -= n;
89365
89366   /* Must contain iBlockid. */
89367   n = fts3GetVarint(pData, &iBlockid);
89368   assert( n>0 );
89369   assert( n<=nData );
89370   pData += n;
89371   nData -= n;
89372
89373   /* Zero or more terms of positive length */
89374   if( nData!=0 ){
89375     /* First term is not delta-encoded. */
89376     n = fts3GetVarint32(pData, &iDummy);
89377     assert( n>0 );
89378     assert( iDummy>0 );
89379     assert( n+iDummy>0);
89380     assert( n+iDummy<=nData );
89381     pData += n+iDummy;
89382     nData -= n+iDummy;
89383
89384     /* Following terms delta-encoded. */
89385     while( nData!=0 ){
89386       /* Length of shared prefix. */
89387       n = fts3GetVarint32(pData, &iDummy);
89388       assert( n>0 );
89389       assert( iDummy>=0 );
89390       assert( n<nData );
89391       pData += n;
89392       nData -= n;
89393
89394       /* Length and data of distinct suffix. */
89395       n = fts3GetVarint32(pData, &iDummy);
89396       assert( n>0 );
89397       assert( iDummy>0 );
89398       assert( n+iDummy>0);
89399       assert( n+iDummy<=nData );
89400       pData += n+iDummy;
89401       nData -= n+iDummy;
89402     }
89403   }
89404 }
89405 #define ASSERT_VALID_INTERIOR_BLOCK(x) interiorBlockValidate(x)
89406 #else
89407 #define ASSERT_VALID_INTERIOR_BLOCK(x) assert( 1 )
89408 #endif
89409
89410 typedef struct InteriorWriter {
89411   int iHeight;                   /* from 0 at leaves. */
89412   InteriorBlock *first, *last;
89413   struct InteriorWriter *parentWriter;
89414
89415   DataBuffer term;               /* Last term written to block "last". */
89416   sqlite_int64 iOpeningChildBlock; /* First child block in block "last". */
89417 #ifndef NDEBUG
89418   sqlite_int64 iLastChildBlock;  /* for consistency checks. */
89419 #endif
89420 } InteriorWriter;
89421
89422 /* Initialize an interior node where pTerm[nTerm] marks the leftmost
89423 ** term in the tree.  iChildBlock is the leftmost child block at the
89424 ** next level down the tree.
89425 */
89426 static void interiorWriterInit(int iHeight, const char *pTerm, int nTerm,
89427                                sqlite_int64 iChildBlock,
89428                                InteriorWriter *pWriter){
89429   InteriorBlock *block;
89430   assert( iHeight>0 );
89431   CLEAR(pWriter);
89432
89433   pWriter->iHeight = iHeight;
89434   pWriter->iOpeningChildBlock = iChildBlock;
89435 #ifndef NDEBUG
89436   pWriter->iLastChildBlock = iChildBlock;
89437 #endif
89438   block = interiorBlockNew(iHeight, iChildBlock, pTerm, nTerm);
89439   pWriter->last = pWriter->first = block;
89440   ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
89441   dataBufferInit(&pWriter->term, 0);
89442 }
89443
89444 /* Append the child node rooted at iChildBlock to the interior node,
89445 ** with pTerm[nTerm] as the leftmost term in iChildBlock's subtree.
89446 */
89447 static void interiorWriterAppend(InteriorWriter *pWriter,
89448                                  const char *pTerm, int nTerm,
89449                                  sqlite_int64 iChildBlock){
89450   char c[VARINT_MAX+VARINT_MAX];
89451   int n, nPrefix = 0;
89452
89453   ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
89454
89455   /* The first term written into an interior node is actually
89456   ** associated with the second child added (the first child was added
89457   ** in interiorWriterInit, or in the if clause at the bottom of this
89458   ** function).  That term gets encoded straight up, with nPrefix left
89459   ** at 0.
89460   */
89461   if( pWriter->term.nData==0 ){
89462     n = fts3PutVarint(c, nTerm);
89463   }else{
89464     while( nPrefix<pWriter->term.nData &&
89465            pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){
89466       nPrefix++;
89467     }
89468
89469     n = fts3PutVarint(c, nPrefix);
89470     n += fts3PutVarint(c+n, nTerm-nPrefix);
89471   }
89472
89473 #ifndef NDEBUG
89474   pWriter->iLastChildBlock++;
89475 #endif
89476   assert( pWriter->iLastChildBlock==iChildBlock );
89477
89478   /* Overflow to a new block if the new term makes the current block
89479   ** too big, and the current block already has enough terms.
89480   */
89481   if( pWriter->last->data.nData+n+nTerm-nPrefix>INTERIOR_MAX &&
89482       iChildBlock-pWriter->iOpeningChildBlock>INTERIOR_MIN_TERMS ){
89483     pWriter->last->next = interiorBlockNew(pWriter->iHeight, iChildBlock,
89484                                            pTerm, nTerm);
89485     pWriter->last = pWriter->last->next;
89486     pWriter->iOpeningChildBlock = iChildBlock;
89487     dataBufferReset(&pWriter->term);
89488   }else{
89489     dataBufferAppend2(&pWriter->last->data, c, n,
89490                       pTerm+nPrefix, nTerm-nPrefix);
89491     dataBufferReplace(&pWriter->term, pTerm, nTerm);
89492   }
89493   ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
89494 }
89495
89496 /* Free the space used by pWriter, including the linked-list of
89497 ** InteriorBlocks, and parentWriter, if present.
89498 */
89499 static int interiorWriterDestroy(InteriorWriter *pWriter){
89500   InteriorBlock *block = pWriter->first;
89501
89502   while( block!=NULL ){
89503     InteriorBlock *b = block;
89504     block = block->next;
89505     dataBufferDestroy(&b->term);
89506     dataBufferDestroy(&b->data);
89507     sqlite3_free(b);
89508   }
89509   if( pWriter->parentWriter!=NULL ){
89510     interiorWriterDestroy(pWriter->parentWriter);
89511     sqlite3_free(pWriter->parentWriter);
89512   }
89513   dataBufferDestroy(&pWriter->term);
89514   SCRAMBLE(pWriter);
89515   return SQLITE_OK;
89516 }
89517
89518 /* If pWriter can fit entirely in ROOT_MAX, return it as the root info
89519 ** directly, leaving *piEndBlockid unchanged.  Otherwise, flush
89520 ** pWriter to %_segments, building a new layer of interior nodes, and
89521 ** recursively ask for their root into.
89522 */
89523 static int interiorWriterRootInfo(fulltext_vtab *v, InteriorWriter *pWriter,
89524                                   char **ppRootInfo, int *pnRootInfo,
89525                                   sqlite_int64 *piEndBlockid){
89526   InteriorBlock *block = pWriter->first;
89527   sqlite_int64 iBlockid = 0;
89528   int rc;
89529
89530   /* If we can fit the segment inline */
89531   if( block==pWriter->last && block->data.nData<ROOT_MAX ){
89532     *ppRootInfo = block->data.pData;
89533     *pnRootInfo = block->data.nData;
89534     return SQLITE_OK;
89535   }
89536
89537   /* Flush the first block to %_segments, and create a new level of
89538   ** interior node.
89539   */
89540   ASSERT_VALID_INTERIOR_BLOCK(block);
89541   rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid);
89542   if( rc!=SQLITE_OK ) return rc;
89543   *piEndBlockid = iBlockid;
89544
89545   pWriter->parentWriter = sqlite3_malloc(sizeof(*pWriter->parentWriter));
89546   interiorWriterInit(pWriter->iHeight+1,
89547                      block->term.pData, block->term.nData,
89548                      iBlockid, pWriter->parentWriter);
89549
89550   /* Flush additional blocks and append to the higher interior
89551   ** node.
89552   */
89553   for(block=block->next; block!=NULL; block=block->next){
89554     ASSERT_VALID_INTERIOR_BLOCK(block);
89555     rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid);
89556     if( rc!=SQLITE_OK ) return rc;
89557     *piEndBlockid = iBlockid;
89558
89559     interiorWriterAppend(pWriter->parentWriter,
89560                          block->term.pData, block->term.nData, iBlockid);
89561   }
89562
89563   /* Parent node gets the chance to be the root. */
89564   return interiorWriterRootInfo(v, pWriter->parentWriter,
89565                                 ppRootInfo, pnRootInfo, piEndBlockid);
89566 }
89567
89568 /****************************************************************/
89569 /* InteriorReader is used to read off the data from an interior node
89570 ** (see comment at top of file for the format).
89571 */
89572 typedef struct InteriorReader {
89573   const char *pData;
89574   int nData;
89575
89576   DataBuffer term;          /* previous term, for decoding term delta. */
89577
89578   sqlite_int64 iBlockid;
89579 } InteriorReader;
89580
89581 static void interiorReaderDestroy(InteriorReader *pReader){
89582   dataBufferDestroy(&pReader->term);
89583   SCRAMBLE(pReader);
89584 }
89585
89586 /* TODO(shess) The assertions are great, but what if we're in NDEBUG
89587 ** and the blob is empty or otherwise contains suspect data?
89588 */
89589 static void interiorReaderInit(const char *pData, int nData,
89590                                InteriorReader *pReader){
89591   int n, nTerm;
89592
89593   /* Require at least the leading flag byte */
89594   assert( nData>0 );
89595   assert( pData[0]!='\0' );
89596
89597   CLEAR(pReader);
89598
89599   /* Decode the base blockid, and set the cursor to the first term. */
89600   n = fts3GetVarint(pData+1, &pReader->iBlockid);
89601   assert( 1+n<=nData );
89602   pReader->pData = pData+1+n;
89603   pReader->nData = nData-(1+n);
89604
89605   /* A single-child interior node (such as when a leaf node was too
89606   ** large for the segment directory) won't have any terms.
89607   ** Otherwise, decode the first term.
89608   */
89609   if( pReader->nData==0 ){
89610     dataBufferInit(&pReader->term, 0);
89611   }else{
89612     n = fts3GetVarint32(pReader->pData, &nTerm);
89613     dataBufferInit(&pReader->term, nTerm);
89614     dataBufferReplace(&pReader->term, pReader->pData+n, nTerm);
89615     assert( n+nTerm<=pReader->nData );
89616     pReader->pData += n+nTerm;
89617     pReader->nData -= n+nTerm;
89618   }
89619 }
89620
89621 static int interiorReaderAtEnd(InteriorReader *pReader){
89622   return pReader->term.nData==0;
89623 }
89624
89625 static sqlite_int64 interiorReaderCurrentBlockid(InteriorReader *pReader){
89626   return pReader->iBlockid;
89627 }
89628
89629 static int interiorReaderTermBytes(InteriorReader *pReader){
89630   assert( !interiorReaderAtEnd(pReader) );
89631   return pReader->term.nData;
89632 }
89633 static const char *interiorReaderTerm(InteriorReader *pReader){
89634   assert( !interiorReaderAtEnd(pReader) );
89635   return pReader->term.pData;
89636 }
89637
89638 /* Step forward to the next term in the node. */
89639 static void interiorReaderStep(InteriorReader *pReader){
89640   assert( !interiorReaderAtEnd(pReader) );
89641
89642   /* If the last term has been read, signal eof, else construct the
89643   ** next term.
89644   */
89645   if( pReader->nData==0 ){
89646     dataBufferReset(&pReader->term);
89647   }else{
89648     int n, nPrefix, nSuffix;
89649
89650     n = fts3GetVarint32(pReader->pData, &nPrefix);
89651     n += fts3GetVarint32(pReader->pData+n, &nSuffix);
89652
89653     /* Truncate the current term and append suffix data. */
89654     pReader->term.nData = nPrefix;
89655     dataBufferAppend(&pReader->term, pReader->pData+n, nSuffix);
89656
89657     assert( n+nSuffix<=pReader->nData );
89658     pReader->pData += n+nSuffix;
89659     pReader->nData -= n+nSuffix;
89660   }
89661   pReader->iBlockid++;
89662 }
89663
89664 /* Compare the current term to pTerm[nTerm], returning strcmp-style
89665 ** results.  If isPrefix, equality means equal through nTerm bytes.
89666 */
89667 static int interiorReaderTermCmp(InteriorReader *pReader,
89668                                  const char *pTerm, int nTerm, int isPrefix){
89669   const char *pReaderTerm = interiorReaderTerm(pReader);
89670   int nReaderTerm = interiorReaderTermBytes(pReader);
89671   int c, n = nReaderTerm<nTerm ? nReaderTerm : nTerm;
89672
89673   if( n==0 ){
89674     if( nReaderTerm>0 ) return -1;
89675     if( nTerm>0 ) return 1;
89676     return 0;
89677   }
89678
89679   c = memcmp(pReaderTerm, pTerm, n);
89680   if( c!=0 ) return c;
89681   if( isPrefix && n==nTerm ) return 0;
89682   return nReaderTerm - nTerm;
89683 }
89684
89685 /****************************************************************/
89686 /* LeafWriter is used to collect terms and associated doclist data
89687 ** into leaf blocks in %_segments (see top of file for format info).
89688 ** Expected usage is:
89689 **
89690 ** LeafWriter writer;
89691 ** leafWriterInit(0, 0, &writer);
89692 ** while( sorted_terms_left_to_process ){
89693 **   // data is doclist data for that term.
89694 **   rc = leafWriterStep(v, &writer, pTerm, nTerm, pData, nData);
89695 **   if( rc!=SQLITE_OK ) goto err;
89696 ** }
89697 ** rc = leafWriterFinalize(v, &writer);
89698 **err:
89699 ** leafWriterDestroy(&writer);
89700 ** return rc;
89701 **
89702 ** leafWriterStep() may write a collected leaf out to %_segments.
89703 ** leafWriterFinalize() finishes writing any buffered data and stores
89704 ** a root node in %_segdir.  leafWriterDestroy() frees all buffers and
89705 ** InteriorWriters allocated as part of writing this segment.
89706 **
89707 ** TODO(shess) Document leafWriterStepMerge().
89708 */
89709
89710 /* Put terms with data this big in their own block. */
89711 #define STANDALONE_MIN 1024
89712
89713 /* Keep leaf blocks below this size. */
89714 #define LEAF_MAX 2048
89715
89716 typedef struct LeafWriter {
89717   int iLevel;
89718   int idx;
89719   sqlite_int64 iStartBlockid;     /* needed to create the root info */
89720   sqlite_int64 iEndBlockid;       /* when we're done writing. */
89721
89722   DataBuffer term;                /* previous encoded term */
89723   DataBuffer data;                /* encoding buffer */
89724
89725   /* bytes of first term in the current node which distinguishes that
89726   ** term from the last term of the previous node.
89727   */
89728   int nTermDistinct;
89729
89730   InteriorWriter parentWriter;    /* if we overflow */
89731   int has_parent;
89732 } LeafWriter;
89733
89734 static void leafWriterInit(int iLevel, int idx, LeafWriter *pWriter){
89735   CLEAR(pWriter);
89736   pWriter->iLevel = iLevel;
89737   pWriter->idx = idx;
89738
89739   dataBufferInit(&pWriter->term, 32);
89740
89741   /* Start out with a reasonably sized block, though it can grow. */
89742   dataBufferInit(&pWriter->data, LEAF_MAX);
89743 }
89744
89745 #ifndef NDEBUG
89746 /* Verify that the data is readable as a leaf node. */
89747 static void leafNodeValidate(const char *pData, int nData){
89748   int n, iDummy;
89749
89750   if( nData==0 ) return;
89751   assert( nData>0 );
89752   assert( pData!=0 );
89753   assert( pData+nData>pData );
89754
89755   /* Must lead with a varint(0) */
89756   n = fts3GetVarint32(pData, &iDummy);
89757   assert( iDummy==0 );
89758   assert( n>0 );
89759   assert( n<nData );
89760   pData += n;
89761   nData -= n;
89762
89763   /* Leading term length and data must fit in buffer. */
89764   n = fts3GetVarint32(pData, &iDummy);
89765   assert( n>0 );
89766   assert( iDummy>0 );
89767   assert( n+iDummy>0 );
89768   assert( n+iDummy<nData );
89769   pData += n+iDummy;
89770   nData -= n+iDummy;
89771
89772   /* Leading term's doclist length and data must fit. */
89773   n = fts3GetVarint32(pData, &iDummy);
89774   assert( n>0 );
89775   assert( iDummy>0 );
89776   assert( n+iDummy>0 );
89777   assert( n+iDummy<=nData );
89778   ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL);
89779   pData += n+iDummy;
89780   nData -= n+iDummy;
89781
89782   /* Verify that trailing terms and doclists also are readable. */
89783   while( nData!=0 ){
89784     n = fts3GetVarint32(pData, &iDummy);
89785     assert( n>0 );
89786     assert( iDummy>=0 );
89787     assert( n<nData );
89788     pData += n;
89789     nData -= n;
89790     n = fts3GetVarint32(pData, &iDummy);
89791     assert( n>0 );
89792     assert( iDummy>0 );
89793     assert( n+iDummy>0 );
89794     assert( n+iDummy<nData );
89795     pData += n+iDummy;
89796     nData -= n+iDummy;
89797
89798     n = fts3GetVarint32(pData, &iDummy);
89799     assert( n>0 );
89800     assert( iDummy>0 );
89801     assert( n+iDummy>0 );
89802     assert( n+iDummy<=nData );
89803     ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL);
89804     pData += n+iDummy;
89805     nData -= n+iDummy;
89806   }
89807 }
89808 #define ASSERT_VALID_LEAF_NODE(p, n) leafNodeValidate(p, n)
89809 #else
89810 #define ASSERT_VALID_LEAF_NODE(p, n) assert( 1 )
89811 #endif
89812
89813 /* Flush the current leaf node to %_segments, and adding the resulting
89814 ** blockid and the starting term to the interior node which will
89815 ** contain it.
89816 */
89817 static int leafWriterInternalFlush(fulltext_vtab *v, LeafWriter *pWriter,
89818                                    int iData, int nData){
89819   sqlite_int64 iBlockid = 0;
89820   const char *pStartingTerm;
89821   int nStartingTerm, rc, n;
89822
89823   /* Must have the leading varint(0) flag, plus at least some
89824   ** valid-looking data.
89825   */
89826   assert( nData>2 );
89827   assert( iData>=0 );
89828   assert( iData+nData<=pWriter->data.nData );
89829   ASSERT_VALID_LEAF_NODE(pWriter->data.pData+iData, nData);
89830
89831   rc = block_insert(v, pWriter->data.pData+iData, nData, &iBlockid);
89832   if( rc!=SQLITE_OK ) return rc;
89833   assert( iBlockid!=0 );
89834
89835   /* Reconstruct the first term in the leaf for purposes of building
89836   ** the interior node.
89837   */
89838   n = fts3GetVarint32(pWriter->data.pData+iData+1, &nStartingTerm);
89839   pStartingTerm = pWriter->data.pData+iData+1+n;
89840   assert( pWriter->data.nData>iData+1+n+nStartingTerm );
89841   assert( pWriter->nTermDistinct>0 );
89842   assert( pWriter->nTermDistinct<=nStartingTerm );
89843   nStartingTerm = pWriter->nTermDistinct;
89844
89845   if( pWriter->has_parent ){
89846     interiorWriterAppend(&pWriter->parentWriter,
89847                          pStartingTerm, nStartingTerm, iBlockid);
89848   }else{
89849     interiorWriterInit(1, pStartingTerm, nStartingTerm, iBlockid,
89850                        &pWriter->parentWriter);
89851     pWriter->has_parent = 1;
89852   }
89853
89854   /* Track the span of this segment's leaf nodes. */
89855   if( pWriter->iEndBlockid==0 ){
89856     pWriter->iEndBlockid = pWriter->iStartBlockid = iBlockid;
89857   }else{
89858     pWriter->iEndBlockid++;
89859     assert( iBlockid==pWriter->iEndBlockid );
89860   }
89861
89862   return SQLITE_OK;
89863 }
89864 static int leafWriterFlush(fulltext_vtab *v, LeafWriter *pWriter){
89865   int rc = leafWriterInternalFlush(v, pWriter, 0, pWriter->data.nData);
89866   if( rc!=SQLITE_OK ) return rc;
89867
89868   /* Re-initialize the output buffer. */
89869   dataBufferReset(&pWriter->data);
89870
89871   return SQLITE_OK;
89872 }
89873
89874 /* Fetch the root info for the segment.  If the entire leaf fits
89875 ** within ROOT_MAX, then it will be returned directly, otherwise it
89876 ** will be flushed and the root info will be returned from the
89877 ** interior node.  *piEndBlockid is set to the blockid of the last
89878 ** interior or leaf node written to disk (0 if none are written at
89879 ** all).
89880 */
89881 static int leafWriterRootInfo(fulltext_vtab *v, LeafWriter *pWriter,
89882                               char **ppRootInfo, int *pnRootInfo,
89883                               sqlite_int64 *piEndBlockid){
89884   /* we can fit the segment entirely inline */
89885   if( !pWriter->has_parent && pWriter->data.nData<ROOT_MAX ){
89886     *ppRootInfo = pWriter->data.pData;
89887     *pnRootInfo = pWriter->data.nData;
89888     *piEndBlockid = 0;
89889     return SQLITE_OK;
89890   }
89891
89892   /* Flush remaining leaf data. */
89893   if( pWriter->data.nData>0 ){
89894     int rc = leafWriterFlush(v, pWriter);
89895     if( rc!=SQLITE_OK ) return rc;
89896   }
89897
89898   /* We must have flushed a leaf at some point. */
89899   assert( pWriter->has_parent );
89900
89901   /* Tenatively set the end leaf blockid as the end blockid.  If the
89902   ** interior node can be returned inline, this will be the final
89903   ** blockid, otherwise it will be overwritten by
89904   ** interiorWriterRootInfo().
89905   */
89906   *piEndBlockid = pWriter->iEndBlockid;
89907
89908   return interiorWriterRootInfo(v, &pWriter->parentWriter,
89909                                 ppRootInfo, pnRootInfo, piEndBlockid);
89910 }
89911
89912 /* Collect the rootInfo data and store it into the segment directory.
89913 ** This has the effect of flushing the segment's leaf data to
89914 ** %_segments, and also flushing any interior nodes to %_segments.
89915 */
89916 static int leafWriterFinalize(fulltext_vtab *v, LeafWriter *pWriter){
89917   sqlite_int64 iEndBlockid;
89918   char *pRootInfo;
89919   int rc, nRootInfo;
89920
89921   rc = leafWriterRootInfo(v, pWriter, &pRootInfo, &nRootInfo, &iEndBlockid);
89922   if( rc!=SQLITE_OK ) return rc;
89923
89924   /* Don't bother storing an entirely empty segment. */
89925   if( iEndBlockid==0 && nRootInfo==0 ) return SQLITE_OK;
89926
89927   return segdir_set(v, pWriter->iLevel, pWriter->idx,
89928                     pWriter->iStartBlockid, pWriter->iEndBlockid,
89929                     iEndBlockid, pRootInfo, nRootInfo);
89930 }
89931
89932 static void leafWriterDestroy(LeafWriter *pWriter){
89933   if( pWriter->has_parent ) interiorWriterDestroy(&pWriter->parentWriter);
89934   dataBufferDestroy(&pWriter->term);
89935   dataBufferDestroy(&pWriter->data);
89936 }
89937
89938 /* Encode a term into the leafWriter, delta-encoding as appropriate.
89939 ** Returns the length of the new term which distinguishes it from the
89940 ** previous term, which can be used to set nTermDistinct when a node
89941 ** boundary is crossed.
89942 */
89943 static int leafWriterEncodeTerm(LeafWriter *pWriter,
89944                                 const char *pTerm, int nTerm){
89945   char c[VARINT_MAX+VARINT_MAX];
89946   int n, nPrefix = 0;
89947
89948   assert( nTerm>0 );
89949   while( nPrefix<pWriter->term.nData &&
89950          pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){
89951     nPrefix++;
89952     /* Failing this implies that the terms weren't in order. */
89953     assert( nPrefix<nTerm );
89954   }
89955
89956   if( pWriter->data.nData==0 ){
89957     /* Encode the node header and leading term as:
89958     **  varint(0)
89959     **  varint(nTerm)
89960     **  char pTerm[nTerm]
89961     */
89962     n = fts3PutVarint(c, '\0');
89963     n += fts3PutVarint(c+n, nTerm);
89964     dataBufferAppend2(&pWriter->data, c, n, pTerm, nTerm);
89965   }else{
89966     /* Delta-encode the term as:
89967     **  varint(nPrefix)
89968     **  varint(nSuffix)
89969     **  char pTermSuffix[nSuffix]
89970     */
89971     n = fts3PutVarint(c, nPrefix);
89972     n += fts3PutVarint(c+n, nTerm-nPrefix);
89973     dataBufferAppend2(&pWriter->data, c, n, pTerm+nPrefix, nTerm-nPrefix);
89974   }
89975   dataBufferReplace(&pWriter->term, pTerm, nTerm);
89976
89977   return nPrefix+1;
89978 }
89979
89980 /* Used to avoid a memmove when a large amount of doclist data is in
89981 ** the buffer.  This constructs a node and term header before
89982 ** iDoclistData and flushes the resulting complete node using
89983 ** leafWriterInternalFlush().
89984 */
89985 static int leafWriterInlineFlush(fulltext_vtab *v, LeafWriter *pWriter,
89986                                  const char *pTerm, int nTerm,
89987                                  int iDoclistData){
89988   char c[VARINT_MAX+VARINT_MAX];
89989   int iData, n = fts3PutVarint(c, 0);
89990   n += fts3PutVarint(c+n, nTerm);
89991
89992   /* There should always be room for the header.  Even if pTerm shared
89993   ** a substantial prefix with the previous term, the entire prefix
89994   ** could be constructed from earlier data in the doclist, so there
89995   ** should be room.
89996   */
89997   assert( iDoclistData>=n+nTerm );
89998
89999   iData = iDoclistData-(n+nTerm);
90000   memcpy(pWriter->data.pData+iData, c, n);
90001   memcpy(pWriter->data.pData+iData+n, pTerm, nTerm);
90002
90003   return leafWriterInternalFlush(v, pWriter, iData, pWriter->data.nData-iData);
90004 }
90005
90006 /* Push pTerm[nTerm] along with the doclist data to the leaf layer of
90007 ** %_segments.
90008 */
90009 static int leafWriterStepMerge(fulltext_vtab *v, LeafWriter *pWriter,
90010                                const char *pTerm, int nTerm,
90011                                DLReader *pReaders, int nReaders){
90012   char c[VARINT_MAX+VARINT_MAX];
90013   int iTermData = pWriter->data.nData, iDoclistData;
90014   int i, nData, n, nActualData, nActual, rc, nTermDistinct;
90015
90016   ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData);
90017   nTermDistinct = leafWriterEncodeTerm(pWriter, pTerm, nTerm);
90018
90019   /* Remember nTermDistinct if opening a new node. */
90020   if( iTermData==0 ) pWriter->nTermDistinct = nTermDistinct;
90021
90022   iDoclistData = pWriter->data.nData;
90023
90024   /* Estimate the length of the merged doclist so we can leave space
90025   ** to encode it.
90026   */
90027   for(i=0, nData=0; i<nReaders; i++){
90028     nData += dlrAllDataBytes(&pReaders[i]);
90029   }
90030   n = fts3PutVarint(c, nData);
90031   dataBufferAppend(&pWriter->data, c, n);
90032
90033   docListMerge(&pWriter->data, pReaders, nReaders);
90034   ASSERT_VALID_DOCLIST(DL_DEFAULT,
90035                        pWriter->data.pData+iDoclistData+n,
90036                        pWriter->data.nData-iDoclistData-n, NULL);
90037
90038   /* The actual amount of doclist data at this point could be smaller
90039   ** than the length we encoded.  Additionally, the space required to
90040   ** encode this length could be smaller.  For small doclists, this is
90041   ** not a big deal, we can just use memmove() to adjust things.
90042   */
90043   nActualData = pWriter->data.nData-(iDoclistData+n);
90044   nActual = fts3PutVarint(c, nActualData);
90045   assert( nActualData<=nData );
90046   assert( nActual<=n );
90047
90048   /* If the new doclist is big enough for force a standalone leaf
90049   ** node, we can immediately flush it inline without doing the
90050   ** memmove().
90051   */
90052   /* TODO(shess) This test matches leafWriterStep(), which does this
90053   ** test before it knows the cost to varint-encode the term and
90054   ** doclist lengths.  At some point, change to
90055   ** pWriter->data.nData-iTermData>STANDALONE_MIN.
90056   */
90057   if( nTerm+nActualData>STANDALONE_MIN ){
90058     /* Push leaf node from before this term. */
90059     if( iTermData>0 ){
90060       rc = leafWriterInternalFlush(v, pWriter, 0, iTermData);
90061       if( rc!=SQLITE_OK ) return rc;
90062
90063       pWriter->nTermDistinct = nTermDistinct;
90064     }
90065
90066     /* Fix the encoded doclist length. */
90067     iDoclistData += n - nActual;
90068     memcpy(pWriter->data.pData+iDoclistData, c, nActual);
90069
90070     /* Push the standalone leaf node. */
90071     rc = leafWriterInlineFlush(v, pWriter, pTerm, nTerm, iDoclistData);
90072     if( rc!=SQLITE_OK ) return rc;
90073
90074     /* Leave the node empty. */
90075     dataBufferReset(&pWriter->data);
90076
90077     return rc;
90078   }
90079
90080   /* At this point, we know that the doclist was small, so do the
90081   ** memmove if indicated.
90082   */
90083   if( nActual<n ){
90084     memmove(pWriter->data.pData+iDoclistData+nActual,
90085             pWriter->data.pData+iDoclistData+n,
90086             pWriter->data.nData-(iDoclistData+n));
90087     pWriter->data.nData -= n-nActual;
90088   }
90089
90090   /* Replace written length with actual length. */
90091   memcpy(pWriter->data.pData+iDoclistData, c, nActual);
90092
90093   /* If the node is too large, break things up. */
90094   /* TODO(shess) This test matches leafWriterStep(), which does this
90095   ** test before it knows the cost to varint-encode the term and
90096   ** doclist lengths.  At some point, change to
90097   ** pWriter->data.nData>LEAF_MAX.
90098   */
90099   if( iTermData+nTerm+nActualData>LEAF_MAX ){
90100     /* Flush out the leading data as a node */
90101     rc = leafWriterInternalFlush(v, pWriter, 0, iTermData);
90102     if( rc!=SQLITE_OK ) return rc;
90103
90104     pWriter->nTermDistinct = nTermDistinct;
90105
90106     /* Rebuild header using the current term */
90107     n = fts3PutVarint(pWriter->data.pData, 0);
90108     n += fts3PutVarint(pWriter->data.pData+n, nTerm);
90109     memcpy(pWriter->data.pData+n, pTerm, nTerm);
90110     n += nTerm;
90111
90112     /* There should always be room, because the previous encoding
90113     ** included all data necessary to construct the term.
90114     */
90115     assert( n<iDoclistData );
90116     /* So long as STANDALONE_MIN is half or less of LEAF_MAX, the
90117     ** following memcpy() is safe (as opposed to needing a memmove).
90118     */
90119     assert( 2*STANDALONE_MIN<=LEAF_MAX );
90120     assert( n+pWriter->data.nData-iDoclistData<iDoclistData );
90121     memcpy(pWriter->data.pData+n,
90122            pWriter->data.pData+iDoclistData,
90123            pWriter->data.nData-iDoclistData);
90124     pWriter->data.nData -= iDoclistData-n;
90125   }
90126   ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData);
90127
90128   return SQLITE_OK;
90129 }
90130
90131 /* Push pTerm[nTerm] along with the doclist data to the leaf layer of
90132 ** %_segments.
90133 */
90134 /* TODO(shess) Revise writeZeroSegment() so that doclists are
90135 ** constructed directly in pWriter->data.
90136 */
90137 static int leafWriterStep(fulltext_vtab *v, LeafWriter *pWriter,
90138                           const char *pTerm, int nTerm,
90139                           const char *pData, int nData){
90140   int rc;
90141   DLReader reader;
90142
90143   dlrInit(&reader, DL_DEFAULT, pData, nData);
90144   rc = leafWriterStepMerge(v, pWriter, pTerm, nTerm, &reader, 1);
90145   dlrDestroy(&reader);
90146
90147   return rc;
90148 }
90149
90150
90151 /****************************************************************/
90152 /* LeafReader is used to iterate over an individual leaf node. */
90153 typedef struct LeafReader {
90154   DataBuffer term;          /* copy of current term. */
90155
90156   const char *pData;        /* data for current term. */
90157   int nData;
90158 } LeafReader;
90159
90160 static void leafReaderDestroy(LeafReader *pReader){
90161   dataBufferDestroy(&pReader->term);
90162   SCRAMBLE(pReader);
90163 }
90164
90165 static int leafReaderAtEnd(LeafReader *pReader){
90166   return pReader->nData<=0;
90167 }
90168
90169 /* Access the current term. */
90170 static int leafReaderTermBytes(LeafReader *pReader){
90171   return pReader->term.nData;
90172 }
90173 static const char *leafReaderTerm(LeafReader *pReader){
90174   assert( pReader->term.nData>0 );
90175   return pReader->term.pData;
90176 }
90177
90178 /* Access the doclist data for the current term. */
90179 static int leafReaderDataBytes(LeafReader *pReader){
90180   int nData;
90181   assert( pReader->term.nData>0 );
90182   fts3GetVarint32(pReader->pData, &nData);
90183   return nData;
90184 }
90185 static const char *leafReaderData(LeafReader *pReader){
90186   int n, nData;
90187   assert( pReader->term.nData>0 );
90188   n = fts3GetVarint32(pReader->pData, &nData);
90189   return pReader->pData+n;
90190 }
90191
90192 static void leafReaderInit(const char *pData, int nData,
90193                            LeafReader *pReader){
90194   int nTerm, n;
90195
90196   assert( nData>0 );
90197   assert( pData[0]=='\0' );
90198
90199   CLEAR(pReader);
90200
90201   /* Read the first term, skipping the header byte. */
90202   n = fts3GetVarint32(pData+1, &nTerm);
90203   dataBufferInit(&pReader->term, nTerm);
90204   dataBufferReplace(&pReader->term, pData+1+n, nTerm);
90205
90206   /* Position after the first term. */
90207   assert( 1+n+nTerm<nData );
90208   pReader->pData = pData+1+n+nTerm;
90209   pReader->nData = nData-1-n-nTerm;
90210 }
90211
90212 /* Step the reader forward to the next term. */
90213 static void leafReaderStep(LeafReader *pReader){
90214   int n, nData, nPrefix, nSuffix;
90215   assert( !leafReaderAtEnd(pReader) );
90216
90217   /* Skip previous entry's data block. */
90218   n = fts3GetVarint32(pReader->pData, &nData);
90219   assert( n+nData<=pReader->nData );
90220   pReader->pData += n+nData;
90221   pReader->nData -= n+nData;
90222
90223   if( !leafReaderAtEnd(pReader) ){
90224     /* Construct the new term using a prefix from the old term plus a
90225     ** suffix from the leaf data.
90226     */
90227     n = fts3GetVarint32(pReader->pData, &nPrefix);
90228     n += fts3GetVarint32(pReader->pData+n, &nSuffix);
90229     assert( n+nSuffix<pReader->nData );
90230     pReader->term.nData = nPrefix;
90231     dataBufferAppend(&pReader->term, pReader->pData+n, nSuffix);
90232
90233     pReader->pData += n+nSuffix;
90234     pReader->nData -= n+nSuffix;
90235   }
90236 }
90237
90238 /* strcmp-style comparison of pReader's current term against pTerm.
90239 ** If isPrefix, equality means equal through nTerm bytes.
90240 */
90241 static int leafReaderTermCmp(LeafReader *pReader,
90242                              const char *pTerm, int nTerm, int isPrefix){
90243   int c, n = pReader->term.nData<nTerm ? pReader->term.nData : nTerm;
90244   if( n==0 ){
90245     if( pReader->term.nData>0 ) return -1;
90246     if(nTerm>0 ) return 1;
90247     return 0;
90248   }
90249
90250   c = memcmp(pReader->term.pData, pTerm, n);
90251   if( c!=0 ) return c;
90252   if( isPrefix && n==nTerm ) return 0;
90253   return pReader->term.nData - nTerm;
90254 }
90255
90256
90257 /****************************************************************/
90258 /* LeavesReader wraps LeafReader to allow iterating over the entire
90259 ** leaf layer of the tree.
90260 */
90261 typedef struct LeavesReader {
90262   int idx;                  /* Index within the segment. */
90263
90264   sqlite3_stmt *pStmt;      /* Statement we're streaming leaves from. */
90265   int eof;                  /* we've seen SQLITE_DONE from pStmt. */
90266
90267   LeafReader leafReader;    /* reader for the current leaf. */
90268   DataBuffer rootData;      /* root data for inline. */
90269 } LeavesReader;
90270
90271 /* Access the current term. */
90272 static int leavesReaderTermBytes(LeavesReader *pReader){
90273   assert( !pReader->eof );
90274   return leafReaderTermBytes(&pReader->leafReader);
90275 }
90276 static const char *leavesReaderTerm(LeavesReader *pReader){
90277   assert( !pReader->eof );
90278   return leafReaderTerm(&pReader->leafReader);
90279 }
90280
90281 /* Access the doclist data for the current term. */
90282 static int leavesReaderDataBytes(LeavesReader *pReader){
90283   assert( !pReader->eof );
90284   return leafReaderDataBytes(&pReader->leafReader);
90285 }
90286 static const char *leavesReaderData(LeavesReader *pReader){
90287   assert( !pReader->eof );
90288   return leafReaderData(&pReader->leafReader);
90289 }
90290
90291 static int leavesReaderAtEnd(LeavesReader *pReader){
90292   return pReader->eof;
90293 }
90294
90295 /* loadSegmentLeaves() may not read all the way to SQLITE_DONE, thus
90296 ** leaving the statement handle open, which locks the table.
90297 */
90298 /* TODO(shess) This "solution" is not satisfactory.  Really, there
90299 ** should be check-in function for all statement handles which
90300 ** arranges to call sqlite3_reset().  This most likely will require
90301 ** modification to control flow all over the place, though, so for now
90302 ** just punt.
90303 **
90304 ** Note the the current system assumes that segment merges will run to
90305 ** completion, which is why this particular probably hasn't arisen in
90306 ** this case.  Probably a brittle assumption.
90307 */
90308 static int leavesReaderReset(LeavesReader *pReader){
90309   return sqlite3_reset(pReader->pStmt);
90310 }
90311
90312 static void leavesReaderDestroy(LeavesReader *pReader){
90313   /* If idx is -1, that means we're using a non-cached statement
90314   ** handle in the optimize() case, so we need to release it.
90315   */
90316   if( pReader->pStmt!=NULL && pReader->idx==-1 ){
90317     sqlite3_finalize(pReader->pStmt);
90318   }
90319   leafReaderDestroy(&pReader->leafReader);
90320   dataBufferDestroy(&pReader->rootData);
90321   SCRAMBLE(pReader);
90322 }
90323
90324 /* Initialize pReader with the given root data (if iStartBlockid==0
90325 ** the leaf data was entirely contained in the root), or from the
90326 ** stream of blocks between iStartBlockid and iEndBlockid, inclusive.
90327 */
90328 static int leavesReaderInit(fulltext_vtab *v,
90329                             int idx,
90330                             sqlite_int64 iStartBlockid,
90331                             sqlite_int64 iEndBlockid,
90332                             const char *pRootData, int nRootData,
90333                             LeavesReader *pReader){
90334   CLEAR(pReader);
90335   pReader->idx = idx;
90336
90337   dataBufferInit(&pReader->rootData, 0);
90338   if( iStartBlockid==0 ){
90339     /* Entire leaf level fit in root data. */
90340     dataBufferReplace(&pReader->rootData, pRootData, nRootData);
90341     leafReaderInit(pReader->rootData.pData, pReader->rootData.nData,
90342                    &pReader->leafReader);
90343   }else{
90344     sqlite3_stmt *s;
90345     int rc = sql_get_leaf_statement(v, idx, &s);
90346     if( rc!=SQLITE_OK ) return rc;
90347
90348     rc = sqlite3_bind_int64(s, 1, iStartBlockid);
90349     if( rc!=SQLITE_OK ) return rc;
90350
90351     rc = sqlite3_bind_int64(s, 2, iEndBlockid);
90352     if( rc!=SQLITE_OK ) return rc;
90353
90354     rc = sqlite3_step(s);
90355     if( rc==SQLITE_DONE ){
90356       pReader->eof = 1;
90357       return SQLITE_OK;
90358     }
90359     if( rc!=SQLITE_ROW ) return rc;
90360
90361     pReader->pStmt = s;
90362     leafReaderInit(sqlite3_column_blob(pReader->pStmt, 0),
90363                    sqlite3_column_bytes(pReader->pStmt, 0),
90364                    &pReader->leafReader);
90365   }
90366   return SQLITE_OK;
90367 }
90368
90369 /* Step the current leaf forward to the next term.  If we reach the
90370 ** end of the current leaf, step forward to the next leaf block.
90371 */
90372 static int leavesReaderStep(fulltext_vtab *v, LeavesReader *pReader){
90373   assert( !leavesReaderAtEnd(pReader) );
90374   leafReaderStep(&pReader->leafReader);
90375
90376   if( leafReaderAtEnd(&pReader->leafReader) ){
90377     int rc;
90378     if( pReader->rootData.pData ){
90379       pReader->eof = 1;
90380       return SQLITE_OK;
90381     }
90382     rc = sqlite3_step(pReader->pStmt);
90383     if( rc!=SQLITE_ROW ){
90384       pReader->eof = 1;
90385       return rc==SQLITE_DONE ? SQLITE_OK : rc;
90386     }
90387     leafReaderDestroy(&pReader->leafReader);
90388     leafReaderInit(sqlite3_column_blob(pReader->pStmt, 0),
90389                    sqlite3_column_bytes(pReader->pStmt, 0),
90390                    &pReader->leafReader);
90391   }
90392   return SQLITE_OK;
90393 }
90394
90395 /* Order LeavesReaders by their term, ignoring idx.  Readers at eof
90396 ** always sort to the end.
90397 */
90398 static int leavesReaderTermCmp(LeavesReader *lr1, LeavesReader *lr2){
90399   if( leavesReaderAtEnd(lr1) ){
90400     if( leavesReaderAtEnd(lr2) ) return 0;
90401     return 1;
90402   }
90403   if( leavesReaderAtEnd(lr2) ) return -1;
90404
90405   return leafReaderTermCmp(&lr1->leafReader,
90406                            leavesReaderTerm(lr2), leavesReaderTermBytes(lr2),
90407                            0);
90408 }
90409
90410 /* Similar to leavesReaderTermCmp(), with additional ordering by idx
90411 ** so that older segments sort before newer segments.
90412 */
90413 static int leavesReaderCmp(LeavesReader *lr1, LeavesReader *lr2){
90414   int c = leavesReaderTermCmp(lr1, lr2);
90415   if( c!=0 ) return c;
90416   return lr1->idx-lr2->idx;
90417 }
90418
90419 /* Assume that pLr[1]..pLr[nLr] are sorted.  Bubble pLr[0] into its
90420 ** sorted position.
90421 */
90422 static void leavesReaderReorder(LeavesReader *pLr, int nLr){
90423   while( nLr>1 && leavesReaderCmp(pLr, pLr+1)>0 ){
90424     LeavesReader tmp = pLr[0];
90425     pLr[0] = pLr[1];
90426     pLr[1] = tmp;
90427     nLr--;
90428     pLr++;
90429   }
90430 }
90431
90432 /* Initializes pReaders with the segments from level iLevel, returning
90433 ** the number of segments in *piReaders.  Leaves pReaders in sorted
90434 ** order.
90435 */
90436 static int leavesReadersInit(fulltext_vtab *v, int iLevel,
90437                              LeavesReader *pReaders, int *piReaders){
90438   sqlite3_stmt *s;
90439   int i, rc = sql_get_statement(v, SEGDIR_SELECT_LEVEL_STMT, &s);
90440   if( rc!=SQLITE_OK ) return rc;
90441
90442   rc = sqlite3_bind_int(s, 1, iLevel);
90443   if( rc!=SQLITE_OK ) return rc;
90444
90445   i = 0;
90446   while( (rc = sqlite3_step(s))==SQLITE_ROW ){
90447     sqlite_int64 iStart = sqlite3_column_int64(s, 0);
90448     sqlite_int64 iEnd = sqlite3_column_int64(s, 1);
90449     const char *pRootData = sqlite3_column_blob(s, 2);
90450     int nRootData = sqlite3_column_bytes(s, 2);
90451
90452     assert( i<MERGE_COUNT );
90453     rc = leavesReaderInit(v, i, iStart, iEnd, pRootData, nRootData,
90454                           &pReaders[i]);
90455     if( rc!=SQLITE_OK ) break;
90456
90457     i++;
90458   }
90459   if( rc!=SQLITE_DONE ){
90460     while( i-->0 ){
90461       leavesReaderDestroy(&pReaders[i]);
90462     }
90463     return rc;
90464   }
90465
90466   *piReaders = i;
90467
90468   /* Leave our results sorted by term, then age. */
90469   while( i-- ){
90470     leavesReaderReorder(pReaders+i, *piReaders-i);
90471   }
90472   return SQLITE_OK;
90473 }
90474
90475 /* Merge doclists from pReaders[nReaders] into a single doclist, which
90476 ** is written to pWriter.  Assumes pReaders is ordered oldest to
90477 ** newest.
90478 */
90479 /* TODO(shess) Consider putting this inline in segmentMerge(). */
90480 static int leavesReadersMerge(fulltext_vtab *v,
90481                               LeavesReader *pReaders, int nReaders,
90482                               LeafWriter *pWriter){
90483   DLReader dlReaders[MERGE_COUNT];
90484   const char *pTerm = leavesReaderTerm(pReaders);
90485   int i, nTerm = leavesReaderTermBytes(pReaders);
90486
90487   assert( nReaders<=MERGE_COUNT );
90488
90489   for(i=0; i<nReaders; i++){
90490     dlrInit(&dlReaders[i], DL_DEFAULT,
90491             leavesReaderData(pReaders+i),
90492             leavesReaderDataBytes(pReaders+i));
90493   }
90494
90495   return leafWriterStepMerge(v, pWriter, pTerm, nTerm, dlReaders, nReaders);
90496 }
90497
90498 /* Forward ref due to mutual recursion with segdirNextIndex(). */
90499 static int segmentMerge(fulltext_vtab *v, int iLevel);
90500
90501 /* Put the next available index at iLevel into *pidx.  If iLevel
90502 ** already has MERGE_COUNT segments, they are merged to a higher
90503 ** level to make room.
90504 */
90505 static int segdirNextIndex(fulltext_vtab *v, int iLevel, int *pidx){
90506   int rc = segdir_max_index(v, iLevel, pidx);
90507   if( rc==SQLITE_DONE ){              /* No segments at iLevel. */
90508     *pidx = 0;
90509   }else if( rc==SQLITE_ROW ){
90510     if( *pidx==(MERGE_COUNT-1) ){
90511       rc = segmentMerge(v, iLevel);
90512       if( rc!=SQLITE_OK ) return rc;
90513       *pidx = 0;
90514     }else{
90515       (*pidx)++;
90516     }
90517   }else{
90518     return rc;
90519   }
90520   return SQLITE_OK;
90521 }
90522
90523 /* Merge MERGE_COUNT segments at iLevel into a new segment at
90524 ** iLevel+1.  If iLevel+1 is already full of segments, those will be
90525 ** merged to make room.
90526 */
90527 static int segmentMerge(fulltext_vtab *v, int iLevel){
90528   LeafWriter writer;
90529   LeavesReader lrs[MERGE_COUNT];
90530   int i, rc, idx = 0;
90531
90532   /* Determine the next available segment index at the next level,
90533   ** merging as necessary.
90534   */
90535   rc = segdirNextIndex(v, iLevel+1, &idx);
90536   if( rc!=SQLITE_OK ) return rc;
90537
90538   /* TODO(shess) This assumes that we'll always see exactly
90539   ** MERGE_COUNT segments to merge at a given level.  That will be
90540   ** broken if we allow the developer to request preemptive or
90541   ** deferred merging.
90542   */
90543   memset(&lrs, '\0', sizeof(lrs));
90544   rc = leavesReadersInit(v, iLevel, lrs, &i);
90545   if( rc!=SQLITE_OK ) return rc;
90546   assert( i==MERGE_COUNT );
90547
90548   leafWriterInit(iLevel+1, idx, &writer);
90549
90550   /* Since leavesReaderReorder() pushes readers at eof to the end,
90551   ** when the first reader is empty, all will be empty.
90552   */
90553   while( !leavesReaderAtEnd(lrs) ){
90554     /* Figure out how many readers share their next term. */
90555     for(i=1; i<MERGE_COUNT && !leavesReaderAtEnd(lrs+i); i++){
90556       if( 0!=leavesReaderTermCmp(lrs, lrs+i) ) break;
90557     }
90558
90559     rc = leavesReadersMerge(v, lrs, i, &writer);
90560     if( rc!=SQLITE_OK ) goto err;
90561
90562     /* Step forward those that were merged. */
90563     while( i-->0 ){
90564       rc = leavesReaderStep(v, lrs+i);
90565       if( rc!=SQLITE_OK ) goto err;
90566
90567       /* Reorder by term, then by age. */
90568       leavesReaderReorder(lrs+i, MERGE_COUNT-i);
90569     }
90570   }
90571
90572   for(i=0; i<MERGE_COUNT; i++){
90573     leavesReaderDestroy(&lrs[i]);
90574   }
90575
90576   rc = leafWriterFinalize(v, &writer);
90577   leafWriterDestroy(&writer);
90578   if( rc!=SQLITE_OK ) return rc;
90579
90580   /* Delete the merged segment data. */
90581   return segdir_delete(v, iLevel);
90582
90583  err:
90584   for(i=0; i<MERGE_COUNT; i++){
90585     leavesReaderDestroy(&lrs[i]);
90586   }
90587   leafWriterDestroy(&writer);
90588   return rc;
90589 }
90590
90591 /* Accumulate the union of *acc and *pData into *acc. */
90592 static void docListAccumulateUnion(DataBuffer *acc,
90593                                    const char *pData, int nData) {
90594   DataBuffer tmp = *acc;
90595   dataBufferInit(acc, tmp.nData+nData);
90596   docListUnion(tmp.pData, tmp.nData, pData, nData, acc);
90597   dataBufferDestroy(&tmp);
90598 }
90599
90600 /* TODO(shess) It might be interesting to explore different merge
90601 ** strategies, here.  For instance, since this is a sorted merge, we
90602 ** could easily merge many doclists in parallel.  With some
90603 ** comprehension of the storage format, we could merge all of the
90604 ** doclists within a leaf node directly from the leaf node's storage.
90605 ** It may be worthwhile to merge smaller doclists before larger
90606 ** doclists, since they can be traversed more quickly - but the
90607 ** results may have less overlap, making them more expensive in a
90608 ** different way.
90609 */
90610
90611 /* Scan pReader for pTerm/nTerm, and merge the term's doclist over
90612 ** *out (any doclists with duplicate docids overwrite those in *out).
90613 ** Internal function for loadSegmentLeaf().
90614 */
90615 static int loadSegmentLeavesInt(fulltext_vtab *v, LeavesReader *pReader,
90616                                 const char *pTerm, int nTerm, int isPrefix,
90617                                 DataBuffer *out){
90618   /* doclist data is accumulated into pBuffers similar to how one does
90619   ** increment in binary arithmetic.  If index 0 is empty, the data is
90620   ** stored there.  If there is data there, it is merged and the
90621   ** results carried into position 1, with further merge-and-carry
90622   ** until an empty position is found.
90623   */
90624   DataBuffer *pBuffers = NULL;
90625   int nBuffers = 0, nMaxBuffers = 0, rc;
90626
90627   assert( nTerm>0 );
90628
90629   for(rc=SQLITE_OK; rc==SQLITE_OK && !leavesReaderAtEnd(pReader);
90630       rc=leavesReaderStep(v, pReader)){
90631     /* TODO(shess) Really want leavesReaderTermCmp(), but that name is
90632     ** already taken to compare the terms of two LeavesReaders.  Think
90633     ** on a better name.  [Meanwhile, break encapsulation rather than
90634     ** use a confusing name.]
90635     */
90636     int c = leafReaderTermCmp(&pReader->leafReader, pTerm, nTerm, isPrefix);
90637     if( c>0 ) break;      /* Past any possible matches. */
90638     if( c==0 ){
90639       const char *pData = leavesReaderData(pReader);
90640       int iBuffer, nData = leavesReaderDataBytes(pReader);
90641
90642       /* Find the first empty buffer. */
90643       for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){
90644         if( 0==pBuffers[iBuffer].nData ) break;
90645       }
90646
90647       /* Out of buffers, add an empty one. */
90648       if( iBuffer==nBuffers ){
90649         if( nBuffers==nMaxBuffers ){
90650           DataBuffer *p;
90651           nMaxBuffers += 20;
90652
90653           /* Manual realloc so we can handle NULL appropriately. */
90654           p = sqlite3_malloc(nMaxBuffers*sizeof(*pBuffers));
90655           if( p==NULL ){
90656             rc = SQLITE_NOMEM;
90657             break;
90658           }
90659
90660           if( nBuffers>0 ){
90661             assert(pBuffers!=NULL);
90662             memcpy(p, pBuffers, nBuffers*sizeof(*pBuffers));
90663             sqlite3_free(pBuffers);
90664           }
90665           pBuffers = p;
90666         }
90667         dataBufferInit(&(pBuffers[nBuffers]), 0);
90668         nBuffers++;
90669       }
90670
90671       /* At this point, must have an empty at iBuffer. */
90672       assert(iBuffer<nBuffers && pBuffers[iBuffer].nData==0);
90673
90674       /* If empty was first buffer, no need for merge logic. */
90675       if( iBuffer==0 ){
90676         dataBufferReplace(&(pBuffers[0]), pData, nData);
90677       }else{
90678         /* pAcc is the empty buffer the merged data will end up in. */
90679         DataBuffer *pAcc = &(pBuffers[iBuffer]);
90680         DataBuffer *p = &(pBuffers[0]);
90681
90682         /* Handle position 0 specially to avoid need to prime pAcc
90683         ** with pData/nData.
90684         */
90685         dataBufferSwap(p, pAcc);
90686         docListAccumulateUnion(pAcc, pData, nData);
90687
90688         /* Accumulate remaining doclists into pAcc. */
90689         for(++p; p<pAcc; ++p){
90690           docListAccumulateUnion(pAcc, p->pData, p->nData);
90691
90692           /* dataBufferReset() could allow a large doclist to blow up
90693           ** our memory requirements.
90694           */
90695           if( p->nCapacity<1024 ){
90696             dataBufferReset(p);
90697           }else{
90698             dataBufferDestroy(p);
90699             dataBufferInit(p, 0);
90700           }
90701         }
90702       }
90703     }
90704   }
90705
90706   /* Union all the doclists together into *out. */
90707   /* TODO(shess) What if *out is big?  Sigh. */
90708   if( rc==SQLITE_OK && nBuffers>0 ){
90709     int iBuffer;
90710     for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){
90711       if( pBuffers[iBuffer].nData>0 ){
90712         if( out->nData==0 ){
90713           dataBufferSwap(out, &(pBuffers[iBuffer]));
90714         }else{
90715           docListAccumulateUnion(out, pBuffers[iBuffer].pData,
90716                                  pBuffers[iBuffer].nData);
90717         }
90718       }
90719     }
90720   }
90721
90722   while( nBuffers-- ){
90723     dataBufferDestroy(&(pBuffers[nBuffers]));
90724   }
90725   if( pBuffers!=NULL ) sqlite3_free(pBuffers);
90726
90727   return rc;
90728 }
90729
90730 /* Call loadSegmentLeavesInt() with pData/nData as input. */
90731 static int loadSegmentLeaf(fulltext_vtab *v, const char *pData, int nData,
90732                            const char *pTerm, int nTerm, int isPrefix,
90733                            DataBuffer *out){
90734   LeavesReader reader;
90735   int rc;
90736
90737   assert( nData>1 );
90738   assert( *pData=='\0' );
90739   rc = leavesReaderInit(v, 0, 0, 0, pData, nData, &reader);
90740   if( rc!=SQLITE_OK ) return rc;
90741
90742   rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out);
90743   leavesReaderReset(&reader);
90744   leavesReaderDestroy(&reader);
90745   return rc;
90746 }
90747
90748 /* Call loadSegmentLeavesInt() with the leaf nodes from iStartLeaf to
90749 ** iEndLeaf (inclusive) as input, and merge the resulting doclist into
90750 ** out.
90751 */
90752 static int loadSegmentLeaves(fulltext_vtab *v,
90753                              sqlite_int64 iStartLeaf, sqlite_int64 iEndLeaf,
90754                              const char *pTerm, int nTerm, int isPrefix,
90755                              DataBuffer *out){
90756   int rc;
90757   LeavesReader reader;
90758
90759   assert( iStartLeaf<=iEndLeaf );
90760   rc = leavesReaderInit(v, 0, iStartLeaf, iEndLeaf, NULL, 0, &reader);
90761   if( rc!=SQLITE_OK ) return rc;
90762
90763   rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out);
90764   leavesReaderReset(&reader);
90765   leavesReaderDestroy(&reader);
90766   return rc;
90767 }
90768
90769 /* Taking pData/nData as an interior node, find the sequence of child
90770 ** nodes which could include pTerm/nTerm/isPrefix.  Note that the
90771 ** interior node terms logically come between the blocks, so there is
90772 ** one more blockid than there are terms (that block contains terms >=
90773 ** the last interior-node term).
90774 */
90775 /* TODO(shess) The calling code may already know that the end child is
90776 ** not worth calculating, because the end may be in a later sibling
90777 ** node.  Consider whether breaking symmetry is worthwhile.  I suspect
90778 ** it is not worthwhile.
90779 */
90780 static void getChildrenContaining(const char *pData, int nData,
90781                                   const char *pTerm, int nTerm, int isPrefix,
90782                                   sqlite_int64 *piStartChild,
90783                                   sqlite_int64 *piEndChild){
90784   InteriorReader reader;
90785
90786   assert( nData>1 );
90787   assert( *pData!='\0' );
90788   interiorReaderInit(pData, nData, &reader);
90789
90790   /* Scan for the first child which could contain pTerm/nTerm. */
90791   while( !interiorReaderAtEnd(&reader) ){
90792     if( interiorReaderTermCmp(&reader, pTerm, nTerm, 0)>0 ) break;
90793     interiorReaderStep(&reader);
90794   }
90795   *piStartChild = interiorReaderCurrentBlockid(&reader);
90796
90797   /* Keep scanning to find a term greater than our term, using prefix
90798   ** comparison if indicated.  If isPrefix is false, this will be the
90799   ** same blockid as the starting block.
90800   */
90801   while( !interiorReaderAtEnd(&reader) ){
90802     if( interiorReaderTermCmp(&reader, pTerm, nTerm, isPrefix)>0 ) break;
90803     interiorReaderStep(&reader);
90804   }
90805   *piEndChild = interiorReaderCurrentBlockid(&reader);
90806
90807   interiorReaderDestroy(&reader);
90808
90809   /* Children must ascend, and if !prefix, both must be the same. */
90810   assert( *piEndChild>=*piStartChild );
90811   assert( isPrefix || *piStartChild==*piEndChild );
90812 }
90813
90814 /* Read block at iBlockid and pass it with other params to
90815 ** getChildrenContaining().
90816 */
90817 static int loadAndGetChildrenContaining(
90818   fulltext_vtab *v,
90819   sqlite_int64 iBlockid,
90820   const char *pTerm, int nTerm, int isPrefix,
90821   sqlite_int64 *piStartChild, sqlite_int64 *piEndChild
90822 ){
90823   sqlite3_stmt *s = NULL;
90824   int rc;
90825
90826   assert( iBlockid!=0 );
90827   assert( pTerm!=NULL );
90828   assert( nTerm!=0 );        /* TODO(shess) Why not allow this? */
90829   assert( piStartChild!=NULL );
90830   assert( piEndChild!=NULL );
90831
90832   rc = sql_get_statement(v, BLOCK_SELECT_STMT, &s);
90833   if( rc!=SQLITE_OK ) return rc;
90834
90835   rc = sqlite3_bind_int64(s, 1, iBlockid);
90836   if( rc!=SQLITE_OK ) return rc;
90837
90838   rc = sqlite3_step(s);
90839   if( rc==SQLITE_DONE ) return SQLITE_ERROR;
90840   if( rc!=SQLITE_ROW ) return rc;
90841
90842   getChildrenContaining(sqlite3_column_blob(s, 0), sqlite3_column_bytes(s, 0),
90843                         pTerm, nTerm, isPrefix, piStartChild, piEndChild);
90844
90845   /* We expect only one row.  We must execute another sqlite3_step()
90846    * to complete the iteration; otherwise the table will remain
90847    * locked. */
90848   rc = sqlite3_step(s);
90849   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
90850   if( rc!=SQLITE_DONE ) return rc;
90851
90852   return SQLITE_OK;
90853 }
90854
90855 /* Traverse the tree represented by pData[nData] looking for
90856 ** pTerm[nTerm], placing its doclist into *out.  This is internal to
90857 ** loadSegment() to make error-handling cleaner.
90858 */
90859 static int loadSegmentInt(fulltext_vtab *v, const char *pData, int nData,
90860                           sqlite_int64 iLeavesEnd,
90861                           const char *pTerm, int nTerm, int isPrefix,
90862                           DataBuffer *out){
90863   /* Special case where root is a leaf. */
90864   if( *pData=='\0' ){
90865     return loadSegmentLeaf(v, pData, nData, pTerm, nTerm, isPrefix, out);
90866   }else{
90867     int rc;
90868     sqlite_int64 iStartChild, iEndChild;
90869
90870     /* Process pData as an interior node, then loop down the tree
90871     ** until we find the set of leaf nodes to scan for the term.
90872     */
90873     getChildrenContaining(pData, nData, pTerm, nTerm, isPrefix,
90874                           &iStartChild, &iEndChild);
90875     while( iStartChild>iLeavesEnd ){
90876       sqlite_int64 iNextStart, iNextEnd;
90877       rc = loadAndGetChildrenContaining(v, iStartChild, pTerm, nTerm, isPrefix,
90878                                         &iNextStart, &iNextEnd);
90879       if( rc!=SQLITE_OK ) return rc;
90880
90881       /* If we've branched, follow the end branch, too. */
90882       if( iStartChild!=iEndChild ){
90883         sqlite_int64 iDummy;
90884         rc = loadAndGetChildrenContaining(v, iEndChild, pTerm, nTerm, isPrefix,
90885                                           &iDummy, &iNextEnd);
90886         if( rc!=SQLITE_OK ) return rc;
90887       }
90888
90889       assert( iNextStart<=iNextEnd );
90890       iStartChild = iNextStart;
90891       iEndChild = iNextEnd;
90892     }
90893     assert( iStartChild<=iLeavesEnd );
90894     assert( iEndChild<=iLeavesEnd );
90895
90896     /* Scan through the leaf segments for doclists. */
90897     return loadSegmentLeaves(v, iStartChild, iEndChild,
90898                              pTerm, nTerm, isPrefix, out);
90899   }
90900 }
90901
90902 /* Call loadSegmentInt() to collect the doclist for pTerm/nTerm, then
90903 ** merge its doclist over *out (any duplicate doclists read from the
90904 ** segment rooted at pData will overwrite those in *out).
90905 */
90906 /* TODO(shess) Consider changing this to determine the depth of the
90907 ** leaves using either the first characters of interior nodes (when
90908 ** ==1, we're one level above the leaves), or the first character of
90909 ** the root (which will describe the height of the tree directly).
90910 ** Either feels somewhat tricky to me.
90911 */
90912 /* TODO(shess) The current merge is likely to be slow for large
90913 ** doclists (though it should process from newest/smallest to
90914 ** oldest/largest, so it may not be that bad).  It might be useful to
90915 ** modify things to allow for N-way merging.  This could either be
90916 ** within a segment, with pairwise merges across segments, or across
90917 ** all segments at once.
90918 */
90919 static int loadSegment(fulltext_vtab *v, const char *pData, int nData,
90920                        sqlite_int64 iLeavesEnd,
90921                        const char *pTerm, int nTerm, int isPrefix,
90922                        DataBuffer *out){
90923   DataBuffer result;
90924   int rc;
90925
90926   assert( nData>1 );
90927
90928   /* This code should never be called with buffered updates. */
90929   assert( v->nPendingData<0 );
90930
90931   dataBufferInit(&result, 0);
90932   rc = loadSegmentInt(v, pData, nData, iLeavesEnd,
90933                       pTerm, nTerm, isPrefix, &result);
90934   if( rc==SQLITE_OK && result.nData>0 ){
90935     if( out->nData==0 ){
90936       DataBuffer tmp = *out;
90937       *out = result;
90938       result = tmp;
90939     }else{
90940       DataBuffer merged;
90941       DLReader readers[2];
90942
90943       dlrInit(&readers[0], DL_DEFAULT, out->pData, out->nData);
90944       dlrInit(&readers[1], DL_DEFAULT, result.pData, result.nData);
90945       dataBufferInit(&merged, out->nData+result.nData);
90946       docListMerge(&merged, readers, 2);
90947       dataBufferDestroy(out);
90948       *out = merged;
90949       dlrDestroy(&readers[0]);
90950       dlrDestroy(&readers[1]);
90951     }
90952   }
90953   dataBufferDestroy(&result);
90954   return rc;
90955 }
90956
90957 /* Scan the database and merge together the posting lists for the term
90958 ** into *out.
90959 */
90960 static int termSelect(fulltext_vtab *v, int iColumn,
90961                       const char *pTerm, int nTerm, int isPrefix,
90962                       DocListType iType, DataBuffer *out){
90963   DataBuffer doclist;
90964   sqlite3_stmt *s;
90965   int rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
90966   if( rc!=SQLITE_OK ) return rc;
90967
90968   /* This code should never be called with buffered updates. */
90969   assert( v->nPendingData<0 );
90970
90971   dataBufferInit(&doclist, 0);
90972
90973   /* Traverse the segments from oldest to newest so that newer doclist
90974   ** elements for given docids overwrite older elements.
90975   */
90976   while( (rc = sqlite3_step(s))==SQLITE_ROW ){
90977     const char *pData = sqlite3_column_blob(s, 2);
90978     const int nData = sqlite3_column_bytes(s, 2);
90979     const sqlite_int64 iLeavesEnd = sqlite3_column_int64(s, 1);
90980     rc = loadSegment(v, pData, nData, iLeavesEnd, pTerm, nTerm, isPrefix,
90981                      &doclist);
90982     if( rc!=SQLITE_OK ) goto err;
90983   }
90984   if( rc==SQLITE_DONE ){
90985     if( doclist.nData!=0 ){
90986       /* TODO(shess) The old term_select_all() code applied the column
90987       ** restrict as we merged segments, leading to smaller buffers.
90988       ** This is probably worthwhile to bring back, once the new storage
90989       ** system is checked in.
90990       */
90991       if( iColumn==v->nColumn) iColumn = -1;
90992       docListTrim(DL_DEFAULT, doclist.pData, doclist.nData,
90993                   iColumn, iType, out);
90994     }
90995     rc = SQLITE_OK;
90996   }
90997
90998  err:
90999   dataBufferDestroy(&doclist);
91000   return rc;
91001 }
91002
91003 /****************************************************************/
91004 /* Used to hold hashtable data for sorting. */
91005 typedef struct TermData {
91006   const char *pTerm;
91007   int nTerm;
91008   DLCollector *pCollector;
91009 } TermData;
91010
91011 /* Orders TermData elements in strcmp fashion ( <0 for less-than, 0
91012 ** for equal, >0 for greater-than).
91013 */
91014 static int termDataCmp(const void *av, const void *bv){
91015   const TermData *a = (const TermData *)av;
91016   const TermData *b = (const TermData *)bv;
91017   int n = a->nTerm<b->nTerm ? a->nTerm : b->nTerm;
91018   int c = memcmp(a->pTerm, b->pTerm, n);
91019   if( c!=0 ) return c;
91020   return a->nTerm-b->nTerm;
91021 }
91022
91023 /* Order pTerms data by term, then write a new level 0 segment using
91024 ** LeafWriter.
91025 */
91026 static int writeZeroSegment(fulltext_vtab *v, fts3Hash *pTerms){
91027   fts3HashElem *e;
91028   int idx, rc, i, n;
91029   TermData *pData;
91030   LeafWriter writer;
91031   DataBuffer dl;
91032
91033   /* Determine the next index at level 0, merging as necessary. */
91034   rc = segdirNextIndex(v, 0, &idx);
91035   if( rc!=SQLITE_OK ) return rc;
91036
91037   n = fts3HashCount(pTerms);
91038   pData = sqlite3_malloc(n*sizeof(TermData));
91039
91040   for(i = 0, e = fts3HashFirst(pTerms); e; i++, e = fts3HashNext(e)){
91041     assert( i<n );
91042     pData[i].pTerm = fts3HashKey(e);
91043     pData[i].nTerm = fts3HashKeysize(e);
91044     pData[i].pCollector = fts3HashData(e);
91045   }
91046   assert( i==n );
91047
91048   /* TODO(shess) Should we allow user-defined collation sequences,
91049   ** here?  I think we only need that once we support prefix searches.
91050   */
91051   if( n>1 ) qsort(pData, n, sizeof(*pData), termDataCmp);
91052
91053   /* TODO(shess) Refactor so that we can write directly to the segment
91054   ** DataBuffer, as happens for segment merges.
91055   */
91056   leafWriterInit(0, idx, &writer);
91057   dataBufferInit(&dl, 0);
91058   for(i=0; i<n; i++){
91059     dataBufferReset(&dl);
91060     dlcAddDoclist(pData[i].pCollector, &dl);
91061     rc = leafWriterStep(v, &writer,
91062                         pData[i].pTerm, pData[i].nTerm, dl.pData, dl.nData);
91063     if( rc!=SQLITE_OK ) goto err;
91064   }
91065   rc = leafWriterFinalize(v, &writer);
91066
91067  err:
91068   dataBufferDestroy(&dl);
91069   sqlite3_free(pData);
91070   leafWriterDestroy(&writer);
91071   return rc;
91072 }
91073
91074 /* If pendingTerms has data, free it. */
91075 static int clearPendingTerms(fulltext_vtab *v){
91076   if( v->nPendingData>=0 ){
91077     fts3HashElem *e;
91078     for(e=fts3HashFirst(&v->pendingTerms); e; e=fts3HashNext(e)){
91079       dlcDelete(fts3HashData(e));
91080     }
91081     fts3HashClear(&v->pendingTerms);
91082     v->nPendingData = -1;
91083   }
91084   return SQLITE_OK;
91085 }
91086
91087 /* If pendingTerms has data, flush it to a level-zero segment, and
91088 ** free it.
91089 */
91090 static int flushPendingTerms(fulltext_vtab *v){
91091   if( v->nPendingData>=0 ){
91092     int rc = writeZeroSegment(v, &v->pendingTerms);
91093     if( rc==SQLITE_OK ) clearPendingTerms(v);
91094     return rc;
91095   }
91096   return SQLITE_OK;
91097 }
91098
91099 /* If pendingTerms is "too big", or docid is out of order, flush it.
91100 ** Regardless, be certain that pendingTerms is initialized for use.
91101 */
91102 static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid){
91103   /* TODO(shess) Explore whether partially flushing the buffer on
91104   ** forced-flush would provide better performance.  I suspect that if
91105   ** we ordered the doclists by size and flushed the largest until the
91106   ** buffer was half empty, that would let the less frequent terms
91107   ** generate longer doclists.
91108   */
91109   if( iDocid<=v->iPrevDocid || v->nPendingData>kPendingThreshold ){
91110     int rc = flushPendingTerms(v);
91111     if( rc!=SQLITE_OK ) return rc;
91112   }
91113   if( v->nPendingData<0 ){
91114     fts3HashInit(&v->pendingTerms, FTS3_HASH_STRING, 1);
91115     v->nPendingData = 0;
91116   }
91117   v->iPrevDocid = iDocid;
91118   return SQLITE_OK;
91119 }
91120
91121 /* This function implements the xUpdate callback; it is the top-level entry
91122  * point for inserting, deleting or updating a row in a full-text table. */
91123 static int fulltextUpdate(sqlite3_vtab *pVtab, int nArg, sqlite3_value **ppArg,
91124                           sqlite_int64 *pRowid){
91125   fulltext_vtab *v = (fulltext_vtab *) pVtab;
91126   int rc;
91127
91128   FTSTRACE(("FTS3 Update %p\n", pVtab));
91129
91130   if( nArg<2 ){
91131     rc = index_delete(v, sqlite3_value_int64(ppArg[0]));
91132     if( rc==SQLITE_OK ){
91133       /* If we just deleted the last row in the table, clear out the
91134       ** index data.
91135       */
91136       rc = content_exists(v);
91137       if( rc==SQLITE_ROW ){
91138         rc = SQLITE_OK;
91139       }else if( rc==SQLITE_DONE ){
91140         /* Clear the pending terms so we don't flush a useless level-0
91141         ** segment when the transaction closes.
91142         */
91143         rc = clearPendingTerms(v);
91144         if( rc==SQLITE_OK ){
91145           rc = segdir_delete_all(v);
91146         }
91147       }
91148     }
91149   } else if( sqlite3_value_type(ppArg[0]) != SQLITE_NULL ){
91150     /* An update:
91151      * ppArg[0] = old rowid
91152      * ppArg[1] = new rowid
91153      * ppArg[2..2+v->nColumn-1] = values
91154      * ppArg[2+v->nColumn] = value for magic column (we ignore this)
91155      * ppArg[2+v->nColumn+1] = value for docid
91156      */
91157     sqlite_int64 rowid = sqlite3_value_int64(ppArg[0]);
91158     if( sqlite3_value_type(ppArg[1]) != SQLITE_INTEGER ||
91159         sqlite3_value_int64(ppArg[1]) != rowid ){
91160       rc = SQLITE_ERROR;  /* we don't allow changing the rowid */
91161     }else if( sqlite3_value_type(ppArg[2+v->nColumn+1]) != SQLITE_INTEGER ||
91162               sqlite3_value_int64(ppArg[2+v->nColumn+1]) != rowid ){
91163       rc = SQLITE_ERROR;  /* we don't allow changing the docid */
91164     }else{
91165       assert( nArg==2+v->nColumn+2);
91166       rc = index_update(v, rowid, &ppArg[2]);
91167     }
91168   } else {
91169     /* An insert:
91170      * ppArg[1] = requested rowid
91171      * ppArg[2..2+v->nColumn-1] = values
91172      * ppArg[2+v->nColumn] = value for magic column (we ignore this)
91173      * ppArg[2+v->nColumn+1] = value for docid
91174      */
91175     sqlite3_value *pRequestDocid = ppArg[2+v->nColumn+1];
91176     assert( nArg==2+v->nColumn+2);
91177     if( SQLITE_NULL != sqlite3_value_type(pRequestDocid) &&
91178         SQLITE_NULL != sqlite3_value_type(ppArg[1]) ){
91179       /* TODO(shess) Consider allowing this to work if the values are
91180       ** identical.  I'm inclined to discourage that usage, though,
91181       ** given that both rowid and docid are special columns.  Better
91182       ** would be to define one or the other as the default winner,
91183       ** but should it be fts3-centric (docid) or SQLite-centric
91184       ** (rowid)?
91185       */
91186       rc = SQLITE_ERROR;
91187     }else{
91188       if( SQLITE_NULL == sqlite3_value_type(pRequestDocid) ){
91189         pRequestDocid = ppArg[1];
91190       }
91191       rc = index_insert(v, pRequestDocid, &ppArg[2], pRowid);
91192     }
91193   }
91194
91195   return rc;
91196 }
91197
91198 static int fulltextSync(sqlite3_vtab *pVtab){
91199   FTSTRACE(("FTS3 xSync()\n"));
91200   return flushPendingTerms((fulltext_vtab *)pVtab);
91201 }
91202
91203 static int fulltextBegin(sqlite3_vtab *pVtab){
91204   fulltext_vtab *v = (fulltext_vtab *) pVtab;
91205   FTSTRACE(("FTS3 xBegin()\n"));
91206
91207   /* Any buffered updates should have been cleared by the previous
91208   ** transaction.
91209   */
91210   assert( v->nPendingData<0 );
91211   return clearPendingTerms(v);
91212 }
91213
91214 static int fulltextCommit(sqlite3_vtab *pVtab){
91215   fulltext_vtab *v = (fulltext_vtab *) pVtab;
91216   FTSTRACE(("FTS3 xCommit()\n"));
91217
91218   /* Buffered updates should have been cleared by fulltextSync(). */
91219   assert( v->nPendingData<0 );
91220   return clearPendingTerms(v);
91221 }
91222
91223 static int fulltextRollback(sqlite3_vtab *pVtab){
91224   FTSTRACE(("FTS3 xRollback()\n"));
91225   return clearPendingTerms((fulltext_vtab *)pVtab);
91226 }
91227
91228 /*
91229 ** Implementation of the snippet() function for FTS3
91230 */
91231 static void snippetFunc(
91232   sqlite3_context *pContext,
91233   int argc,
91234   sqlite3_value **argv
91235 ){
91236   fulltext_cursor *pCursor;
91237   if( argc<1 ) return;
91238   if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
91239       sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
91240     sqlite3_result_error(pContext, "illegal first argument to html_snippet",-1);
91241   }else{
91242     const char *zStart = "<b>";
91243     const char *zEnd = "</b>";
91244     const char *zEllipsis = "<b>...</b>";
91245     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
91246     if( argc>=2 ){
91247       zStart = (const char*)sqlite3_value_text(argv[1]);
91248       if( argc>=3 ){
91249         zEnd = (const char*)sqlite3_value_text(argv[2]);
91250         if( argc>=4 ){
91251           zEllipsis = (const char*)sqlite3_value_text(argv[3]);
91252         }
91253       }
91254     }
91255     snippetAllOffsets(pCursor);
91256     snippetText(pCursor, zStart, zEnd, zEllipsis);
91257     sqlite3_result_text(pContext, pCursor->snippet.zSnippet,
91258                         pCursor->snippet.nSnippet, SQLITE_STATIC);
91259   }
91260 }
91261
91262 /*
91263 ** Implementation of the offsets() function for FTS3
91264 */
91265 static void snippetOffsetsFunc(
91266   sqlite3_context *pContext,
91267   int argc,
91268   sqlite3_value **argv
91269 ){
91270   fulltext_cursor *pCursor;
91271   if( argc<1 ) return;
91272   if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
91273       sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
91274     sqlite3_result_error(pContext, "illegal first argument to offsets",-1);
91275   }else{
91276     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
91277     snippetAllOffsets(pCursor);
91278     snippetOffsetText(&pCursor->snippet);
91279     sqlite3_result_text(pContext,
91280                         pCursor->snippet.zOffset, pCursor->snippet.nOffset,
91281                         SQLITE_STATIC);
91282   }
91283 }
91284
91285 /* OptLeavesReader is nearly identical to LeavesReader, except that
91286 ** where LeavesReader is geared towards the merging of complete
91287 ** segment levels (with exactly MERGE_COUNT segments), OptLeavesReader
91288 ** is geared towards implementation of the optimize() function, and
91289 ** can merge all segments simultaneously.  This version may be
91290 ** somewhat less efficient than LeavesReader because it merges into an
91291 ** accumulator rather than doing an N-way merge, but since segment
91292 ** size grows exponentially (so segment count logrithmically) this is
91293 ** probably not an immediate problem.
91294 */
91295 /* TODO(shess): Prove that assertion, or extend the merge code to
91296 ** merge tree fashion (like the prefix-searching code does).
91297 */
91298 /* TODO(shess): OptLeavesReader and LeavesReader could probably be
91299 ** merged with little or no loss of performance for LeavesReader.  The
91300 ** merged code would need to handle >MERGE_COUNT segments, and would
91301 ** also need to be able to optionally optimize away deletes.
91302 */
91303 typedef struct OptLeavesReader {
91304   /* Segment number, to order readers by age. */
91305   int segment;
91306   LeavesReader reader;
91307 } OptLeavesReader;
91308
91309 static int optLeavesReaderAtEnd(OptLeavesReader *pReader){
91310   return leavesReaderAtEnd(&pReader->reader);
91311 }
91312 static int optLeavesReaderTermBytes(OptLeavesReader *pReader){
91313   return leavesReaderTermBytes(&pReader->reader);
91314 }
91315 static const char *optLeavesReaderData(OptLeavesReader *pReader){
91316   return leavesReaderData(&pReader->reader);
91317 }
91318 static int optLeavesReaderDataBytes(OptLeavesReader *pReader){
91319   return leavesReaderDataBytes(&pReader->reader);
91320 }
91321 static const char *optLeavesReaderTerm(OptLeavesReader *pReader){
91322   return leavesReaderTerm(&pReader->reader);
91323 }
91324 static int optLeavesReaderStep(fulltext_vtab *v, OptLeavesReader *pReader){
91325   return leavesReaderStep(v, &pReader->reader);
91326 }
91327 static int optLeavesReaderTermCmp(OptLeavesReader *lr1, OptLeavesReader *lr2){
91328   return leavesReaderTermCmp(&lr1->reader, &lr2->reader);
91329 }
91330 /* Order by term ascending, segment ascending (oldest to newest), with
91331 ** exhausted readers to the end.
91332 */
91333 static int optLeavesReaderCmp(OptLeavesReader *lr1, OptLeavesReader *lr2){
91334   int c = optLeavesReaderTermCmp(lr1, lr2);
91335   if( c!=0 ) return c;
91336   return lr1->segment-lr2->segment;
91337 }
91338 /* Bubble pLr[0] to appropriate place in pLr[1..nLr-1].  Assumes that
91339 ** pLr[1..nLr-1] is already sorted.
91340 */
91341 static void optLeavesReaderReorder(OptLeavesReader *pLr, int nLr){
91342   while( nLr>1 && optLeavesReaderCmp(pLr, pLr+1)>0 ){
91343     OptLeavesReader tmp = pLr[0];
91344     pLr[0] = pLr[1];
91345     pLr[1] = tmp;
91346     nLr--;
91347     pLr++;
91348   }
91349 }
91350
91351 /* optimize() helper function.  Put the readers in order and iterate
91352 ** through them, merging doclists for matching terms into pWriter.
91353 ** Returns SQLITE_OK on success, or the SQLite error code which
91354 ** prevented success.
91355 */
91356 static int optimizeInternal(fulltext_vtab *v,
91357                             OptLeavesReader *readers, int nReaders,
91358                             LeafWriter *pWriter){
91359   int i, rc = SQLITE_OK;
91360   DataBuffer doclist, merged, tmp;
91361
91362   /* Order the readers. */
91363   i = nReaders;
91364   while( i-- > 0 ){
91365     optLeavesReaderReorder(&readers[i], nReaders-i);
91366   }
91367
91368   dataBufferInit(&doclist, LEAF_MAX);
91369   dataBufferInit(&merged, LEAF_MAX);
91370
91371   /* Exhausted readers bubble to the end, so when the first reader is
91372   ** at eof, all are at eof.
91373   */
91374   while( !optLeavesReaderAtEnd(&readers[0]) ){
91375
91376     /* Figure out how many readers share the next term. */
91377     for(i=1; i<nReaders && !optLeavesReaderAtEnd(&readers[i]); i++){
91378       if( 0!=optLeavesReaderTermCmp(&readers[0], &readers[i]) ) break;
91379     }
91380
91381     /* Special-case for no merge. */
91382     if( i==1 ){
91383       /* Trim deletions from the doclist. */
91384       dataBufferReset(&merged);
91385       docListTrim(DL_DEFAULT,
91386                   optLeavesReaderData(&readers[0]),
91387                   optLeavesReaderDataBytes(&readers[0]),
91388                   -1, DL_DEFAULT, &merged);
91389     }else{
91390       DLReader dlReaders[MERGE_COUNT];
91391       int iReader, nReaders;
91392
91393       /* Prime the pipeline with the first reader's doclist.  After
91394       ** one pass index 0 will reference the accumulated doclist.
91395       */
91396       dlrInit(&dlReaders[0], DL_DEFAULT,
91397               optLeavesReaderData(&readers[0]),
91398               optLeavesReaderDataBytes(&readers[0]));
91399       iReader = 1;
91400
91401       assert( iReader<i );  /* Must execute the loop at least once. */
91402       while( iReader<i ){
91403         /* Merge 16 inputs per pass. */
91404         for( nReaders=1; iReader<i && nReaders<MERGE_COUNT;
91405              iReader++, nReaders++ ){
91406           dlrInit(&dlReaders[nReaders], DL_DEFAULT,
91407                   optLeavesReaderData(&readers[iReader]),
91408                   optLeavesReaderDataBytes(&readers[iReader]));
91409         }
91410
91411         /* Merge doclists and swap result into accumulator. */
91412         dataBufferReset(&merged);
91413         docListMerge(&merged, dlReaders, nReaders);
91414         tmp = merged;
91415         merged = doclist;
91416         doclist = tmp;
91417
91418         while( nReaders-- > 0 ){
91419           dlrDestroy(&dlReaders[nReaders]);
91420         }
91421
91422         /* Accumulated doclist to reader 0 for next pass. */
91423         dlrInit(&dlReaders[0], DL_DEFAULT, doclist.pData, doclist.nData);
91424       }
91425
91426       /* Destroy reader that was left in the pipeline. */
91427       dlrDestroy(&dlReaders[0]);
91428
91429       /* Trim deletions from the doclist. */
91430       dataBufferReset(&merged);
91431       docListTrim(DL_DEFAULT, doclist.pData, doclist.nData,
91432                   -1, DL_DEFAULT, &merged);
91433     }
91434
91435     /* Only pass doclists with hits (skip if all hits deleted). */
91436     if( merged.nData>0 ){
91437       rc = leafWriterStep(v, pWriter,
91438                           optLeavesReaderTerm(&readers[0]),
91439                           optLeavesReaderTermBytes(&readers[0]),
91440                           merged.pData, merged.nData);
91441       if( rc!=SQLITE_OK ) goto err;
91442     }
91443
91444     /* Step merged readers to next term and reorder. */
91445     while( i-- > 0 ){
91446       rc = optLeavesReaderStep(v, &readers[i]);
91447       if( rc!=SQLITE_OK ) goto err;
91448
91449       optLeavesReaderReorder(&readers[i], nReaders-i);
91450     }
91451   }
91452
91453  err:
91454   dataBufferDestroy(&doclist);
91455   dataBufferDestroy(&merged);
91456   return rc;
91457 }
91458
91459 /* Implement optimize() function for FTS3.  optimize(t) merges all
91460 ** segments in the fts index into a single segment.  't' is the magic
91461 ** table-named column.
91462 */
91463 static void optimizeFunc(sqlite3_context *pContext,
91464                          int argc, sqlite3_value **argv){
91465   fulltext_cursor *pCursor;
91466   if( argc>1 ){
91467     sqlite3_result_error(pContext, "excess arguments to optimize()",-1);
91468   }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
91469             sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
91470     sqlite3_result_error(pContext, "illegal first argument to optimize",-1);
91471   }else{
91472     fulltext_vtab *v;
91473     int i, rc, iMaxLevel;
91474     OptLeavesReader *readers;
91475     int nReaders;
91476     LeafWriter writer;
91477     sqlite3_stmt *s;
91478
91479     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
91480     v = cursor_vtab(pCursor);
91481
91482     /* Flush any buffered updates before optimizing. */
91483     rc = flushPendingTerms(v);
91484     if( rc!=SQLITE_OK ) goto err;
91485
91486     rc = segdir_count(v, &nReaders, &iMaxLevel);
91487     if( rc!=SQLITE_OK ) goto err;
91488     if( nReaders==0 || nReaders==1 ){
91489       sqlite3_result_text(pContext, "Index already optimal", -1,
91490                           SQLITE_STATIC);
91491       return;
91492     }
91493
91494     rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
91495     if( rc!=SQLITE_OK ) goto err;
91496
91497     readers = sqlite3_malloc(nReaders*sizeof(readers[0]));
91498     if( readers==NULL ) goto err;
91499
91500     /* Note that there will already be a segment at this position
91501     ** until we call segdir_delete() on iMaxLevel.
91502     */
91503     leafWriterInit(iMaxLevel, 0, &writer);
91504
91505     i = 0;
91506     while( (rc = sqlite3_step(s))==SQLITE_ROW ){
91507       sqlite_int64 iStart = sqlite3_column_int64(s, 0);
91508       sqlite_int64 iEnd = sqlite3_column_int64(s, 1);
91509       const char *pRootData = sqlite3_column_blob(s, 2);
91510       int nRootData = sqlite3_column_bytes(s, 2);
91511
91512       assert( i<nReaders );
91513       rc = leavesReaderInit(v, -1, iStart, iEnd, pRootData, nRootData,
91514                             &readers[i].reader);
91515       if( rc!=SQLITE_OK ) break;
91516
91517       readers[i].segment = i;
91518       i++;
91519     }
91520
91521     /* If we managed to succesfully read them all, optimize them. */
91522     if( rc==SQLITE_DONE ){
91523       assert( i==nReaders );
91524       rc = optimizeInternal(v, readers, nReaders, &writer);
91525     }
91526
91527     while( i-- > 0 ){
91528       leavesReaderDestroy(&readers[i].reader);
91529     }
91530     sqlite3_free(readers);
91531
91532     /* If we've successfully gotten to here, delete the old segments
91533     ** and flush the interior structure of the new segment.
91534     */
91535     if( rc==SQLITE_OK ){
91536       for( i=0; i<=iMaxLevel; i++ ){
91537         rc = segdir_delete(v, i);
91538         if( rc!=SQLITE_OK ) break;
91539       }
91540
91541       if( rc==SQLITE_OK ) rc = leafWriterFinalize(v, &writer);
91542     }
91543
91544     leafWriterDestroy(&writer);
91545
91546     if( rc!=SQLITE_OK ) goto err;
91547
91548     sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
91549     return;
91550
91551     /* TODO(shess): Error-handling needs to be improved along the
91552     ** lines of the dump_ functions.
91553     */
91554  err:
91555     {
91556       char buf[512];
91557       sqlite3_snprintf(sizeof(buf), buf, "Error in optimize: %s",
91558                        sqlite3_errmsg(sqlite3_context_db_handle(pContext)));
91559       sqlite3_result_error(pContext, buf, -1);
91560     }
91561   }
91562 }
91563
91564 #ifdef SQLITE_TEST
91565 /* Generate an error of the form "<prefix>: <msg>".  If msg is NULL,
91566 ** pull the error from the context's db handle.
91567 */
91568 static void generateError(sqlite3_context *pContext,
91569                           const char *prefix, const char *msg){
91570   char buf[512];
91571   if( msg==NULL ) msg = sqlite3_errmsg(sqlite3_context_db_handle(pContext));
91572   sqlite3_snprintf(sizeof(buf), buf, "%s: %s", prefix, msg);
91573   sqlite3_result_error(pContext, buf, -1);
91574 }
91575
91576 /* Helper function to collect the set of terms in the segment into
91577 ** pTerms.  The segment is defined by the leaf nodes between
91578 ** iStartBlockid and iEndBlockid, inclusive, or by the contents of
91579 ** pRootData if iStartBlockid is 0 (in which case the entire segment
91580 ** fit in a leaf).
91581 */
91582 static int collectSegmentTerms(fulltext_vtab *v, sqlite3_stmt *s,
91583                                fts3Hash *pTerms){
91584   const sqlite_int64 iStartBlockid = sqlite3_column_int64(s, 0);
91585   const sqlite_int64 iEndBlockid = sqlite3_column_int64(s, 1);
91586   const char *pRootData = sqlite3_column_blob(s, 2);
91587   const int nRootData = sqlite3_column_bytes(s, 2);
91588   LeavesReader reader;
91589   int rc = leavesReaderInit(v, 0, iStartBlockid, iEndBlockid,
91590                             pRootData, nRootData, &reader);
91591   if( rc!=SQLITE_OK ) return rc;
91592
91593   while( rc==SQLITE_OK && !leavesReaderAtEnd(&reader) ){
91594     const char *pTerm = leavesReaderTerm(&reader);
91595     const int nTerm = leavesReaderTermBytes(&reader);
91596     void *oldValue = sqlite3Fts3HashFind(pTerms, pTerm, nTerm);
91597     void *newValue = (void *)((char *)oldValue+1);
91598
91599     /* From the comment before sqlite3Fts3HashInsert in fts3_hash.c,
91600     ** the data value passed is returned in case of malloc failure.
91601     */
91602     if( newValue==sqlite3Fts3HashInsert(pTerms, pTerm, nTerm, newValue) ){
91603       rc = SQLITE_NOMEM;
91604     }else{
91605       rc = leavesReaderStep(v, &reader);
91606     }
91607   }
91608
91609   leavesReaderDestroy(&reader);
91610   return rc;
91611 }
91612
91613 /* Helper function to build the result string for dump_terms(). */
91614 static int generateTermsResult(sqlite3_context *pContext, fts3Hash *pTerms){
91615   int iTerm, nTerms, nResultBytes, iByte;
91616   char *result;
91617   TermData *pData;
91618   fts3HashElem *e;
91619
91620   /* Iterate pTerms to generate an array of terms in pData for
91621   ** sorting.
91622   */
91623   nTerms = fts3HashCount(pTerms);
91624   assert( nTerms>0 );
91625   pData = sqlite3_malloc(nTerms*sizeof(TermData));
91626   if( pData==NULL ) return SQLITE_NOMEM;
91627
91628   nResultBytes = 0;
91629   for(iTerm = 0, e = fts3HashFirst(pTerms); e; iTerm++, e = fts3HashNext(e)){
91630     nResultBytes += fts3HashKeysize(e)+1;   /* Term plus trailing space */
91631     assert( iTerm<nTerms );
91632     pData[iTerm].pTerm = fts3HashKey(e);
91633     pData[iTerm].nTerm = fts3HashKeysize(e);
91634     pData[iTerm].pCollector = fts3HashData(e);  /* unused */
91635   }
91636   assert( iTerm==nTerms );
91637
91638   assert( nResultBytes>0 );   /* nTerms>0, nResultsBytes must be, too. */
91639   result = sqlite3_malloc(nResultBytes);
91640   if( result==NULL ){
91641     sqlite3_free(pData);
91642     return SQLITE_NOMEM;
91643   }
91644
91645   if( nTerms>1 ) qsort(pData, nTerms, sizeof(*pData), termDataCmp);
91646
91647   /* Read the terms in order to build the result. */
91648   iByte = 0;
91649   for(iTerm=0; iTerm<nTerms; ++iTerm){
91650     memcpy(result+iByte, pData[iTerm].pTerm, pData[iTerm].nTerm);
91651     iByte += pData[iTerm].nTerm;
91652     result[iByte++] = ' ';
91653   }
91654   assert( iByte==nResultBytes );
91655   assert( result[nResultBytes-1]==' ' );
91656   result[nResultBytes-1] = '\0';
91657
91658   /* Passes away ownership of result. */
91659   sqlite3_result_text(pContext, result, nResultBytes-1, sqlite3_free);
91660   sqlite3_free(pData);
91661   return SQLITE_OK;
91662 }
91663
91664 /* Implements dump_terms() for use in inspecting the fts3 index from
91665 ** tests.  TEXT result containing the ordered list of terms joined by
91666 ** spaces.  dump_terms(t, level, idx) dumps the terms for the segment
91667 ** specified by level, idx (in %_segdir), while dump_terms(t) dumps
91668 ** all terms in the index.  In both cases t is the fts table's magic
91669 ** table-named column.
91670 */
91671 static void dumpTermsFunc(
91672   sqlite3_context *pContext,
91673   int argc, sqlite3_value **argv
91674 ){
91675   fulltext_cursor *pCursor;
91676   if( argc!=3 && argc!=1 ){
91677     generateError(pContext, "dump_terms", "incorrect arguments");
91678   }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
91679             sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
91680     generateError(pContext, "dump_terms", "illegal first argument");
91681   }else{
91682     fulltext_vtab *v;
91683     fts3Hash terms;
91684     sqlite3_stmt *s = NULL;
91685     int rc;
91686
91687     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
91688     v = cursor_vtab(pCursor);
91689
91690     /* If passed only the cursor column, get all segments.  Otherwise
91691     ** get the segment described by the following two arguments.
91692     */
91693     if( argc==1 ){
91694       rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
91695     }else{
91696       rc = sql_get_statement(v, SEGDIR_SELECT_SEGMENT_STMT, &s);
91697       if( rc==SQLITE_OK ){
91698         rc = sqlite3_bind_int(s, 1, sqlite3_value_int(argv[1]));
91699         if( rc==SQLITE_OK ){
91700           rc = sqlite3_bind_int(s, 2, sqlite3_value_int(argv[2]));
91701         }
91702       }
91703     }
91704
91705     if( rc!=SQLITE_OK ){
91706       generateError(pContext, "dump_terms", NULL);
91707       return;
91708     }
91709
91710     /* Collect the terms for each segment. */
91711     sqlite3Fts3HashInit(&terms, FTS3_HASH_STRING, 1);
91712     while( (rc = sqlite3_step(s))==SQLITE_ROW ){
91713       rc = collectSegmentTerms(v, s, &terms);
91714       if( rc!=SQLITE_OK ) break;
91715     }
91716
91717     if( rc!=SQLITE_DONE ){
91718       sqlite3_reset(s);
91719       generateError(pContext, "dump_terms", NULL);
91720     }else{
91721       const int nTerms = fts3HashCount(&terms);
91722       if( nTerms>0 ){
91723         rc = generateTermsResult(pContext, &terms);
91724         if( rc==SQLITE_NOMEM ){
91725           generateError(pContext, "dump_terms", "out of memory");
91726         }else{
91727           assert( rc==SQLITE_OK );
91728         }
91729       }else if( argc==3 ){
91730         /* The specific segment asked for could not be found. */
91731         generateError(pContext, "dump_terms", "segment not found");
91732       }else{
91733         /* No segments found. */
91734         /* TODO(shess): It should be impossible to reach this.  This
91735         ** case can only happen for an empty table, in which case
91736         ** SQLite has no rows to call this function on.
91737         */
91738         sqlite3_result_null(pContext);
91739       }
91740     }
91741     sqlite3Fts3HashClear(&terms);
91742   }
91743 }
91744
91745 /* Expand the DL_DEFAULT doclist in pData into a text result in
91746 ** pContext.
91747 */
91748 static void createDoclistResult(sqlite3_context *pContext,
91749                                 const char *pData, int nData){
91750   DataBuffer dump;
91751   DLReader dlReader;
91752
91753   assert( pData!=NULL && nData>0 );
91754
91755   dataBufferInit(&dump, 0);
91756   dlrInit(&dlReader, DL_DEFAULT, pData, nData);
91757   for( ; !dlrAtEnd(&dlReader); dlrStep(&dlReader) ){
91758     char buf[256];
91759     PLReader plReader;
91760
91761     plrInit(&plReader, &dlReader);
91762     if( DL_DEFAULT==DL_DOCIDS || plrAtEnd(&plReader) ){
91763       sqlite3_snprintf(sizeof(buf), buf, "[%lld] ", dlrDocid(&dlReader));
91764       dataBufferAppend(&dump, buf, strlen(buf));
91765     }else{
91766       int iColumn = plrColumn(&plReader);
91767
91768       sqlite3_snprintf(sizeof(buf), buf, "[%lld %d[",
91769                        dlrDocid(&dlReader), iColumn);
91770       dataBufferAppend(&dump, buf, strlen(buf));
91771
91772       for( ; !plrAtEnd(&plReader); plrStep(&plReader) ){
91773         if( plrColumn(&plReader)!=iColumn ){
91774           iColumn = plrColumn(&plReader);
91775           sqlite3_snprintf(sizeof(buf), buf, "] %d[", iColumn);
91776           assert( dump.nData>0 );
91777           dump.nData--;                     /* Overwrite trailing space. */
91778           assert( dump.pData[dump.nData]==' ');
91779           dataBufferAppend(&dump, buf, strlen(buf));
91780         }
91781         if( DL_DEFAULT==DL_POSITIONS_OFFSETS ){
91782           sqlite3_snprintf(sizeof(buf), buf, "%d,%d,%d ",
91783                            plrPosition(&plReader),
91784                            plrStartOffset(&plReader), plrEndOffset(&plReader));
91785         }else if( DL_DEFAULT==DL_POSITIONS ){
91786           sqlite3_snprintf(sizeof(buf), buf, "%d ", plrPosition(&plReader));
91787         }else{
91788           assert( NULL=="Unhandled DL_DEFAULT value");
91789         }
91790         dataBufferAppend(&dump, buf, strlen(buf));
91791       }
91792       plrDestroy(&plReader);
91793
91794       assert( dump.nData>0 );
91795       dump.nData--;                     /* Overwrite trailing space. */
91796       assert( dump.pData[dump.nData]==' ');
91797       dataBufferAppend(&dump, "]] ", 3);
91798     }
91799   }
91800   dlrDestroy(&dlReader);
91801
91802   assert( dump.nData>0 );
91803   dump.nData--;                     /* Overwrite trailing space. */
91804   assert( dump.pData[dump.nData]==' ');
91805   dump.pData[dump.nData] = '\0';
91806   assert( dump.nData>0 );
91807
91808   /* Passes ownership of dump's buffer to pContext. */
91809   sqlite3_result_text(pContext, dump.pData, dump.nData, sqlite3_free);
91810   dump.pData = NULL;
91811   dump.nData = dump.nCapacity = 0;
91812 }
91813
91814 /* Implements dump_doclist() for use in inspecting the fts3 index from
91815 ** tests.  TEXT result containing a string representation of the
91816 ** doclist for the indicated term.  dump_doclist(t, term, level, idx)
91817 ** dumps the doclist for term from the segment specified by level, idx
91818 ** (in %_segdir), while dump_doclist(t, term) dumps the logical
91819 ** doclist for the term across all segments.  The per-segment doclist
91820 ** can contain deletions, while the full-index doclist will not
91821 ** (deletions are omitted).
91822 **
91823 ** Result formats differ with the setting of DL_DEFAULTS.  Examples:
91824 **
91825 ** DL_DOCIDS: [1] [3] [7]
91826 ** DL_POSITIONS: [1 0[0 4] 1[17]] [3 1[5]]
91827 ** DL_POSITIONS_OFFSETS: [1 0[0,0,3 4,23,26] 1[17,102,105]] [3 1[5,20,23]]
91828 **
91829 ** In each case the number after the outer '[' is the docid.  In the
91830 ** latter two cases, the number before the inner '[' is the column
91831 ** associated with the values within.  For DL_POSITIONS the numbers
91832 ** within are the positions, for DL_POSITIONS_OFFSETS they are the
91833 ** position, the start offset, and the end offset.
91834 */
91835 static void dumpDoclistFunc(
91836   sqlite3_context *pContext,
91837   int argc, sqlite3_value **argv
91838 ){
91839   fulltext_cursor *pCursor;
91840   if( argc!=2 && argc!=4 ){
91841     generateError(pContext, "dump_doclist", "incorrect arguments");
91842   }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
91843             sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
91844     generateError(pContext, "dump_doclist", "illegal first argument");
91845   }else if( sqlite3_value_text(argv[1])==NULL ||
91846             sqlite3_value_text(argv[1])[0]=='\0' ){
91847     generateError(pContext, "dump_doclist", "empty second argument");
91848   }else{
91849     const char *pTerm = (const char *)sqlite3_value_text(argv[1]);
91850     const int nTerm = strlen(pTerm);
91851     fulltext_vtab *v;
91852     int rc;
91853     DataBuffer doclist;
91854
91855     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
91856     v = cursor_vtab(pCursor);
91857
91858     dataBufferInit(&doclist, 0);
91859
91860     /* termSelect() yields the same logical doclist that queries are
91861     ** run against.
91862     */
91863     if( argc==2 ){
91864       rc = termSelect(v, v->nColumn, pTerm, nTerm, 0, DL_DEFAULT, &doclist);
91865     }else{
91866       sqlite3_stmt *s = NULL;
91867
91868       /* Get our specific segment's information. */
91869       rc = sql_get_statement(v, SEGDIR_SELECT_SEGMENT_STMT, &s);
91870       if( rc==SQLITE_OK ){
91871         rc = sqlite3_bind_int(s, 1, sqlite3_value_int(argv[2]));
91872         if( rc==SQLITE_OK ){
91873           rc = sqlite3_bind_int(s, 2, sqlite3_value_int(argv[3]));
91874         }
91875       }
91876
91877       if( rc==SQLITE_OK ){
91878         rc = sqlite3_step(s);
91879
91880         if( rc==SQLITE_DONE ){
91881           dataBufferDestroy(&doclist);
91882           generateError(pContext, "dump_doclist", "segment not found");
91883           return;
91884         }
91885
91886         /* Found a segment, load it into doclist. */
91887         if( rc==SQLITE_ROW ){
91888           const sqlite_int64 iLeavesEnd = sqlite3_column_int64(s, 1);
91889           const char *pData = sqlite3_column_blob(s, 2);
91890           const int nData = sqlite3_column_bytes(s, 2);
91891
91892           /* loadSegment() is used by termSelect() to load each
91893           ** segment's data.
91894           */
91895           rc = loadSegment(v, pData, nData, iLeavesEnd, pTerm, nTerm, 0,
91896                            &doclist);
91897           if( rc==SQLITE_OK ){
91898             rc = sqlite3_step(s);
91899
91900             /* Should not have more than one matching segment. */
91901             if( rc!=SQLITE_DONE ){
91902               sqlite3_reset(s);
91903               dataBufferDestroy(&doclist);
91904               generateError(pContext, "dump_doclist", "invalid segdir");
91905               return;
91906             }
91907             rc = SQLITE_OK;
91908           }
91909         }
91910       }
91911
91912       sqlite3_reset(s);
91913     }
91914
91915     if( rc==SQLITE_OK ){
91916       if( doclist.nData>0 ){
91917         createDoclistResult(pContext, doclist.pData, doclist.nData);
91918       }else{
91919         /* TODO(shess): This can happen if the term is not present, or
91920         ** if all instances of the term have been deleted and this is
91921         ** an all-index dump.  It may be interesting to distinguish
91922         ** these cases.
91923         */
91924         sqlite3_result_text(pContext, "", 0, SQLITE_STATIC);
91925       }
91926     }else if( rc==SQLITE_NOMEM ){
91927       /* Handle out-of-memory cases specially because if they are
91928       ** generated in fts3 code they may not be reflected in the db
91929       ** handle.
91930       */
91931       /* TODO(shess): Handle this more comprehensively.
91932       ** sqlite3ErrStr() has what I need, but is internal.
91933       */
91934       generateError(pContext, "dump_doclist", "out of memory");
91935     }else{
91936       generateError(pContext, "dump_doclist", NULL);
91937     }
91938
91939     dataBufferDestroy(&doclist);
91940   }
91941 }
91942 #endif
91943
91944 /*
91945 ** This routine implements the xFindFunction method for the FTS3
91946 ** virtual table.
91947 */
91948 static int fulltextFindFunction(
91949   sqlite3_vtab *pVtab,
91950   int nArg,
91951   const char *zName,
91952   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
91953   void **ppArg
91954 ){
91955   if( strcmp(zName,"snippet")==0 ){
91956     *pxFunc = snippetFunc;
91957     return 1;
91958   }else if( strcmp(zName,"offsets")==0 ){
91959     *pxFunc = snippetOffsetsFunc;
91960     return 1;
91961   }else if( strcmp(zName,"optimize")==0 ){
91962     *pxFunc = optimizeFunc;
91963     return 1;
91964 #ifdef SQLITE_TEST
91965     /* NOTE(shess): These functions are present only for testing
91966     ** purposes.  No particular effort is made to optimize their
91967     ** execution or how they build their results.
91968     */
91969   }else if( strcmp(zName,"dump_terms")==0 ){
91970     /* fprintf(stderr, "Found dump_terms\n"); */
91971     *pxFunc = dumpTermsFunc;
91972     return 1;
91973   }else if( strcmp(zName,"dump_doclist")==0 ){
91974     /* fprintf(stderr, "Found dump_doclist\n"); */
91975     *pxFunc = dumpDoclistFunc;
91976     return 1;
91977 #endif
91978   }
91979   return 0;
91980 }
91981
91982 /*
91983 ** Rename an fts3 table.
91984 */
91985 static int fulltextRename(
91986   sqlite3_vtab *pVtab,
91987   const char *zName
91988 ){
91989   fulltext_vtab *p = (fulltext_vtab *)pVtab;
91990   int rc = SQLITE_NOMEM;
91991   char *zSql = sqlite3_mprintf(
91992     "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';"
91993     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';"
91994     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';"
91995     , p->zDb, p->zName, zName 
91996     , p->zDb, p->zName, zName 
91997     , p->zDb, p->zName, zName
91998   );
91999   if( zSql ){
92000     rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
92001     sqlite3_free(zSql);
92002   }
92003   return rc;
92004 }
92005
92006 static const sqlite3_module fts3Module = {
92007   /* iVersion      */ 0,
92008   /* xCreate       */ fulltextCreate,
92009   /* xConnect      */ fulltextConnect,
92010   /* xBestIndex    */ fulltextBestIndex,
92011   /* xDisconnect   */ fulltextDisconnect,
92012   /* xDestroy      */ fulltextDestroy,
92013   /* xOpen         */ fulltextOpen,
92014   /* xClose        */ fulltextClose,
92015   /* xFilter       */ fulltextFilter,
92016   /* xNext         */ fulltextNext,
92017   /* xEof          */ fulltextEof,
92018   /* xColumn       */ fulltextColumn,
92019   /* xRowid        */ fulltextRowid,
92020   /* xUpdate       */ fulltextUpdate,
92021   /* xBegin        */ fulltextBegin,
92022   /* xSync         */ fulltextSync,
92023   /* xCommit       */ fulltextCommit,
92024   /* xRollback     */ fulltextRollback,
92025   /* xFindFunction */ fulltextFindFunction,
92026   /* xRename */       fulltextRename,
92027 };
92028
92029 static void hashDestroy(void *p){
92030   fts3Hash *pHash = (fts3Hash *)p;
92031   sqlite3Fts3HashClear(pHash);
92032   sqlite3_free(pHash);
92033 }
92034
92035 /*
92036 ** The fts3 built-in tokenizers - "simple" and "porter" - are implemented
92037 ** in files fts3_tokenizer1.c and fts3_porter.c respectively. The following
92038 ** two forward declarations are for functions declared in these files
92039 ** used to retrieve the respective implementations.
92040 **
92041 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
92042 ** to by the argument to point a the "simple" tokenizer implementation.
92043 ** Function ...PorterTokenizerModule() sets *pModule to point to the
92044 ** porter tokenizer/stemmer implementation.
92045 */
92046 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
92047 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
92048 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
92049
92050 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, fts3Hash *, const char *);
92051
92052 /*
92053 ** Initialise the fts3 extension. If this extension is built as part
92054 ** of the sqlite library, then this function is called directly by
92055 ** SQLite. If fts3 is built as a dynamically loadable extension, this
92056 ** function is called by the sqlite3_extension_init() entry point.
92057 */
92058 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
92059   int rc = SQLITE_OK;
92060   fts3Hash *pHash = 0;
92061   const sqlite3_tokenizer_module *pSimple = 0;
92062   const sqlite3_tokenizer_module *pPorter = 0;
92063   const sqlite3_tokenizer_module *pIcu = 0;
92064
92065   sqlite3Fts3SimpleTokenizerModule(&pSimple);
92066   sqlite3Fts3PorterTokenizerModule(&pPorter);
92067 #ifdef SQLITE_ENABLE_ICU
92068   sqlite3Fts3IcuTokenizerModule(&pIcu);
92069 #endif
92070
92071   /* Allocate and initialise the hash-table used to store tokenizers. */
92072   pHash = sqlite3_malloc(sizeof(fts3Hash));
92073   if( !pHash ){
92074     rc = SQLITE_NOMEM;
92075   }else{
92076     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
92077   }
92078
92079   /* Load the built-in tokenizers into the hash table */
92080   if( rc==SQLITE_OK ){
92081     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
92082      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
92083      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
92084     ){
92085       rc = SQLITE_NOMEM;
92086     }
92087   }
92088
92089   /* Create the virtual table wrapper around the hash-table and overload 
92090   ** the two scalar functions. If this is successful, register the
92091   ** module with sqlite.
92092   */
92093   if( SQLITE_OK==rc 
92094    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
92095    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
92096    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", -1))
92097    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", -1))
92098 #ifdef SQLITE_TEST
92099    && SQLITE_OK==(rc = sqlite3_overload_function(db, "dump_terms", -1))
92100    && SQLITE_OK==(rc = sqlite3_overload_function(db, "dump_doclist", -1))
92101 #endif
92102   ){
92103     return sqlite3_create_module_v2(
92104         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
92105     );
92106   }
92107
92108   /* An error has occured. Delete the hash table and return the error code. */
92109   assert( rc!=SQLITE_OK );
92110   if( pHash ){
92111     sqlite3Fts3HashClear(pHash);
92112     sqlite3_free(pHash);
92113   }
92114   return rc;
92115 }
92116
92117 #if !SQLITE_CORE
92118 SQLITE_API int sqlite3_extension_init(
92119   sqlite3 *db, 
92120   char **pzErrMsg,
92121   const sqlite3_api_routines *pApi
92122 ){
92123   SQLITE_EXTENSION_INIT2(pApi)
92124   return sqlite3Fts3Init(db);
92125 }
92126 #endif
92127
92128 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
92129
92130 /************** End of fts3.c ************************************************/
92131 /************** Begin file fts3_hash.c ***************************************/
92132 /*
92133 ** 2001 September 22
92134 **
92135 ** The author disclaims copyright to this source code.  In place of
92136 ** a legal notice, here is a blessing:
92137 **
92138 **    May you do good and not evil.
92139 **    May you find forgiveness for yourself and forgive others.
92140 **    May you share freely, never taking more than you give.
92141 **
92142 *************************************************************************
92143 ** This is the implementation of generic hash-tables used in SQLite.
92144 ** We've modified it slightly to serve as a standalone hash table
92145 ** implementation for the full-text indexing module.
92146 */
92147
92148 /*
92149 ** The code in this file is only compiled if:
92150 **
92151 **     * The FTS3 module is being built as an extension
92152 **       (in which case SQLITE_CORE is not defined), or
92153 **
92154 **     * The FTS3 module is being built into the core of
92155 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
92156 */
92157 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
92158
92159
92160
92161 /*
92162 ** Malloc and Free functions
92163 */
92164 static void *fts3HashMalloc(int n){
92165   void *p = sqlite3_malloc(n);
92166   if( p ){
92167     memset(p, 0, n);
92168   }
92169   return p;
92170 }
92171 static void fts3HashFree(void *p){
92172   sqlite3_free(p);
92173 }
92174
92175 /* Turn bulk memory into a hash table object by initializing the
92176 ** fields of the Hash structure.
92177 **
92178 ** "pNew" is a pointer to the hash table that is to be initialized.
92179 ** keyClass is one of the constants 
92180 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
92181 ** determines what kind of key the hash table will use.  "copyKey" is
92182 ** true if the hash table should make its own private copy of keys and
92183 ** false if it should just use the supplied pointer.
92184 */
92185 SQLITE_PRIVATE void sqlite3Fts3HashInit(fts3Hash *pNew, int keyClass, int copyKey){
92186   assert( pNew!=0 );
92187   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
92188   pNew->keyClass = keyClass;
92189   pNew->copyKey = copyKey;
92190   pNew->first = 0;
92191   pNew->count = 0;
92192   pNew->htsize = 0;
92193   pNew->ht = 0;
92194 }
92195
92196 /* Remove all entries from a hash table.  Reclaim all memory.
92197 ** Call this routine to delete a hash table or to reset a hash table
92198 ** to the empty state.
92199 */
92200 SQLITE_PRIVATE void sqlite3Fts3HashClear(fts3Hash *pH){
92201   fts3HashElem *elem;         /* For looping over all elements of the table */
92202
92203   assert( pH!=0 );
92204   elem = pH->first;
92205   pH->first = 0;
92206   fts3HashFree(pH->ht);
92207   pH->ht = 0;
92208   pH->htsize = 0;
92209   while( elem ){
92210     fts3HashElem *next_elem = elem->next;
92211     if( pH->copyKey && elem->pKey ){
92212       fts3HashFree(elem->pKey);
92213     }
92214     fts3HashFree(elem);
92215     elem = next_elem;
92216   }
92217   pH->count = 0;
92218 }
92219
92220 /*
92221 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
92222 */
92223 static int fts3StrHash(const void *pKey, int nKey){
92224   const char *z = (const char *)pKey;
92225   int h = 0;
92226   if( nKey<=0 ) nKey = (int) strlen(z);
92227   while( nKey > 0  ){
92228     h = (h<<3) ^ h ^ *z++;
92229     nKey--;
92230   }
92231   return h & 0x7fffffff;
92232 }
92233 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
92234   if( n1!=n2 ) return 1;
92235   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
92236 }
92237
92238 /*
92239 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
92240 */
92241 static int fts3BinHash(const void *pKey, int nKey){
92242   int h = 0;
92243   const char *z = (const char *)pKey;
92244   while( nKey-- > 0 ){
92245     h = (h<<3) ^ h ^ *(z++);
92246   }
92247   return h & 0x7fffffff;
92248 }
92249 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
92250   if( n1!=n2 ) return 1;
92251   return memcmp(pKey1,pKey2,n1);
92252 }
92253
92254 /*
92255 ** Return a pointer to the appropriate hash function given the key class.
92256 **
92257 ** The C syntax in this function definition may be unfamilar to some 
92258 ** programmers, so we provide the following additional explanation:
92259 **
92260 ** The name of the function is "ftsHashFunction".  The function takes a
92261 ** single parameter "keyClass".  The return value of ftsHashFunction()
92262 ** is a pointer to another function.  Specifically, the return value
92263 ** of ftsHashFunction() is a pointer to a function that takes two parameters
92264 ** with types "const void*" and "int" and returns an "int".
92265 */
92266 static int (*ftsHashFunction(int keyClass))(const void*,int){
92267   if( keyClass==FTS3_HASH_STRING ){
92268     return &fts3StrHash;
92269   }else{
92270     assert( keyClass==FTS3_HASH_BINARY );
92271     return &fts3BinHash;
92272   }
92273 }
92274
92275 /*
92276 ** Return a pointer to the appropriate hash function given the key class.
92277 **
92278 ** For help in interpreted the obscure C code in the function definition,
92279 ** see the header comment on the previous function.
92280 */
92281 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
92282   if( keyClass==FTS3_HASH_STRING ){
92283     return &fts3StrCompare;
92284   }else{
92285     assert( keyClass==FTS3_HASH_BINARY );
92286     return &fts3BinCompare;
92287   }
92288 }
92289
92290 /* Link an element into the hash table
92291 */
92292 static void fts3HashInsertElement(
92293   fts3Hash *pH,            /* The complete hash table */
92294   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
92295   fts3HashElem *pNew       /* The element to be inserted */
92296 ){
92297   fts3HashElem *pHead;     /* First element already in pEntry */
92298   pHead = pEntry->chain;
92299   if( pHead ){
92300     pNew->next = pHead;
92301     pNew->prev = pHead->prev;
92302     if( pHead->prev ){ pHead->prev->next = pNew; }
92303     else             { pH->first = pNew; }
92304     pHead->prev = pNew;
92305   }else{
92306     pNew->next = pH->first;
92307     if( pH->first ){ pH->first->prev = pNew; }
92308     pNew->prev = 0;
92309     pH->first = pNew;
92310   }
92311   pEntry->count++;
92312   pEntry->chain = pNew;
92313 }
92314
92315
92316 /* Resize the hash table so that it cantains "new_size" buckets.
92317 ** "new_size" must be a power of 2.  The hash table might fail 
92318 ** to resize if sqliteMalloc() fails.
92319 */
92320 static void fts3Rehash(fts3Hash *pH, int new_size){
92321   struct _fts3ht *new_ht;          /* The new hash table */
92322   fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
92323   int (*xHash)(const void*,int);   /* The hash function */
92324
92325   assert( (new_size & (new_size-1))==0 );
92326   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
92327   if( new_ht==0 ) return;
92328   fts3HashFree(pH->ht);
92329   pH->ht = new_ht;
92330   pH->htsize = new_size;
92331   xHash = ftsHashFunction(pH->keyClass);
92332   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
92333     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
92334     next_elem = elem->next;
92335     fts3HashInsertElement(pH, &new_ht[h], elem);
92336   }
92337 }
92338
92339 /* This function (for internal use only) locates an element in an
92340 ** hash table that matches the given key.  The hash for this key has
92341 ** already been computed and is passed as the 4th parameter.
92342 */
92343 static fts3HashElem *fts3FindElementByHash(
92344   const fts3Hash *pH, /* The pH to be searched */
92345   const void *pKey,   /* The key we are searching for */
92346   int nKey,
92347   int h               /* The hash for this key. */
92348 ){
92349   fts3HashElem *elem;            /* Used to loop thru the element list */
92350   int count;                     /* Number of elements left to test */
92351   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
92352
92353   if( pH->ht ){
92354     struct _fts3ht *pEntry = &pH->ht[h];
92355     elem = pEntry->chain;
92356     count = pEntry->count;
92357     xCompare = ftsCompareFunction(pH->keyClass);
92358     while( count-- && elem ){
92359       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
92360         return elem;
92361       }
92362       elem = elem->next;
92363     }
92364   }
92365   return 0;
92366 }
92367
92368 /* Remove a single entry from the hash table given a pointer to that
92369 ** element and a hash on the element's key.
92370 */
92371 static void fts3RemoveElementByHash(
92372   fts3Hash *pH,         /* The pH containing "elem" */
92373   fts3HashElem* elem,   /* The element to be removed from the pH */
92374   int h                 /* Hash value for the element */
92375 ){
92376   struct _fts3ht *pEntry;
92377   if( elem->prev ){
92378     elem->prev->next = elem->next; 
92379   }else{
92380     pH->first = elem->next;
92381   }
92382   if( elem->next ){
92383     elem->next->prev = elem->prev;
92384   }
92385   pEntry = &pH->ht[h];
92386   if( pEntry->chain==elem ){
92387     pEntry->chain = elem->next;
92388   }
92389   pEntry->count--;
92390   if( pEntry->count<=0 ){
92391     pEntry->chain = 0;
92392   }
92393   if( pH->copyKey && elem->pKey ){
92394     fts3HashFree(elem->pKey);
92395   }
92396   fts3HashFree( elem );
92397   pH->count--;
92398   if( pH->count<=0 ){
92399     assert( pH->first==0 );
92400     assert( pH->count==0 );
92401     fts3HashClear(pH);
92402   }
92403 }
92404
92405 /* Attempt to locate an element of the hash table pH with a key
92406 ** that matches pKey,nKey.  Return the data for this element if it is
92407 ** found, or NULL if there is no match.
92408 */
92409 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const fts3Hash *pH, const void *pKey, int nKey){
92410   int h;                 /* A hash on key */
92411   fts3HashElem *elem;    /* The element that matches key */
92412   int (*xHash)(const void*,int);  /* The hash function */
92413
92414   if( pH==0 || pH->ht==0 ) return 0;
92415   xHash = ftsHashFunction(pH->keyClass);
92416   assert( xHash!=0 );
92417   h = (*xHash)(pKey,nKey);
92418   assert( (pH->htsize & (pH->htsize-1))==0 );
92419   elem = fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
92420   return elem ? elem->data : 0;
92421 }
92422
92423 /* Insert an element into the hash table pH.  The key is pKey,nKey
92424 ** and the data is "data".
92425 **
92426 ** If no element exists with a matching key, then a new
92427 ** element is created.  A copy of the key is made if the copyKey
92428 ** flag is set.  NULL is returned.
92429 **
92430 ** If another element already exists with the same key, then the
92431 ** new data replaces the old data and the old data is returned.
92432 ** The key is not copied in this instance.  If a malloc fails, then
92433 ** the new data is returned and the hash table is unchanged.
92434 **
92435 ** If the "data" parameter to this function is NULL, then the
92436 ** element corresponding to "key" is removed from the hash table.
92437 */
92438 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
92439   fts3Hash *pH,        /* The hash table to insert into */
92440   const void *pKey,    /* The key */
92441   int nKey,            /* Number of bytes in the key */
92442   void *data           /* The data */
92443 ){
92444   int hraw;                 /* Raw hash value of the key */
92445   int h;                    /* the hash of the key modulo hash table size */
92446   fts3HashElem *elem;       /* Used to loop thru the element list */
92447   fts3HashElem *new_elem;   /* New element added to the pH */
92448   int (*xHash)(const void*,int);  /* The hash function */
92449
92450   assert( pH!=0 );
92451   xHash = ftsHashFunction(pH->keyClass);
92452   assert( xHash!=0 );
92453   hraw = (*xHash)(pKey, nKey);
92454   assert( (pH->htsize & (pH->htsize-1))==0 );
92455   h = hraw & (pH->htsize-1);
92456   elem = fts3FindElementByHash(pH,pKey,nKey,h);
92457   if( elem ){
92458     void *old_data = elem->data;
92459     if( data==0 ){
92460       fts3RemoveElementByHash(pH,elem,h);
92461     }else{
92462       elem->data = data;
92463     }
92464     return old_data;
92465   }
92466   if( data==0 ) return 0;
92467   new_elem = (fts3HashElem*)fts3HashMalloc( sizeof(fts3HashElem) );
92468   if( new_elem==0 ) return data;
92469   if( pH->copyKey && pKey!=0 ){
92470     new_elem->pKey = fts3HashMalloc( nKey );
92471     if( new_elem->pKey==0 ){
92472       fts3HashFree(new_elem);
92473       return data;
92474     }
92475     memcpy((void*)new_elem->pKey, pKey, nKey);
92476   }else{
92477     new_elem->pKey = (void*)pKey;
92478   }
92479   new_elem->nKey = nKey;
92480   pH->count++;
92481   if( pH->htsize==0 ){
92482     fts3Rehash(pH,8);
92483     if( pH->htsize==0 ){
92484       pH->count = 0;
92485       fts3HashFree(new_elem);
92486       return data;
92487     }
92488   }
92489   if( pH->count > pH->htsize ){
92490     fts3Rehash(pH,pH->htsize*2);
92491   }
92492   assert( pH->htsize>0 );
92493   assert( (pH->htsize & (pH->htsize-1))==0 );
92494   h = hraw & (pH->htsize-1);
92495   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
92496   new_elem->data = data;
92497   return 0;
92498 }
92499
92500 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
92501
92502 /************** End of fts3_hash.c *******************************************/
92503 /************** Begin file fts3_porter.c *************************************/
92504 /*
92505 ** 2006 September 30
92506 **
92507 ** The author disclaims copyright to this source code.  In place of
92508 ** a legal notice, here is a blessing:
92509 **
92510 **    May you do good and not evil.
92511 **    May you find forgiveness for yourself and forgive others.
92512 **    May you share freely, never taking more than you give.
92513 **
92514 *************************************************************************
92515 ** Implementation of the full-text-search tokenizer that implements
92516 ** a Porter stemmer.
92517 */
92518
92519 /*
92520 ** The code in this file is only compiled if:
92521 **
92522 **     * The FTS3 module is being built as an extension
92523 **       (in which case SQLITE_CORE is not defined), or
92524 **
92525 **     * The FTS3 module is being built into the core of
92526 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
92527 */
92528 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
92529
92530
92531
92532
92533 /*
92534 ** Class derived from sqlite3_tokenizer
92535 */
92536 typedef struct porter_tokenizer {
92537   sqlite3_tokenizer base;      /* Base class */
92538 } porter_tokenizer;
92539
92540 /*
92541 ** Class derived from sqlit3_tokenizer_cursor
92542 */
92543 typedef struct porter_tokenizer_cursor {
92544   sqlite3_tokenizer_cursor base;
92545   const char *zInput;          /* input we are tokenizing */
92546   int nInput;                  /* size of the input */
92547   int iOffset;                 /* current position in zInput */
92548   int iToken;                  /* index of next token to be returned */
92549   char *zToken;                /* storage for current token */
92550   int nAllocated;              /* space allocated to zToken buffer */
92551 } porter_tokenizer_cursor;
92552
92553
92554 /* Forward declaration */
92555 static const sqlite3_tokenizer_module porterTokenizerModule;
92556
92557
92558 /*
92559 ** Create a new tokenizer instance.
92560 */
92561 static int porterCreate(
92562   int argc, const char * const *argv,
92563   sqlite3_tokenizer **ppTokenizer
92564 ){
92565   porter_tokenizer *t;
92566   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
92567   if( t==NULL ) return SQLITE_NOMEM;
92568   memset(t, 0, sizeof(*t));
92569   *ppTokenizer = &t->base;
92570   return SQLITE_OK;
92571 }
92572
92573 /*
92574 ** Destroy a tokenizer
92575 */
92576 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
92577   sqlite3_free(pTokenizer);
92578   return SQLITE_OK;
92579 }
92580
92581 /*
92582 ** Prepare to begin tokenizing a particular string.  The input
92583 ** string to be tokenized is zInput[0..nInput-1].  A cursor
92584 ** used to incrementally tokenize this string is returned in 
92585 ** *ppCursor.
92586 */
92587 static int porterOpen(
92588   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
92589   const char *zInput, int nInput,        /* String to be tokenized */
92590   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
92591 ){
92592   porter_tokenizer_cursor *c;
92593
92594   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
92595   if( c==NULL ) return SQLITE_NOMEM;
92596
92597   c->zInput = zInput;
92598   if( zInput==0 ){
92599     c->nInput = 0;
92600   }else if( nInput<0 ){
92601     c->nInput = (int)strlen(zInput);
92602   }else{
92603     c->nInput = nInput;
92604   }
92605   c->iOffset = 0;                 /* start tokenizing at the beginning */
92606   c->iToken = 0;
92607   c->zToken = NULL;               /* no space allocated, yet. */
92608   c->nAllocated = 0;
92609
92610   *ppCursor = &c->base;
92611   return SQLITE_OK;
92612 }
92613
92614 /*
92615 ** Close a tokenization cursor previously opened by a call to
92616 ** porterOpen() above.
92617 */
92618 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
92619   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
92620   sqlite3_free(c->zToken);
92621   sqlite3_free(c);
92622   return SQLITE_OK;
92623 }
92624 /*
92625 ** Vowel or consonant
92626 */
92627 static const char cType[] = {
92628    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
92629    1, 1, 1, 2, 1
92630 };
92631
92632 /*
92633 ** isConsonant() and isVowel() determine if their first character in
92634 ** the string they point to is a consonant or a vowel, according
92635 ** to Porter ruls.  
92636 **
92637 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
92638 ** 'Y' is a consonant unless it follows another consonant,
92639 ** in which case it is a vowel.
92640 **
92641 ** In these routine, the letters are in reverse order.  So the 'y' rule
92642 ** is that 'y' is a consonant unless it is followed by another
92643 ** consonent.
92644 */
92645 static int isVowel(const char*);
92646 static int isConsonant(const char *z){
92647   int j;
92648   char x = *z;
92649   if( x==0 ) return 0;
92650   assert( x>='a' && x<='z' );
92651   j = cType[x-'a'];
92652   if( j<2 ) return j;
92653   return z[1]==0 || isVowel(z + 1);
92654 }
92655 static int isVowel(const char *z){
92656   int j;
92657   char x = *z;
92658   if( x==0 ) return 0;
92659   assert( x>='a' && x<='z' );
92660   j = cType[x-'a'];
92661   if( j<2 ) return 1-j;
92662   return isConsonant(z + 1);
92663 }
92664
92665 /*
92666 ** Let any sequence of one or more vowels be represented by V and let
92667 ** C be sequence of one or more consonants.  Then every word can be
92668 ** represented as:
92669 **
92670 **           [C] (VC){m} [V]
92671 **
92672 ** In prose:  A word is an optional consonant followed by zero or
92673 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
92674 ** number of vowel consonant pairs.  This routine computes the value
92675 ** of m for the first i bytes of a word.
92676 **
92677 ** Return true if the m-value for z is 1 or more.  In other words,
92678 ** return true if z contains at least one vowel that is followed
92679 ** by a consonant.
92680 **
92681 ** In this routine z[] is in reverse order.  So we are really looking
92682 ** for an instance of of a consonant followed by a vowel.
92683 */
92684 static int m_gt_0(const char *z){
92685   while( isVowel(z) ){ z++; }
92686   if( *z==0 ) return 0;
92687   while( isConsonant(z) ){ z++; }
92688   return *z!=0;
92689 }
92690
92691 /* Like mgt0 above except we are looking for a value of m which is
92692 ** exactly 1
92693 */
92694 static int m_eq_1(const char *z){
92695   while( isVowel(z) ){ z++; }
92696   if( *z==0 ) return 0;
92697   while( isConsonant(z) ){ z++; }
92698   if( *z==0 ) return 0;
92699   while( isVowel(z) ){ z++; }
92700   if( *z==0 ) return 1;
92701   while( isConsonant(z) ){ z++; }
92702   return *z==0;
92703 }
92704
92705 /* Like mgt0 above except we are looking for a value of m>1 instead
92706 ** or m>0
92707 */
92708 static int m_gt_1(const char *z){
92709   while( isVowel(z) ){ z++; }
92710   if( *z==0 ) return 0;
92711   while( isConsonant(z) ){ z++; }
92712   if( *z==0 ) return 0;
92713   while( isVowel(z) ){ z++; }
92714   if( *z==0 ) return 0;
92715   while( isConsonant(z) ){ z++; }
92716   return *z!=0;
92717 }
92718
92719 /*
92720 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
92721 */
92722 static int hasVowel(const char *z){
92723   while( isConsonant(z) ){ z++; }
92724   return *z!=0;
92725 }
92726
92727 /*
92728 ** Return TRUE if the word ends in a double consonant.
92729 **
92730 ** The text is reversed here. So we are really looking at
92731 ** the first two characters of z[].
92732 */
92733 static int doubleConsonant(const char *z){
92734   return isConsonant(z) && z[0]==z[1] && isConsonant(z+1);
92735 }
92736
92737 /*
92738 ** Return TRUE if the word ends with three letters which
92739 ** are consonant-vowel-consonent and where the final consonant
92740 ** is not 'w', 'x', or 'y'.
92741 **
92742 ** The word is reversed here.  So we are really checking the
92743 ** first three letters and the first one cannot be in [wxy].
92744 */
92745 static int star_oh(const char *z){
92746   return
92747     z[0]!=0 && isConsonant(z) &&
92748     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
92749     z[1]!=0 && isVowel(z+1) &&
92750     z[2]!=0 && isConsonant(z+2);
92751 }
92752
92753 /*
92754 ** If the word ends with zFrom and xCond() is true for the stem
92755 ** of the word that preceeds the zFrom ending, then change the 
92756 ** ending to zTo.
92757 **
92758 ** The input word *pz and zFrom are both in reverse order.  zTo
92759 ** is in normal order. 
92760 **
92761 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
92762 ** match.  Not that TRUE is returned even if xCond() fails and
92763 ** no substitution occurs.
92764 */
92765 static int stem(
92766   char **pz,             /* The word being stemmed (Reversed) */
92767   const char *zFrom,     /* If the ending matches this... (Reversed) */
92768   const char *zTo,       /* ... change the ending to this (not reversed) */
92769   int (*xCond)(const char*)   /* Condition that must be true */
92770 ){
92771   char *z = *pz;
92772   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
92773   if( *zFrom!=0 ) return 0;
92774   if( xCond && !xCond(z) ) return 1;
92775   while( *zTo ){
92776     *(--z) = *(zTo++);
92777   }
92778   *pz = z;
92779   return 1;
92780 }
92781
92782 /*
92783 ** This is the fallback stemmer used when the porter stemmer is
92784 ** inappropriate.  The input word is copied into the output with
92785 ** US-ASCII case folding.  If the input word is too long (more
92786 ** than 20 bytes if it contains no digits or more than 6 bytes if
92787 ** it contains digits) then word is truncated to 20 or 6 bytes
92788 ** by taking 10 or 3 bytes from the beginning and end.
92789 */
92790 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
92791   int i, mx, j;
92792   int hasDigit = 0;
92793   for(i=0; i<nIn; i++){
92794     int c = zIn[i];
92795     if( c>='A' && c<='Z' ){
92796       zOut[i] = c - 'A' + 'a';
92797     }else{
92798       if( c>='0' && c<='9' ) hasDigit = 1;
92799       zOut[i] = c;
92800     }
92801   }
92802   mx = hasDigit ? 3 : 10;
92803   if( nIn>mx*2 ){
92804     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
92805       zOut[j] = zOut[i];
92806     }
92807     i = j;
92808   }
92809   zOut[i] = 0;
92810   *pnOut = i;
92811 }
92812
92813
92814 /*
92815 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
92816 ** zOut is at least big enough to hold nIn bytes.  Write the actual
92817 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
92818 **
92819 ** Any upper-case characters in the US-ASCII character set ([A-Z])
92820 ** are converted to lower case.  Upper-case UTF characters are
92821 ** unchanged.
92822 **
92823 ** Words that are longer than about 20 bytes are stemmed by retaining
92824 ** a few bytes from the beginning and the end of the word.  If the
92825 ** word contains digits, 3 bytes are taken from the beginning and
92826 ** 3 bytes from the end.  For long words without digits, 10 bytes
92827 ** are taken from each end.  US-ASCII case folding still applies.
92828 ** 
92829 ** If the input word contains not digits but does characters not 
92830 ** in [a-zA-Z] then no stemming is attempted and this routine just 
92831 ** copies the input into the input into the output with US-ASCII
92832 ** case folding.
92833 **
92834 ** Stemming never increases the length of the word.  So there is
92835 ** no chance of overflowing the zOut buffer.
92836 */
92837 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
92838   int i, j, c;
92839   char zReverse[28];
92840   char *z, *z2;
92841   if( nIn<3 || nIn>=sizeof(zReverse)-7 ){
92842     /* The word is too big or too small for the porter stemmer.
92843     ** Fallback to the copy stemmer */
92844     copy_stemmer(zIn, nIn, zOut, pnOut);
92845     return;
92846   }
92847   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
92848     c = zIn[i];
92849     if( c>='A' && c<='Z' ){
92850       zReverse[j] = c + 'a' - 'A';
92851     }else if( c>='a' && c<='z' ){
92852       zReverse[j] = c;
92853     }else{
92854       /* The use of a character not in [a-zA-Z] means that we fallback
92855       ** to the copy stemmer */
92856       copy_stemmer(zIn, nIn, zOut, pnOut);
92857       return;
92858     }
92859   }
92860   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
92861   z = &zReverse[j+1];
92862
92863
92864   /* Step 1a */
92865   if( z[0]=='s' ){
92866     if(
92867      !stem(&z, "sess", "ss", 0) &&
92868      !stem(&z, "sei", "i", 0)  &&
92869      !stem(&z, "ss", "ss", 0)
92870     ){
92871       z++;
92872     }
92873   }
92874
92875   /* Step 1b */  
92876   z2 = z;
92877   if( stem(&z, "dee", "ee", m_gt_0) ){
92878     /* Do nothing.  The work was all in the test */
92879   }else if( 
92880      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
92881       && z!=z2
92882   ){
92883      if( stem(&z, "ta", "ate", 0) ||
92884          stem(&z, "lb", "ble", 0) ||
92885          stem(&z, "zi", "ize", 0) ){
92886        /* Do nothing.  The work was all in the test */
92887      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
92888        z++;
92889      }else if( m_eq_1(z) && star_oh(z) ){
92890        *(--z) = 'e';
92891      }
92892   }
92893
92894   /* Step 1c */
92895   if( z[0]=='y' && hasVowel(z+1) ){
92896     z[0] = 'i';
92897   }
92898
92899   /* Step 2 */
92900   switch( z[1] ){
92901    case 'a':
92902      stem(&z, "lanoita", "ate", m_gt_0) ||
92903      stem(&z, "lanoit", "tion", m_gt_0);
92904      break;
92905    case 'c':
92906      stem(&z, "icne", "ence", m_gt_0) ||
92907      stem(&z, "icna", "ance", m_gt_0);
92908      break;
92909    case 'e':
92910      stem(&z, "rezi", "ize", m_gt_0);
92911      break;
92912    case 'g':
92913      stem(&z, "igol", "log", m_gt_0);
92914      break;
92915    case 'l':
92916      stem(&z, "ilb", "ble", m_gt_0) ||
92917      stem(&z, "illa", "al", m_gt_0) ||
92918      stem(&z, "iltne", "ent", m_gt_0) ||
92919      stem(&z, "ile", "e", m_gt_0) ||
92920      stem(&z, "ilsuo", "ous", m_gt_0);
92921      break;
92922    case 'o':
92923      stem(&z, "noitazi", "ize", m_gt_0) ||
92924      stem(&z, "noita", "ate", m_gt_0) ||
92925      stem(&z, "rota", "ate", m_gt_0);
92926      break;
92927    case 's':
92928      stem(&z, "msila", "al", m_gt_0) ||
92929      stem(&z, "ssenevi", "ive", m_gt_0) ||
92930      stem(&z, "ssenluf", "ful", m_gt_0) ||
92931      stem(&z, "ssensuo", "ous", m_gt_0);
92932      break;
92933    case 't':
92934      stem(&z, "itila", "al", m_gt_0) ||
92935      stem(&z, "itivi", "ive", m_gt_0) ||
92936      stem(&z, "itilib", "ble", m_gt_0);
92937      break;
92938   }
92939
92940   /* Step 3 */
92941   switch( z[0] ){
92942    case 'e':
92943      stem(&z, "etaci", "ic", m_gt_0) ||
92944      stem(&z, "evita", "", m_gt_0)   ||
92945      stem(&z, "ezila", "al", m_gt_0);
92946      break;
92947    case 'i':
92948      stem(&z, "itici", "ic", m_gt_0);
92949      break;
92950    case 'l':
92951      stem(&z, "laci", "ic", m_gt_0) ||
92952      stem(&z, "luf", "", m_gt_0);
92953      break;
92954    case 's':
92955      stem(&z, "ssen", "", m_gt_0);
92956      break;
92957   }
92958
92959   /* Step 4 */
92960   switch( z[1] ){
92961    case 'a':
92962      if( z[0]=='l' && m_gt_1(z+2) ){
92963        z += 2;
92964      }
92965      break;
92966    case 'c':
92967      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
92968        z += 4;
92969      }
92970      break;
92971    case 'e':
92972      if( z[0]=='r' && m_gt_1(z+2) ){
92973        z += 2;
92974      }
92975      break;
92976    case 'i':
92977      if( z[0]=='c' && m_gt_1(z+2) ){
92978        z += 2;
92979      }
92980      break;
92981    case 'l':
92982      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
92983        z += 4;
92984      }
92985      break;
92986    case 'n':
92987      if( z[0]=='t' ){
92988        if( z[2]=='a' ){
92989          if( m_gt_1(z+3) ){
92990            z += 3;
92991          }
92992        }else if( z[2]=='e' ){
92993          stem(&z, "tneme", "", m_gt_1) ||
92994          stem(&z, "tnem", "", m_gt_1) ||
92995          stem(&z, "tne", "", m_gt_1);
92996        }
92997      }
92998      break;
92999    case 'o':
93000      if( z[0]=='u' ){
93001        if( m_gt_1(z+2) ){
93002          z += 2;
93003        }
93004      }else if( z[3]=='s' || z[3]=='t' ){
93005        stem(&z, "noi", "", m_gt_1);
93006      }
93007      break;
93008    case 's':
93009      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
93010        z += 3;
93011      }
93012      break;
93013    case 't':
93014      stem(&z, "eta", "", m_gt_1) ||
93015      stem(&z, "iti", "", m_gt_1);
93016      break;
93017    case 'u':
93018      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
93019        z += 3;
93020      }
93021      break;
93022    case 'v':
93023    case 'z':
93024      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
93025        z += 3;
93026      }
93027      break;
93028   }
93029
93030   /* Step 5a */
93031   if( z[0]=='e' ){
93032     if( m_gt_1(z+1) ){
93033       z++;
93034     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
93035       z++;
93036     }
93037   }
93038
93039   /* Step 5b */
93040   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
93041     z++;
93042   }
93043
93044   /* z[] is now the stemmed word in reverse order.  Flip it back
93045   ** around into forward order and return.
93046   */
93047   *pnOut = i = strlen(z);
93048   zOut[i] = 0;
93049   while( *z ){
93050     zOut[--i] = *(z++);
93051   }
93052 }
93053
93054 /*
93055 ** Characters that can be part of a token.  We assume any character
93056 ** whose value is greater than 0x80 (any UTF character) can be
93057 ** part of a token.  In other words, delimiters all must have
93058 ** values of 0x7f or lower.
93059 */
93060 static const char porterIdChar[] = {
93061 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
93062     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
93063     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
93064     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
93065     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
93066     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
93067 };
93068 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
93069
93070 /*
93071 ** Extract the next token from a tokenization cursor.  The cursor must
93072 ** have been opened by a prior call to porterOpen().
93073 */
93074 static int porterNext(
93075   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
93076   const char **pzToken,               /* OUT: *pzToken is the token text */
93077   int *pnBytes,                       /* OUT: Number of bytes in token */
93078   int *piStartOffset,                 /* OUT: Starting offset of token */
93079   int *piEndOffset,                   /* OUT: Ending offset of token */
93080   int *piPosition                     /* OUT: Position integer of token */
93081 ){
93082   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
93083   const char *z = c->zInput;
93084
93085   while( c->iOffset<c->nInput ){
93086     int iStartOffset, ch;
93087
93088     /* Scan past delimiter characters */
93089     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
93090       c->iOffset++;
93091     }
93092
93093     /* Count non-delimiter characters. */
93094     iStartOffset = c->iOffset;
93095     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
93096       c->iOffset++;
93097     }
93098
93099     if( c->iOffset>iStartOffset ){
93100       int n = c->iOffset-iStartOffset;
93101       if( n>c->nAllocated ){
93102         c->nAllocated = n+20;
93103         c->zToken = sqlite3_realloc(c->zToken, c->nAllocated);
93104         if( c->zToken==NULL ) return SQLITE_NOMEM;
93105       }
93106       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
93107       *pzToken = c->zToken;
93108       *piStartOffset = iStartOffset;
93109       *piEndOffset = c->iOffset;
93110       *piPosition = c->iToken++;
93111       return SQLITE_OK;
93112     }
93113   }
93114   return SQLITE_DONE;
93115 }
93116
93117 /*
93118 ** The set of routines that implement the porter-stemmer tokenizer
93119 */
93120 static const sqlite3_tokenizer_module porterTokenizerModule = {
93121   0,
93122   porterCreate,
93123   porterDestroy,
93124   porterOpen,
93125   porterClose,
93126   porterNext,
93127 };
93128
93129 /*
93130 ** Allocate a new porter tokenizer.  Return a pointer to the new
93131 ** tokenizer in *ppModule
93132 */
93133 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
93134   sqlite3_tokenizer_module const**ppModule
93135 ){
93136   *ppModule = &porterTokenizerModule;
93137 }
93138
93139 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
93140
93141 /************** End of fts3_porter.c *****************************************/
93142 /************** Begin file fts3_tokenizer.c **********************************/
93143 /*
93144 ** 2007 June 22
93145 **
93146 ** The author disclaims copyright to this source code.  In place of
93147 ** a legal notice, here is a blessing:
93148 **
93149 **    May you do good and not evil.
93150 **    May you find forgiveness for yourself and forgive others.
93151 **    May you share freely, never taking more than you give.
93152 **
93153 ******************************************************************************
93154 **
93155 ** This is part of an SQLite module implementing full-text search.
93156 ** This particular file implements the generic tokenizer interface.
93157 */
93158
93159 /*
93160 ** The code in this file is only compiled if:
93161 **
93162 **     * The FTS3 module is being built as an extension
93163 **       (in which case SQLITE_CORE is not defined), or
93164 **
93165 **     * The FTS3 module is being built into the core of
93166 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
93167 */
93168 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
93169
93170 #ifndef SQLITE_CORE
93171   SQLITE_EXTENSION_INIT1
93172 #endif
93173
93174
93175 /*
93176 ** Implementation of the SQL scalar function for accessing the underlying 
93177 ** hash table. This function may be called as follows:
93178 **
93179 **   SELECT <function-name>(<key-name>);
93180 **   SELECT <function-name>(<key-name>, <pointer>);
93181 **
93182 ** where <function-name> is the name passed as the second argument
93183 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
93184 **
93185 ** If the <pointer> argument is specified, it must be a blob value
93186 ** containing a pointer to be stored as the hash data corresponding
93187 ** to the string <key-name>. If <pointer> is not specified, then
93188 ** the string <key-name> must already exist in the has table. Otherwise,
93189 ** an error is returned.
93190 **
93191 ** Whether or not the <pointer> argument is specified, the value returned
93192 ** is a blob containing the pointer stored as the hash data corresponding
93193 ** to string <key-name> (after the hash-table is updated, if applicable).
93194 */
93195 static void scalarFunc(
93196   sqlite3_context *context,
93197   int argc,
93198   sqlite3_value **argv
93199 ){
93200   fts3Hash *pHash;
93201   void *pPtr = 0;
93202   const unsigned char *zName;
93203   int nName;
93204
93205   assert( argc==1 || argc==2 );
93206
93207   pHash = (fts3Hash *)sqlite3_user_data(context);
93208
93209   zName = sqlite3_value_text(argv[0]);
93210   nName = sqlite3_value_bytes(argv[0])+1;
93211
93212   if( argc==2 ){
93213     void *pOld;
93214     int n = sqlite3_value_bytes(argv[1]);
93215     if( n!=sizeof(pPtr) ){
93216       sqlite3_result_error(context, "argument type mismatch", -1);
93217       return;
93218     }
93219     pPtr = *(void **)sqlite3_value_blob(argv[1]);
93220     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
93221     if( pOld==pPtr ){
93222       sqlite3_result_error(context, "out of memory", -1);
93223       return;
93224     }
93225   }else{
93226     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
93227     if( !pPtr ){
93228       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
93229       sqlite3_result_error(context, zErr, -1);
93230       sqlite3_free(zErr);
93231       return;
93232     }
93233   }
93234
93235   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
93236 }
93237
93238 #ifdef SQLITE_TEST
93239
93240
93241 /*
93242 ** Implementation of a special SQL scalar function for testing tokenizers 
93243 ** designed to be used in concert with the Tcl testing framework. This
93244 ** function must be called with two arguments:
93245 **
93246 **   SELECT <function-name>(<key-name>, <input-string>);
93247 **   SELECT <function-name>(<key-name>, <pointer>);
93248 **
93249 ** where <function-name> is the name passed as the second argument
93250 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
93251 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
93252 **
93253 ** The return value is a string that may be interpreted as a Tcl
93254 ** list. For each token in the <input-string>, three elements are
93255 ** added to the returned list. The first is the token position, the 
93256 ** second is the token text (folded, stemmed, etc.) and the third is the
93257 ** substring of <input-string> associated with the token. For example, 
93258 ** using the built-in "simple" tokenizer:
93259 **
93260 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
93261 **
93262 ** will return the string:
93263 **
93264 **   "{0 i I 1 dont don't 2 see see 3 how how}"
93265 **   
93266 */
93267 static void testFunc(
93268   sqlite3_context *context,
93269   int argc,
93270   sqlite3_value **argv
93271 ){
93272   fts3Hash *pHash;
93273   sqlite3_tokenizer_module *p;
93274   sqlite3_tokenizer *pTokenizer = 0;
93275   sqlite3_tokenizer_cursor *pCsr = 0;
93276
93277   const char *zErr = 0;
93278
93279   const char *zName;
93280   int nName;
93281   const char *zInput;
93282   int nInput;
93283
93284   const char *zArg = 0;
93285
93286   const char *zToken;
93287   int nToken;
93288   int iStart;
93289   int iEnd;
93290   int iPos;
93291
93292   Tcl_Obj *pRet;
93293
93294   assert( argc==2 || argc==3 );
93295
93296   nName = sqlite3_value_bytes(argv[0]);
93297   zName = (const char *)sqlite3_value_text(argv[0]);
93298   nInput = sqlite3_value_bytes(argv[argc-1]);
93299   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
93300
93301   if( argc==3 ){
93302     zArg = (const char *)sqlite3_value_text(argv[1]);
93303   }
93304
93305   pHash = (fts3Hash *)sqlite3_user_data(context);
93306   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
93307
93308   if( !p ){
93309     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
93310     sqlite3_result_error(context, zErr, -1);
93311     sqlite3_free(zErr);
93312     return;
93313   }
93314
93315   pRet = Tcl_NewObj();
93316   Tcl_IncrRefCount(pRet);
93317
93318   if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
93319     zErr = "error in xCreate()";
93320     goto finish;
93321   }
93322   pTokenizer->pModule = p;
93323   if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
93324     zErr = "error in xOpen()";
93325     goto finish;
93326   }
93327   pCsr->pTokenizer = pTokenizer;
93328
93329   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
93330     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
93331     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
93332     zToken = &zInput[iStart];
93333     nToken = iEnd-iStart;
93334     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
93335   }
93336
93337   if( SQLITE_OK!=p->xClose(pCsr) ){
93338     zErr = "error in xClose()";
93339     goto finish;
93340   }
93341   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
93342     zErr = "error in xDestroy()";
93343     goto finish;
93344   }
93345
93346 finish:
93347   if( zErr ){
93348     sqlite3_result_error(context, zErr, -1);
93349   }else{
93350     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
93351   }
93352   Tcl_DecrRefCount(pRet);
93353 }
93354
93355 static
93356 int registerTokenizer(
93357   sqlite3 *db, 
93358   char *zName, 
93359   const sqlite3_tokenizer_module *p
93360 ){
93361   int rc;
93362   sqlite3_stmt *pStmt;
93363   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
93364
93365   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
93366   if( rc!=SQLITE_OK ){
93367     return rc;
93368   }
93369
93370   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
93371   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
93372   sqlite3_step(pStmt);
93373
93374   return sqlite3_finalize(pStmt);
93375 }
93376
93377 static
93378 int queryTokenizer(
93379   sqlite3 *db, 
93380   char *zName,  
93381   const sqlite3_tokenizer_module **pp
93382 ){
93383   int rc;
93384   sqlite3_stmt *pStmt;
93385   const char zSql[] = "SELECT fts3_tokenizer(?)";
93386
93387   *pp = 0;
93388   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
93389   if( rc!=SQLITE_OK ){
93390     return rc;
93391   }
93392
93393   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
93394   if( SQLITE_ROW==sqlite3_step(pStmt) ){
93395     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
93396       memcpy(pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
93397     }
93398   }
93399
93400   return sqlite3_finalize(pStmt);
93401 }
93402
93403 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
93404
93405 /*
93406 ** Implementation of the scalar function fts3_tokenizer_internal_test().
93407 ** This function is used for testing only, it is not included in the
93408 ** build unless SQLITE_TEST is defined.
93409 **
93410 ** The purpose of this is to test that the fts3_tokenizer() function
93411 ** can be used as designed by the C-code in the queryTokenizer and
93412 ** registerTokenizer() functions above. These two functions are repeated
93413 ** in the README.tokenizer file as an example, so it is important to
93414 ** test them.
93415 **
93416 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
93417 ** function with no arguments. An assert() will fail if a problem is
93418 ** detected. i.e.:
93419 **
93420 **     SELECT fts3_tokenizer_internal_test();
93421 **
93422 */
93423 static void intTestFunc(
93424   sqlite3_context *context,
93425   int argc,
93426   sqlite3_value **argv
93427 ){
93428   int rc;
93429   const sqlite3_tokenizer_module *p1;
93430   const sqlite3_tokenizer_module *p2;
93431   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
93432
93433   /* Test the query function */
93434   sqlite3Fts3SimpleTokenizerModule(&p1);
93435   rc = queryTokenizer(db, "simple", &p2);
93436   assert( rc==SQLITE_OK );
93437   assert( p1==p2 );
93438   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
93439   assert( rc==SQLITE_ERROR );
93440   assert( p2==0 );
93441   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
93442
93443   /* Test the storage function */
93444   rc = registerTokenizer(db, "nosuchtokenizer", p1);
93445   assert( rc==SQLITE_OK );
93446   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
93447   assert( rc==SQLITE_OK );
93448   assert( p2==p1 );
93449
93450   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
93451 }
93452
93453 #endif
93454
93455 /*
93456 ** Set up SQL objects in database db used to access the contents of
93457 ** the hash table pointed to by argument pHash. The hash table must
93458 ** been initialised to use string keys, and to take a private copy 
93459 ** of the key when a value is inserted. i.e. by a call similar to:
93460 **
93461 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
93462 **
93463 ** This function adds a scalar function (see header comment above
93464 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
93465 ** defined at compilation time, a temporary virtual table (see header 
93466 ** comment above struct HashTableVtab) to the database schema. Both 
93467 ** provide read/write access to the contents of *pHash.
93468 **
93469 ** The third argument to this function, zName, is used as the name
93470 ** of both the scalar and, if created, the virtual table.
93471 */
93472 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
93473   sqlite3 *db, 
93474   fts3Hash *pHash, 
93475   const char *zName
93476 ){
93477   int rc = SQLITE_OK;
93478   void *p = (void *)pHash;
93479   const int any = SQLITE_ANY;
93480   char *zTest = 0;
93481   char *zTest2 = 0;
93482
93483 #ifdef SQLITE_TEST
93484   void *pdb = (void *)db;
93485   zTest = sqlite3_mprintf("%s_test", zName);
93486   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
93487   if( !zTest || !zTest2 ){
93488     rc = SQLITE_NOMEM;
93489   }
93490 #endif
93491
93492   if( rc!=SQLITE_OK
93493    || (rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0))
93494    || (rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0))
93495 #ifdef SQLITE_TEST
93496    || (rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0))
93497    || (rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0))
93498    || (rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0))
93499 #endif
93500   );
93501
93502   sqlite3_free(zTest);
93503   sqlite3_free(zTest2);
93504   return rc;
93505 }
93506
93507 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
93508
93509 /************** End of fts3_tokenizer.c **************************************/
93510 /************** Begin file fts3_tokenizer1.c *********************************/
93511 /*
93512 ** 2006 Oct 10
93513 **
93514 ** The author disclaims copyright to this source code.  In place of
93515 ** a legal notice, here is a blessing:
93516 **
93517 **    May you do good and not evil.
93518 **    May you find forgiveness for yourself and forgive others.
93519 **    May you share freely, never taking more than you give.
93520 **
93521 ******************************************************************************
93522 **
93523 ** Implementation of the "simple" full-text-search tokenizer.
93524 */
93525
93526 /*
93527 ** The code in this file is only compiled if:
93528 **
93529 **     * The FTS3 module is being built as an extension
93530 **       (in which case SQLITE_CORE is not defined), or
93531 **
93532 **     * The FTS3 module is being built into the core of
93533 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
93534 */
93535 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
93536
93537
93538
93539
93540 typedef struct simple_tokenizer {
93541   sqlite3_tokenizer base;
93542   char delim[128];             /* flag ASCII delimiters */
93543 } simple_tokenizer;
93544
93545 typedef struct simple_tokenizer_cursor {
93546   sqlite3_tokenizer_cursor base;
93547   const char *pInput;          /* input we are tokenizing */
93548   int nBytes;                  /* size of the input */
93549   int iOffset;                 /* current position in pInput */
93550   int iToken;                  /* index of next token to be returned */
93551   char *pToken;                /* storage for current token */
93552   int nTokenAllocated;         /* space allocated to zToken buffer */
93553 } simple_tokenizer_cursor;
93554
93555
93556 /* Forward declaration */
93557 static const sqlite3_tokenizer_module simpleTokenizerModule;
93558
93559 static int simpleDelim(simple_tokenizer *t, unsigned char c){
93560   return c<0x80 && t->delim[c];
93561 }
93562
93563 /*
93564 ** Create a new tokenizer instance.
93565 */
93566 static int simpleCreate(
93567   int argc, const char * const *argv,
93568   sqlite3_tokenizer **ppTokenizer
93569 ){
93570   simple_tokenizer *t;
93571
93572   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
93573   if( t==NULL ) return SQLITE_NOMEM;
93574   memset(t, 0, sizeof(*t));
93575
93576   /* TODO(shess) Delimiters need to remain the same from run to run,
93577   ** else we need to reindex.  One solution would be a meta-table to
93578   ** track such information in the database, then we'd only want this
93579   ** information on the initial create.
93580   */
93581   if( argc>1 ){
93582     int i, n = strlen(argv[1]);
93583     for(i=0; i<n; i++){
93584       unsigned char ch = argv[1][i];
93585       /* We explicitly don't support UTF-8 delimiters for now. */
93586       if( ch>=0x80 ){
93587         sqlite3_free(t);
93588         return SQLITE_ERROR;
93589       }
93590       t->delim[ch] = 1;
93591     }
93592   } else {
93593     /* Mark non-alphanumeric ASCII characters as delimiters */
93594     int i;
93595     for(i=1; i<0x80; i++){
93596       t->delim[i] = !isalnum(i);
93597     }
93598   }
93599
93600   *ppTokenizer = &t->base;
93601   return SQLITE_OK;
93602 }
93603
93604 /*
93605 ** Destroy a tokenizer
93606 */
93607 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
93608   sqlite3_free(pTokenizer);
93609   return SQLITE_OK;
93610 }
93611
93612 /*
93613 ** Prepare to begin tokenizing a particular string.  The input
93614 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
93615 ** used to incrementally tokenize this string is returned in 
93616 ** *ppCursor.
93617 */
93618 static int simpleOpen(
93619   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
93620   const char *pInput, int nBytes,        /* String to be tokenized */
93621   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
93622 ){
93623   simple_tokenizer_cursor *c;
93624
93625   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
93626   if( c==NULL ) return SQLITE_NOMEM;
93627
93628   c->pInput = pInput;
93629   if( pInput==0 ){
93630     c->nBytes = 0;
93631   }else if( nBytes<0 ){
93632     c->nBytes = (int)strlen(pInput);
93633   }else{
93634     c->nBytes = nBytes;
93635   }
93636   c->iOffset = 0;                 /* start tokenizing at the beginning */
93637   c->iToken = 0;
93638   c->pToken = NULL;               /* no space allocated, yet. */
93639   c->nTokenAllocated = 0;
93640
93641   *ppCursor = &c->base;
93642   return SQLITE_OK;
93643 }
93644
93645 /*
93646 ** Close a tokenization cursor previously opened by a call to
93647 ** simpleOpen() above.
93648 */
93649 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
93650   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
93651   sqlite3_free(c->pToken);
93652   sqlite3_free(c);
93653   return SQLITE_OK;
93654 }
93655
93656 /*
93657 ** Extract the next token from a tokenization cursor.  The cursor must
93658 ** have been opened by a prior call to simpleOpen().
93659 */
93660 static int simpleNext(
93661   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
93662   const char **ppToken,               /* OUT: *ppToken is the token text */
93663   int *pnBytes,                       /* OUT: Number of bytes in token */
93664   int *piStartOffset,                 /* OUT: Starting offset of token */
93665   int *piEndOffset,                   /* OUT: Ending offset of token */
93666   int *piPosition                     /* OUT: Position integer of token */
93667 ){
93668   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
93669   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
93670   unsigned char *p = (unsigned char *)c->pInput;
93671
93672   while( c->iOffset<c->nBytes ){
93673     int iStartOffset;
93674
93675     /* Scan past delimiter characters */
93676     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
93677       c->iOffset++;
93678     }
93679
93680     /* Count non-delimiter characters. */
93681     iStartOffset = c->iOffset;
93682     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
93683       c->iOffset++;
93684     }
93685
93686     if( c->iOffset>iStartOffset ){
93687       int i, n = c->iOffset-iStartOffset;
93688       if( n>c->nTokenAllocated ){
93689         c->nTokenAllocated = n+20;
93690         c->pToken = sqlite3_realloc(c->pToken, c->nTokenAllocated);
93691         if( c->pToken==NULL ) return SQLITE_NOMEM;
93692       }
93693       for(i=0; i<n; i++){
93694         /* TODO(shess) This needs expansion to handle UTF-8
93695         ** case-insensitivity.
93696         */
93697         unsigned char ch = p[iStartOffset+i];
93698         c->pToken[i] = ch<0x80 ? tolower(ch) : ch;
93699       }
93700       *ppToken = c->pToken;
93701       *pnBytes = n;
93702       *piStartOffset = iStartOffset;
93703       *piEndOffset = c->iOffset;
93704       *piPosition = c->iToken++;
93705
93706       return SQLITE_OK;
93707     }
93708   }
93709   return SQLITE_DONE;
93710 }
93711
93712 /*
93713 ** The set of routines that implement the simple tokenizer
93714 */
93715 static const sqlite3_tokenizer_module simpleTokenizerModule = {
93716   0,
93717   simpleCreate,
93718   simpleDestroy,
93719   simpleOpen,
93720   simpleClose,
93721   simpleNext,
93722 };
93723
93724 /*
93725 ** Allocate a new simple tokenizer.  Return a pointer to the new
93726 ** tokenizer in *ppModule
93727 */
93728 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
93729   sqlite3_tokenizer_module const**ppModule
93730 ){
93731   *ppModule = &simpleTokenizerModule;
93732 }
93733
93734 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
93735
93736 /************** End of fts3_tokenizer1.c *************************************/
93737 /************** Begin file rtree.c *******************************************/
93738 /*
93739 ** 2001 September 15
93740 **
93741 ** The author disclaims copyright to this source code.  In place of
93742 ** a legal notice, here is a blessing:
93743 **
93744 **    May you do good and not evil.
93745 **    May you find forgiveness for yourself and forgive others.
93746 **    May you share freely, never taking more than you give.
93747 **
93748 *************************************************************************
93749 ** This file contains code for implementations of the r-tree and r*-tree
93750 ** algorithms packaged as an SQLite virtual table module.
93751 **
93752 ** $Id: rtree.c,v 1.9 2008/09/08 11:07:03 danielk1977 Exp $
93753 */
93754
93755 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
93756
93757 /*
93758 ** This file contains an implementation of a couple of different variants
93759 ** of the r-tree algorithm. See the README file for further details. The 
93760 ** same data-structure is used for all, but the algorithms for insert and
93761 ** delete operations vary. The variants used are selected at compile time 
93762 ** by defining the following symbols:
93763 */
93764
93765 /* Either, both or none of the following may be set to activate 
93766 ** r*tree variant algorithms.
93767 */
93768 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
93769 #define VARIANT_RSTARTREE_REINSERT      1
93770
93771 /* 
93772 ** Exactly one of the following must be set to 1.
93773 */
93774 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
93775 #define VARIANT_GUTTMAN_LINEAR_SPLIT    0
93776 #define VARIANT_RSTARTREE_SPLIT         1
93777
93778 #define VARIANT_GUTTMAN_SPLIT \
93779         (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
93780
93781 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
93782   #define PickNext QuadraticPickNext
93783   #define PickSeeds QuadraticPickSeeds
93784   #define AssignCells splitNodeGuttman
93785 #endif
93786 #if VARIANT_GUTTMAN_LINEAR_SPLIT
93787   #define PickNext LinearPickNext
93788   #define PickSeeds LinearPickSeeds
93789   #define AssignCells splitNodeGuttman
93790 #endif
93791 #if VARIANT_RSTARTREE_SPLIT
93792   #define AssignCells splitNodeStartree
93793 #endif
93794
93795
93796 #ifndef SQLITE_CORE
93797   #include "sqlite3ext.h"
93798   SQLITE_EXTENSION_INIT1
93799 #else
93800   #include "sqlite3.h"
93801 #endif
93802
93803
93804 #ifndef SQLITE_AMALGAMATION
93805 typedef sqlite3_int64 i64;
93806 typedef unsigned char u8;
93807 typedef unsigned int u32;
93808 #endif
93809
93810 typedef struct Rtree Rtree;
93811 typedef struct RtreeCursor RtreeCursor;
93812 typedef struct RtreeNode RtreeNode;
93813 typedef struct RtreeCell RtreeCell;
93814 typedef struct RtreeConstraint RtreeConstraint;
93815 typedef union RtreeCoord RtreeCoord;
93816
93817 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
93818 #define RTREE_MAX_DIMENSIONS 5
93819
93820 /* Size of hash table Rtree.aHash. This hash table is not expected to
93821 ** ever contain very many entries, so a fixed number of buckets is 
93822 ** used.
93823 */
93824 #define HASHSIZE 128
93825
93826 /* 
93827 ** An rtree virtual-table object.
93828 */
93829 struct Rtree {
93830   sqlite3_vtab base;
93831   sqlite3 *db;                /* Host database connection */
93832   int iNodeSize;              /* Size in bytes of each node in the node table */
93833   int nDim;                   /* Number of dimensions */
93834   int nBytesPerCell;          /* Bytes consumed per cell */
93835   int iDepth;                 /* Current depth of the r-tree structure */
93836   char *zDb;                  /* Name of database containing r-tree table */
93837   char *zName;                /* Name of r-tree table */ 
93838   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 
93839   int nBusy;                  /* Current number of users of this structure */
93840
93841   /* List of nodes removed during a CondenseTree operation. List is
93842   ** linked together via the pointer normally used for hash chains -
93843   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 
93844   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
93845   */
93846   RtreeNode *pDeleted;
93847   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
93848
93849   /* Statements to read/write/delete a record from xxx_node */
93850   sqlite3_stmt *pReadNode;
93851   sqlite3_stmt *pWriteNode;
93852   sqlite3_stmt *pDeleteNode;
93853
93854   /* Statements to read/write/delete a record from xxx_rowid */
93855   sqlite3_stmt *pReadRowid;
93856   sqlite3_stmt *pWriteRowid;
93857   sqlite3_stmt *pDeleteRowid;
93858
93859   /* Statements to read/write/delete a record from xxx_parent */
93860   sqlite3_stmt *pReadParent;
93861   sqlite3_stmt *pWriteParent;
93862   sqlite3_stmt *pDeleteParent;
93863
93864   int eCoordType;
93865 };
93866
93867 /* Possible values for eCoordType: */
93868 #define RTREE_COORD_REAL32 0
93869 #define RTREE_COORD_INT32  1
93870
93871 /*
93872 ** The minimum number of cells allowed for a node is a third of the 
93873 ** maximum. In Gutman's notation:
93874 **
93875 **     m = M/3
93876 **
93877 ** If an R*-tree "Reinsert" operation is required, the same number of
93878 ** cells are removed from the overfull node and reinserted into the tree.
93879 */
93880 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
93881 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
93882 #define RTREE_MAXCELLS 51
93883
93884 /* 
93885 ** An rtree cursor object.
93886 */
93887 struct RtreeCursor {
93888   sqlite3_vtab_cursor base;
93889   RtreeNode *pNode;                 /* Node cursor is currently pointing at */
93890   int iCell;                        /* Index of current cell in pNode */
93891   int iStrategy;                    /* Copy of idxNum search parameter */
93892   int nConstraint;                  /* Number of entries in aConstraint */
93893   RtreeConstraint *aConstraint;     /* Search constraints. */
93894 };
93895
93896 union RtreeCoord {
93897   float f;
93898   int i;
93899 };
93900
93901 /*
93902 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
93903 ** formatted as a double. This macro assumes that local variable pRtree points
93904 ** to the Rtree structure associated with the RtreeCoord.
93905 */
93906 #define DCOORD(coord) (                           \
93907   (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
93908     ((double)coord.f) :                           \
93909     ((double)coord.i)                             \
93910 )
93911
93912 /*
93913 ** A search constraint.
93914 */
93915 struct RtreeConstraint {
93916   int iCoord;                       /* Index of constrained coordinate */
93917   int op;                           /* Constraining operation */
93918   double rValue;                    /* Constraint value. */
93919 };
93920
93921 /* Possible values for RtreeConstraint.op */
93922 #define RTREE_EQ 0x41
93923 #define RTREE_LE 0x42
93924 #define RTREE_LT 0x43
93925 #define RTREE_GE 0x44
93926 #define RTREE_GT 0x45
93927
93928 /* 
93929 ** An rtree structure node.
93930 **
93931 ** Data format (RtreeNode.zData):
93932 **
93933 **   1. If the node is the root node (node 1), then the first 2 bytes
93934 **      of the node contain the tree depth as a big-endian integer.
93935 **      For non-root nodes, the first 2 bytes are left unused.
93936 **
93937 **   2. The next 2 bytes contain the number of entries currently 
93938 **      stored in the node.
93939 **
93940 **   3. The remainder of the node contains the node entries. Each entry
93941 **      consists of a single 8-byte integer followed by an even number
93942 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
93943 **      of a record. For internal nodes it is the node number of a
93944 **      child page.
93945 */
93946 struct RtreeNode {
93947   RtreeNode *pParent;               /* Parent node */
93948   i64 iNode;
93949   int nRef;
93950   int isDirty;
93951   u8 *zData;
93952   RtreeNode *pNext;                 /* Next node in this hash chain */
93953 };
93954 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
93955
93956 /* 
93957 ** Structure to store a deserialized rtree record.
93958 */
93959 struct RtreeCell {
93960   i64 iRowid;
93961   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
93962 };
93963
93964 #define MAX(x,y) ((x) < (y) ? (y) : (x))
93965 #define MIN(x,y) ((x) > (y) ? (y) : (x))
93966
93967 /*
93968 ** Functions to deserialize a 16 bit integer, 32 bit real number and
93969 ** 64 bit integer. The deserialized value is returned.
93970 */
93971 static int readInt16(u8 *p){
93972   return (p[0]<<8) + p[1];
93973 }
93974 static void readCoord(u8 *p, RtreeCoord *pCoord){
93975   u32 i = (
93976     (((u32)p[0]) << 24) + 
93977     (((u32)p[1]) << 16) + 
93978     (((u32)p[2]) <<  8) + 
93979     (((u32)p[3]) <<  0)
93980   );
93981   *(u32 *)pCoord = i;
93982 }
93983 static i64 readInt64(u8 *p){
93984   return (
93985     (((i64)p[0]) << 56) + 
93986     (((i64)p[1]) << 48) + 
93987     (((i64)p[2]) << 40) + 
93988     (((i64)p[3]) << 32) + 
93989     (((i64)p[4]) << 24) + 
93990     (((i64)p[5]) << 16) + 
93991     (((i64)p[6]) <<  8) + 
93992     (((i64)p[7]) <<  0)
93993   );
93994 }
93995
93996 /*
93997 ** Functions to serialize a 16 bit integer, 32 bit real number and
93998 ** 64 bit integer. The value returned is the number of bytes written
93999 ** to the argument buffer (always 2, 4 and 8 respectively).
94000 */
94001 static int writeInt16(u8 *p, int i){
94002   p[0] = (i>> 8)&0xFF;
94003   p[1] = (i>> 0)&0xFF;
94004   return 2;
94005 }
94006 static int writeCoord(u8 *p, RtreeCoord *pCoord){
94007   u32 i;
94008   assert( sizeof(RtreeCoord)==4 );
94009   assert( sizeof(u32)==4 );
94010   i = *(u32 *)pCoord;
94011   p[0] = (i>>24)&0xFF;
94012   p[1] = (i>>16)&0xFF;
94013   p[2] = (i>> 8)&0xFF;
94014   p[3] = (i>> 0)&0xFF;
94015   return 4;
94016 }
94017 static int writeInt64(u8 *p, i64 i){
94018   p[0] = (i>>56)&0xFF;
94019   p[1] = (i>>48)&0xFF;
94020   p[2] = (i>>40)&0xFF;
94021   p[3] = (i>>32)&0xFF;
94022   p[4] = (i>>24)&0xFF;
94023   p[5] = (i>>16)&0xFF;
94024   p[6] = (i>> 8)&0xFF;
94025   p[7] = (i>> 0)&0xFF;
94026   return 8;
94027 }
94028
94029 /*
94030 ** Increment the reference count of node p.
94031 */
94032 static void nodeReference(RtreeNode *p){
94033   if( p ){
94034     p->nRef++;
94035   }
94036 }
94037
94038 /*
94039 ** Clear the content of node p (set all bytes to 0x00).
94040 */
94041 static void nodeZero(Rtree *pRtree, RtreeNode *p){
94042   if( p ){
94043     memset(&p->zData[2], 0, pRtree->iNodeSize-2);
94044     p->isDirty = 1;
94045   }
94046 }
94047
94048 /*
94049 ** Given a node number iNode, return the corresponding key to use
94050 ** in the Rtree.aHash table.
94051 */
94052 static int nodeHash(i64 iNode){
94053   return (
94054     (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^ 
94055     (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
94056   ) % HASHSIZE;
94057 }
94058
94059 /*
94060 ** Search the node hash table for node iNode. If found, return a pointer
94061 ** to it. Otherwise, return 0.
94062 */
94063 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
94064   RtreeNode *p;
94065   assert( iNode!=0 );
94066   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
94067   return p;
94068 }
94069
94070 /*
94071 ** Add node pNode to the node hash table.
94072 */
94073 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
94074   if( pNode ){
94075     int iHash;
94076     assert( pNode->pNext==0 );
94077     iHash = nodeHash(pNode->iNode);
94078     pNode->pNext = pRtree->aHash[iHash];
94079     pRtree->aHash[iHash] = pNode;
94080   }
94081 }
94082
94083 /*
94084 ** Remove node pNode from the node hash table.
94085 */
94086 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
94087   RtreeNode **pp;
94088   if( pNode->iNode!=0 ){
94089     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
94090     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
94091     *pp = pNode->pNext;
94092     pNode->pNext = 0;
94093   }
94094 }
94095
94096 /*
94097 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
94098 ** indicating that node has not yet been assigned a node number. It is
94099 ** assigned a node number when nodeWrite() is called to write the
94100 ** node contents out to the database.
94101 */
94102 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent, int zero){
94103   RtreeNode *pNode;
94104   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
94105   if( pNode ){
94106     memset(pNode, 0, sizeof(RtreeNode) + (zero?pRtree->iNodeSize:0));
94107     pNode->zData = (u8 *)&pNode[1];
94108     pNode->nRef = 1;
94109     pNode->pParent = pParent;
94110     pNode->isDirty = 1;
94111     nodeReference(pParent);
94112   }
94113   return pNode;
94114 }
94115
94116 /*
94117 ** Obtain a reference to an r-tree node.
94118 */
94119 static int
94120 nodeAcquire(
94121   Rtree *pRtree,             /* R-tree structure */
94122   i64 iNode,                 /* Node number to load */
94123   RtreeNode *pParent,        /* Either the parent node or NULL */
94124   RtreeNode **ppNode         /* OUT: Acquired node */
94125 ){
94126   int rc;
94127   RtreeNode *pNode;
94128
94129   /* Check if the requested node is already in the hash table. If so,
94130   ** increase its reference count and return it.
94131   */
94132   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
94133     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
94134     if( pParent ){
94135       pNode->pParent = pParent;
94136     }
94137     pNode->nRef++;
94138     *ppNode = pNode;
94139     return SQLITE_OK;
94140   }
94141
94142   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
94143   if( !pNode ){
94144     *ppNode = 0;
94145     return SQLITE_NOMEM;
94146   }
94147   pNode->pParent = pParent;
94148   pNode->zData = (u8 *)&pNode[1];
94149   pNode->nRef = 1;
94150   pNode->iNode = iNode;
94151   pNode->isDirty = 0;
94152   pNode->pNext = 0;
94153
94154   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
94155   rc = sqlite3_step(pRtree->pReadNode);
94156   if( rc==SQLITE_ROW ){
94157     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
94158     memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
94159     nodeReference(pParent);
94160   }else{
94161     sqlite3_free(pNode);
94162     pNode = 0;
94163   }
94164
94165   *ppNode = pNode;
94166   rc = sqlite3_reset(pRtree->pReadNode);
94167
94168   if( rc==SQLITE_OK && iNode==1 ){
94169     pRtree->iDepth = readInt16(pNode->zData);
94170   }
94171
94172   assert( (rc==SQLITE_OK && pNode) || (pNode==0 && rc!=SQLITE_OK) );
94173   nodeHashInsert(pRtree, pNode);
94174
94175   return rc;
94176 }
94177
94178 /*
94179 ** Overwrite cell iCell of node pNode with the contents of pCell.
94180 */
94181 static void nodeOverwriteCell(
94182   Rtree *pRtree, 
94183   RtreeNode *pNode,  
94184   RtreeCell *pCell, 
94185   int iCell
94186 ){
94187   int ii;
94188   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
94189   p += writeInt64(p, pCell->iRowid);
94190   for(ii=0; ii<(pRtree->nDim*2); ii++){
94191     p += writeCoord(p, &pCell->aCoord[ii]);
94192   }
94193   pNode->isDirty = 1;
94194 }
94195
94196 /*
94197 ** Remove cell the cell with index iCell from node pNode.
94198 */
94199 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
94200   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
94201   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
94202   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
94203   memmove(pDst, pSrc, nByte);
94204   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
94205   pNode->isDirty = 1;
94206 }
94207
94208 /*
94209 ** Insert the contents of cell pCell into node pNode. If the insert
94210 ** is successful, return SQLITE_OK.
94211 **
94212 ** If there is not enough free space in pNode, return SQLITE_FULL.
94213 */
94214 static int
94215 nodeInsertCell(
94216   Rtree *pRtree, 
94217   RtreeNode *pNode, 
94218   RtreeCell *pCell 
94219 ){
94220   int nCell;                    /* Current number of cells in pNode */
94221   int nMaxCell;                 /* Maximum number of cells for pNode */
94222
94223   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
94224   nCell = NCELL(pNode);
94225
94226   assert(nCell<=nMaxCell);
94227
94228   if( nCell<nMaxCell ){
94229     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
94230     writeInt16(&pNode->zData[2], nCell+1);
94231     pNode->isDirty = 1;
94232   }
94233
94234   return (nCell==nMaxCell);
94235 }
94236
94237 /*
94238 ** If the node is dirty, write it out to the database.
94239 */
94240 static int
94241 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
94242   int rc = SQLITE_OK;
94243   if( pNode->isDirty ){
94244     sqlite3_stmt *p = pRtree->pWriteNode;
94245     if( pNode->iNode ){
94246       sqlite3_bind_int64(p, 1, pNode->iNode);
94247     }else{
94248       sqlite3_bind_null(p, 1);
94249     }
94250     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
94251     sqlite3_step(p);
94252     pNode->isDirty = 0;
94253     rc = sqlite3_reset(p);
94254     if( pNode->iNode==0 && rc==SQLITE_OK ){
94255       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
94256       nodeHashInsert(pRtree, pNode);
94257     }
94258   }
94259   return rc;
94260 }
94261
94262 /*
94263 ** Release a reference to a node. If the node is dirty and the reference
94264 ** count drops to zero, the node data is written to the database.
94265 */
94266 static int
94267 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
94268   int rc = SQLITE_OK;
94269   if( pNode ){
94270     assert( pNode->nRef>0 );
94271     pNode->nRef--;
94272     if( pNode->nRef==0 ){
94273       if( pNode->iNode==1 ){
94274         pRtree->iDepth = -1;
94275       }
94276       if( pNode->pParent ){
94277         rc = nodeRelease(pRtree, pNode->pParent);
94278       }
94279       if( rc==SQLITE_OK ){
94280         rc = nodeWrite(pRtree, pNode);
94281       }
94282       nodeHashDelete(pRtree, pNode);
94283       sqlite3_free(pNode);
94284     }
94285   }
94286   return rc;
94287 }
94288
94289 /*
94290 ** Return the 64-bit integer value associated with cell iCell of
94291 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
94292 ** an internal node, then the 64-bit integer is a child page number.
94293 */
94294 static i64 nodeGetRowid(
94295   Rtree *pRtree, 
94296   RtreeNode *pNode, 
94297   int iCell
94298 ){
94299   assert( iCell<NCELL(pNode) );
94300   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
94301 }
94302
94303 /*
94304 ** Return coordinate iCoord from cell iCell in node pNode.
94305 */
94306 static void nodeGetCoord(
94307   Rtree *pRtree, 
94308   RtreeNode *pNode, 
94309   int iCell,
94310   int iCoord,
94311   RtreeCoord *pCoord           /* Space to write result to */
94312 ){
94313   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
94314 }
94315
94316 /*
94317 ** Deserialize cell iCell of node pNode. Populate the structure pointed
94318 ** to by pCell with the results.
94319 */
94320 static void nodeGetCell(
94321   Rtree *pRtree, 
94322   RtreeNode *pNode, 
94323   int iCell,
94324   RtreeCell *pCell
94325 ){
94326   int ii;
94327   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
94328   for(ii=0; ii<pRtree->nDim*2; ii++){
94329     nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
94330   }
94331 }
94332
94333
94334 /* Forward declaration for the function that does the work of
94335 ** the virtual table module xCreate() and xConnect() methods.
94336 */
94337 static int rtreeInit(
94338   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int, int
94339 );
94340
94341 /* 
94342 ** Rtree virtual table module xCreate method.
94343 */
94344 static int rtreeCreate(
94345   sqlite3 *db,
94346   void *pAux,
94347   int argc, const char *const*argv,
94348   sqlite3_vtab **ppVtab,
94349   char **pzErr
94350 ){
94351   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1, (int)pAux);
94352 }
94353
94354 /* 
94355 ** Rtree virtual table module xConnect method.
94356 */
94357 static int rtreeConnect(
94358   sqlite3 *db,
94359   void *pAux,
94360   int argc, const char *const*argv,
94361   sqlite3_vtab **ppVtab,
94362   char **pzErr
94363 ){
94364   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0, (int)pAux);
94365 }
94366
94367 /*
94368 ** Increment the r-tree reference count.
94369 */
94370 static void rtreeReference(Rtree *pRtree){
94371   pRtree->nBusy++;
94372 }
94373
94374 /*
94375 ** Decrement the r-tree reference count. When the reference count reaches
94376 ** zero the structure is deleted.
94377 */
94378 static void rtreeRelease(Rtree *pRtree){
94379   pRtree->nBusy--;
94380   if( pRtree->nBusy==0 ){
94381     sqlite3_finalize(pRtree->pReadNode);
94382     sqlite3_finalize(pRtree->pWriteNode);
94383     sqlite3_finalize(pRtree->pDeleteNode);
94384     sqlite3_finalize(pRtree->pReadRowid);
94385     sqlite3_finalize(pRtree->pWriteRowid);
94386     sqlite3_finalize(pRtree->pDeleteRowid);
94387     sqlite3_finalize(pRtree->pReadParent);
94388     sqlite3_finalize(pRtree->pWriteParent);
94389     sqlite3_finalize(pRtree->pDeleteParent);
94390     sqlite3_free(pRtree);
94391   }
94392 }
94393
94394 /* 
94395 ** Rtree virtual table module xDisconnect method.
94396 */
94397 static int rtreeDisconnect(sqlite3_vtab *pVtab){
94398   rtreeRelease((Rtree *)pVtab);
94399   return SQLITE_OK;
94400 }
94401
94402 /* 
94403 ** Rtree virtual table module xDestroy method.
94404 */
94405 static int rtreeDestroy(sqlite3_vtab *pVtab){
94406   Rtree *pRtree = (Rtree *)pVtab;
94407   int rc;
94408   char *zCreate = sqlite3_mprintf(
94409     "DROP TABLE '%q'.'%q_node';"
94410     "DROP TABLE '%q'.'%q_rowid';"
94411     "DROP TABLE '%q'.'%q_parent';",
94412     pRtree->zDb, pRtree->zName, 
94413     pRtree->zDb, pRtree->zName,
94414     pRtree->zDb, pRtree->zName
94415   );
94416   if( !zCreate ){
94417     rc = SQLITE_NOMEM;
94418   }else{
94419     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
94420     sqlite3_free(zCreate);
94421   }
94422   if( rc==SQLITE_OK ){
94423     rtreeRelease(pRtree);
94424   }
94425
94426   return rc;
94427 }
94428
94429 /* 
94430 ** Rtree virtual table module xOpen method.
94431 */
94432 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
94433   int rc = SQLITE_NOMEM;
94434   RtreeCursor *pCsr;
94435
94436   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
94437   if( pCsr ){
94438     memset(pCsr, 0, sizeof(RtreeCursor));
94439     pCsr->base.pVtab = pVTab;
94440     rc = SQLITE_OK;
94441   }
94442   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
94443
94444   return rc;
94445 }
94446
94447 /* 
94448 ** Rtree virtual table module xClose method.
94449 */
94450 static int rtreeClose(sqlite3_vtab_cursor *cur){
94451   Rtree *pRtree = (Rtree *)(cur->pVtab);
94452   int rc;
94453   RtreeCursor *pCsr = (RtreeCursor *)cur;
94454   sqlite3_free(pCsr->aConstraint);
94455   rc = nodeRelease(pRtree, pCsr->pNode);
94456   sqlite3_free(pCsr);
94457   return rc;
94458 }
94459
94460 /*
94461 ** Rtree virtual table module xEof method.
94462 **
94463 ** Return non-zero if the cursor does not currently point to a valid 
94464 ** record (i.e if the scan has finished), or zero otherwise.
94465 */
94466 static int rtreeEof(sqlite3_vtab_cursor *cur){
94467   RtreeCursor *pCsr = (RtreeCursor *)cur;
94468   return (pCsr->pNode==0);
94469 }
94470
94471 /* 
94472 ** Cursor pCursor currently points to a cell in a non-leaf page.
94473 ** Return true if the sub-tree headed by the cell is filtered
94474 ** (excluded) by the constraints in the pCursor->aConstraint[] 
94475 ** array, or false otherwise.
94476 */
94477 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor){
94478   RtreeCell cell;
94479   int ii;
94480   int bRes = 0;
94481
94482   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
94483   for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
94484     RtreeConstraint *p = &pCursor->aConstraint[ii];
94485     double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
94486     double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
94487
94488     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
94489         || p->op==RTREE_GT || p->op==RTREE_EQ
94490     );
94491
94492     switch( p->op ){
94493       case RTREE_LE: case RTREE_LT: bRes = p->rValue<cell_min; break;
94494       case RTREE_GE: case RTREE_GT: bRes = p->rValue>cell_max; break;
94495       case RTREE_EQ: 
94496         bRes = (p->rValue>cell_max || p->rValue<cell_min);
94497         break;
94498     }
94499   }
94500
94501   return bRes;
94502 }
94503
94504 /* 
94505 ** Return true if the cell that cursor pCursor currently points to
94506 ** would be filtered (excluded) by the constraints in the 
94507 ** pCursor->aConstraint[] array, or false otherwise.
94508 **
94509 ** This function assumes that the cell is part of a leaf node.
94510 */
94511 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor){
94512   RtreeCell cell;
94513   int ii;
94514
94515   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
94516   for(ii=0; ii<pCursor->nConstraint; ii++){
94517     RtreeConstraint *p = &pCursor->aConstraint[ii];
94518     double coord = DCOORD(cell.aCoord[p->iCoord]);
94519     int res;
94520     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
94521         || p->op==RTREE_GT || p->op==RTREE_EQ
94522     );
94523     switch( p->op ){
94524       case RTREE_LE: res = (coord<=p->rValue); break;
94525       case RTREE_LT: res = (coord<p->rValue);  break;
94526       case RTREE_GE: res = (coord>=p->rValue); break;
94527       case RTREE_GT: res = (coord>p->rValue);  break;
94528       case RTREE_EQ: res = (coord==p->rValue); break;
94529     }
94530
94531     if( !res ) return 1;
94532   }
94533
94534   return 0;
94535 }
94536
94537 /*
94538 ** Cursor pCursor currently points at a node that heads a sub-tree of
94539 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
94540 ** to point to the left-most cell of the sub-tree that matches the 
94541 ** configured constraints.
94542 */
94543 static int descendToCell(
94544   Rtree *pRtree, 
94545   RtreeCursor *pCursor, 
94546   int iHeight,
94547   int *pEof                 /* OUT: Set to true if cannot descend */
94548 ){
94549   int isEof;
94550   int rc;
94551   int ii;
94552   RtreeNode *pChild;
94553   sqlite3_int64 iRowid;
94554
94555   RtreeNode *pSavedNode = pCursor->pNode;
94556   int iSavedCell = pCursor->iCell;
94557
94558   assert( iHeight>=0 );
94559
94560   if( iHeight==0 ){
94561     isEof = testRtreeEntry(pRtree, pCursor);
94562   }else{
94563     isEof = testRtreeCell(pRtree, pCursor);
94564   }
94565   if( isEof || iHeight==0 ){
94566     *pEof = isEof;
94567     return SQLITE_OK;
94568   }
94569
94570   iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
94571   rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
94572   if( rc!=SQLITE_OK ){
94573     return rc;
94574   }
94575
94576   nodeRelease(pRtree, pCursor->pNode);
94577   pCursor->pNode = pChild;
94578   isEof = 1;
94579   for(ii=0; isEof && ii<NCELL(pChild); ii++){
94580     pCursor->iCell = ii;
94581     rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
94582     if( rc!=SQLITE_OK ){
94583       return rc;
94584     }
94585   }
94586
94587   if( isEof ){
94588     assert( pCursor->pNode==pChild );
94589     nodeReference(pSavedNode);
94590     nodeRelease(pRtree, pChild);
94591     pCursor->pNode = pSavedNode;
94592     pCursor->iCell = iSavedCell;
94593   }
94594
94595   *pEof = isEof;
94596   return SQLITE_OK;
94597 }
94598
94599 /*
94600 ** One of the cells in node pNode is guaranteed to have a 64-bit 
94601 ** integer value equal to iRowid. Return the index of this cell.
94602 */
94603 static int nodeRowidIndex(Rtree *pRtree, RtreeNode *pNode, i64 iRowid){
94604   int ii;
94605   for(ii=0; nodeGetRowid(pRtree, pNode, ii)!=iRowid; ii++){
94606     assert( ii<(NCELL(pNode)-1) );
94607   }
94608   return ii;
94609 }
94610
94611 /*
94612 ** Return the index of the cell containing a pointer to node pNode
94613 ** in its parent. If pNode is the root node, return -1.
94614 */
94615 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode){
94616   RtreeNode *pParent = pNode->pParent;
94617   if( pParent ){
94618     return nodeRowidIndex(pRtree, pParent, pNode->iNode);
94619   }
94620   return -1;
94621 }
94622
94623 /* 
94624 ** Rtree virtual table module xNext method.
94625 */
94626 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
94627   Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
94628   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
94629   int rc = SQLITE_OK;
94630
94631   if( pCsr->iStrategy==1 ){
94632     /* This "scan" is a direct lookup by rowid. There is no next entry. */
94633     nodeRelease(pRtree, pCsr->pNode);
94634     pCsr->pNode = 0;
94635   }
94636
94637   else if( pCsr->pNode ){
94638     /* Move to the next entry that matches the configured constraints. */
94639     int iHeight = 0;
94640     while( pCsr->pNode ){
94641       RtreeNode *pNode = pCsr->pNode;
94642       int nCell = NCELL(pNode);
94643       for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
94644         int isEof;
94645         rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
94646         if( rc!=SQLITE_OK || !isEof ){
94647           return rc;
94648         }
94649       }
94650       pCsr->pNode = pNode->pParent;
94651       pCsr->iCell = nodeParentIndex(pRtree, pNode);
94652       nodeReference(pCsr->pNode);
94653       nodeRelease(pRtree, pNode);
94654       iHeight++;
94655     }
94656   }
94657
94658   return rc;
94659 }
94660
94661 /* 
94662 ** Rtree virtual table module xRowid method.
94663 */
94664 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
94665   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
94666   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
94667
94668   assert(pCsr->pNode);
94669   *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
94670
94671   return SQLITE_OK;
94672 }
94673
94674 /* 
94675 ** Rtree virtual table module xColumn method.
94676 */
94677 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
94678   Rtree *pRtree = (Rtree *)cur->pVtab;
94679   RtreeCursor *pCsr = (RtreeCursor *)cur;
94680
94681   if( i==0 ){
94682     i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
94683     sqlite3_result_int64(ctx, iRowid);
94684   }else{
94685     RtreeCoord c;
94686     nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
94687     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
94688       sqlite3_result_double(ctx, c.f);
94689     }else{
94690       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
94691       sqlite3_result_int(ctx, c.i);
94692     }
94693   }
94694
94695   return SQLITE_OK;
94696 }
94697
94698 /* 
94699 ** Use nodeAcquire() to obtain the leaf node containing the record with 
94700 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
94701 ** return SQLITE_OK. If there is no such record in the table, set
94702 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
94703 ** to zero and return an SQLite error code.
94704 */
94705 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
94706   int rc;
94707   *ppLeaf = 0;
94708   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
94709   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
94710     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
94711     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
94712     sqlite3_reset(pRtree->pReadRowid);
94713   }else{
94714     rc = sqlite3_reset(pRtree->pReadRowid);
94715   }
94716   return rc;
94717 }
94718
94719
94720 /* 
94721 ** Rtree virtual table module xFilter method.
94722 */
94723 static int rtreeFilter(
94724   sqlite3_vtab_cursor *pVtabCursor, 
94725   int idxNum, const char *idxStr,
94726   int argc, sqlite3_value **argv
94727 ){
94728   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
94729   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
94730
94731   RtreeNode *pRoot = 0;
94732   int ii;
94733   int rc = SQLITE_OK;
94734
94735   rtreeReference(pRtree);
94736
94737   sqlite3_free(pCsr->aConstraint);
94738   pCsr->aConstraint = 0;
94739   pCsr->iStrategy = idxNum;
94740
94741   if( idxNum==1 ){
94742     /* Special case - lookup by rowid. */
94743     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
94744     i64 iRowid = sqlite3_value_int64(argv[0]);
94745     rc = findLeafNode(pRtree, iRowid, &pLeaf);
94746     pCsr->pNode = pLeaf; 
94747     if( pLeaf && rc==SQLITE_OK ){
94748       pCsr->iCell = nodeRowidIndex(pRtree, pLeaf, iRowid);
94749     }
94750   }else{
94751     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 
94752     ** with the configured constraints. 
94753     */
94754     if( argc>0 ){
94755       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
94756       pCsr->nConstraint = argc;
94757       if( !pCsr->aConstraint ){
94758         rc = SQLITE_NOMEM;
94759       }else{
94760         assert( (idxStr==0 && argc==0) || strlen(idxStr)==argc*2 );
94761         for(ii=0; ii<argc; ii++){
94762           RtreeConstraint *p = &pCsr->aConstraint[ii];
94763           p->op = idxStr[ii*2];
94764           p->iCoord = idxStr[ii*2+1]-'a';
94765           p->rValue = sqlite3_value_double(argv[ii]);
94766         }
94767       }
94768     }
94769   
94770     if( rc==SQLITE_OK ){
94771       pCsr->pNode = 0;
94772       rc = nodeAcquire(pRtree, 1, 0, &pRoot);
94773     }
94774     if( rc==SQLITE_OK ){
94775       int isEof = 1;
94776       int nCell = NCELL(pRoot);
94777       pCsr->pNode = pRoot;
94778       for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
94779         assert( pCsr->pNode==pRoot );
94780         rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
94781         if( !isEof ){
94782           break;
94783         }
94784       }
94785       if( rc==SQLITE_OK && isEof ){
94786         assert( pCsr->pNode==pRoot );
94787         nodeRelease(pRtree, pRoot);
94788         pCsr->pNode = 0;
94789       }
94790       assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
94791     }
94792   }
94793
94794   rtreeRelease(pRtree);
94795   return rc;
94796 }
94797
94798 /*
94799 ** Rtree virtual table module xBestIndex method. There are three
94800 ** table scan strategies to choose from (in order from most to 
94801 ** least desirable):
94802 **
94803 **   idxNum     idxStr        Strategy
94804 **   ------------------------------------------------
94805 **     1        Unused        Direct lookup by rowid.
94806 **     2        See below     R-tree query.
94807 **     3        Unused        Full table scan.
94808 **   ------------------------------------------------
94809 **
94810 ** If strategy 1 or 3 is used, then idxStr is not meaningful. If strategy
94811 ** 2 is used, idxStr is formatted to contain 2 bytes for each 
94812 ** constraint used. The first two bytes of idxStr correspond to 
94813 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
94814 ** (argvIndex==1) etc.
94815 **
94816 ** The first of each pair of bytes in idxStr identifies the constraint
94817 ** operator as follows:
94818 **
94819 **   Operator    Byte Value
94820 **   ----------------------
94821 **      =        0x41 ('A')
94822 **     <=        0x42 ('B')
94823 **      <        0x43 ('C')
94824 **     >=        0x44 ('D')
94825 **      >        0x45 ('E')
94826 **   ----------------------
94827 **
94828 ** The second of each pair of bytes identifies the coordinate column
94829 ** to which the constraint applies. The leftmost coordinate column
94830 ** is 'a', the second from the left 'b' etc.
94831 */
94832 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
94833   int rc = SQLITE_OK;
94834   int ii, cCol;
94835
94836   int iIdx = 0;
94837   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
94838   memset(zIdxStr, 0, sizeof(zIdxStr));
94839
94840   assert( pIdxInfo->idxStr==0 );
94841   for(ii=0; ii<pIdxInfo->nConstraint; ii++){
94842     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
94843
94844     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
94845       /* We have an equality constraint on the rowid. Use strategy 1. */
94846       int jj;
94847       for(jj=0; jj<ii; jj++){
94848         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
94849         pIdxInfo->aConstraintUsage[jj].omit = 0;
94850       }
94851       pIdxInfo->idxNum = 1;
94852       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
94853       pIdxInfo->aConstraintUsage[jj].omit = 1;
94854
94855       /* This strategy involves a two rowid lookups on an B-Tree structures
94856       ** and then a linear search of an R-Tree node. This should be 
94857       ** considered almost as quick as a direct rowid lookup (for which 
94858       ** sqlite uses an internal cost of 0.0).
94859       */ 
94860       pIdxInfo->estimatedCost = 10.0;
94861       return SQLITE_OK;
94862     }
94863
94864     if( p->usable && p->iColumn>0 ){
94865       u8 op = 0;
94866       switch( p->op ){
94867         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
94868         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
94869         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
94870         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
94871         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
94872       }
94873       if( op ){
94874         /* Make sure this particular constraint has not been used before.
94875         ** If it has been used before, ignore it.
94876         **
94877         ** A <= or < can be used if there is a prior >= or >.
94878         ** A >= or > can be used if there is a prior < or <=.
94879         ** A <= or < is disqualified if there is a prior <=, <, or ==.
94880         ** A >= or > is disqualified if there is a prior >=, >, or ==.
94881         ** A == is disqualifed if there is any prior constraint.
94882         */
94883         int j, opmsk;
94884         static const unsigned char compatible[] = { 0, 0, 1, 1, 2, 2 };
94885         assert( compatible[RTREE_EQ & 7]==0 );
94886         assert( compatible[RTREE_LT & 7]==1 );
94887         assert( compatible[RTREE_LE & 7]==1 );
94888         assert( compatible[RTREE_GT & 7]==2 );
94889         assert( compatible[RTREE_GE & 7]==2 );
94890         cCol = p->iColumn - 1 + 'a';
94891         opmsk = compatible[op & 7];
94892         for(j=0; j<iIdx; j+=2){
94893           if( zIdxStr[j+1]==cCol && (compatible[zIdxStr[j] & 7] & opmsk)!=0 ){
94894             op = 0;
94895             break;
94896           }
94897         }
94898       }
94899       if( op ){
94900         assert( iIdx<sizeof(zIdxStr)-1 );
94901         zIdxStr[iIdx++] = op;
94902         zIdxStr[iIdx++] = cCol;
94903         pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
94904         pIdxInfo->aConstraintUsage[ii].omit = 1;
94905       }
94906     }
94907   }
94908
94909   pIdxInfo->idxNum = 2;
94910   pIdxInfo->needToFreeIdxStr = 1;
94911   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
94912     return SQLITE_NOMEM;
94913   }
94914   assert( iIdx>=0 );
94915   pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
94916   return rc;
94917 }
94918
94919 /*
94920 ** Return the N-dimensional volumn of the cell stored in *p.
94921 */
94922 static float cellArea(Rtree *pRtree, RtreeCell *p){
94923   float area = 1.0;
94924   int ii;
94925   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
94926     area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
94927   }
94928   return area;
94929 }
94930
94931 /*
94932 ** Return the margin length of cell p. The margin length is the sum
94933 ** of the objects size in each dimension.
94934 */
94935 static float cellMargin(Rtree *pRtree, RtreeCell *p){
94936   float margin = 0.0;
94937   int ii;
94938   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
94939     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
94940   }
94941   return margin;
94942 }
94943
94944 /*
94945 ** Store the union of cells p1 and p2 in p1.
94946 */
94947 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
94948   int ii;
94949   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
94950     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
94951       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
94952       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
94953     }
94954   }else{
94955     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
94956       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
94957       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
94958     }
94959   }
94960 }
94961
94962 /*
94963 ** Return true if the area covered by p2 is a subset of the area covered
94964 ** by p1. False otherwise.
94965 */
94966 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
94967   int ii;
94968   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
94969   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
94970     RtreeCoord *a1 = &p1->aCoord[ii];
94971     RtreeCoord *a2 = &p2->aCoord[ii];
94972     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) 
94973      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) 
94974     ){
94975       return 0;
94976     }
94977   }
94978   return 1;
94979 }
94980
94981 /*
94982 ** Return the amount cell p would grow by if it were unioned with pCell.
94983 */
94984 static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
94985   float area;
94986   RtreeCell cell;
94987   memcpy(&cell, p, sizeof(RtreeCell));
94988   area = cellArea(pRtree, &cell);
94989   cellUnion(pRtree, &cell, pCell);
94990   return (cellArea(pRtree, &cell)-area);
94991 }
94992
94993 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
94994 static float cellOverlap(
94995   Rtree *pRtree, 
94996   RtreeCell *p, 
94997   RtreeCell *aCell, 
94998   int nCell, 
94999   int iExclude
95000 ){
95001   int ii;
95002   float overlap = 0.0;
95003   for(ii=0; ii<nCell; ii++){
95004     if( ii!=iExclude ){
95005       int jj;
95006       float o = 1.0;
95007       for(jj=0; jj<(pRtree->nDim*2); jj+=2){
95008         double x1;
95009         double x2;
95010
95011         x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
95012         x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
95013
95014         if( x2<x1 ){
95015           o = 0.0;
95016           break;
95017         }else{
95018           o = o * (x2-x1);
95019         }
95020       }
95021       overlap += o;
95022     }
95023   }
95024   return overlap;
95025 }
95026 #endif
95027
95028 #if VARIANT_RSTARTREE_CHOOSESUBTREE
95029 static float cellOverlapEnlargement(
95030   Rtree *pRtree, 
95031   RtreeCell *p, 
95032   RtreeCell *pInsert, 
95033   RtreeCell *aCell, 
95034   int nCell, 
95035   int iExclude
95036 ){
95037   float before;
95038   float after;
95039   before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
95040   cellUnion(pRtree, p, pInsert);
95041   after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
95042   return after-before;
95043 }
95044 #endif
95045
95046
95047 /*
95048 ** This function implements the ChooseLeaf algorithm from Gutman[84].
95049 ** ChooseSubTree in r*tree terminology.
95050 */
95051 static int ChooseLeaf(
95052   Rtree *pRtree,               /* Rtree table */
95053   RtreeCell *pCell,            /* Cell to insert into rtree */
95054   int iHeight,                 /* Height of sub-tree rooted at pCell */
95055   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
95056 ){
95057   int rc;
95058   int ii;
95059   RtreeNode *pNode;
95060   rc = nodeAcquire(pRtree, 1, 0, &pNode);
95061
95062   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
95063     int iCell;
95064     sqlite3_int64 iBest;
95065
95066     float fMinGrowth;
95067     float fMinArea;
95068     float fMinOverlap;
95069
95070     int nCell = NCELL(pNode);
95071     RtreeCell cell;
95072     RtreeNode *pChild;
95073
95074     RtreeCell *aCell = 0;
95075
95076 #if VARIANT_RSTARTREE_CHOOSESUBTREE
95077     if( ii==(pRtree->iDepth-1) ){
95078       int jj;
95079       aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
95080       if( !aCell ){
95081         rc = SQLITE_NOMEM;
95082         nodeRelease(pRtree, pNode);
95083         pNode = 0;
95084         continue;
95085       }
95086       for(jj=0; jj<nCell; jj++){
95087         nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
95088       }
95089     }
95090 #endif
95091
95092     /* Select the child node which will be enlarged the least if pCell
95093     ** is inserted into it. Resolve ties by choosing the entry with
95094     ** the smallest area.
95095     */
95096     for(iCell=0; iCell<nCell; iCell++){
95097       float growth;
95098       float area;
95099       float overlap = 0.0;
95100       nodeGetCell(pRtree, pNode, iCell, &cell);
95101       growth = cellGrowth(pRtree, &cell, pCell);
95102       area = cellArea(pRtree, &cell);
95103 #if VARIANT_RSTARTREE_CHOOSESUBTREE
95104       if( ii==(pRtree->iDepth-1) ){
95105         overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
95106       }
95107 #endif
95108       if( (iCell==0) 
95109        || (overlap<fMinOverlap) 
95110        || (overlap==fMinOverlap && growth<fMinGrowth)
95111        || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
95112       ){
95113         fMinOverlap = overlap;
95114         fMinGrowth = growth;
95115         fMinArea = area;
95116         iBest = cell.iRowid;
95117       }
95118     }
95119
95120     sqlite3_free(aCell);
95121     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
95122     nodeRelease(pRtree, pNode);
95123     pNode = pChild;
95124   }
95125
95126   *ppLeaf = pNode;
95127   return rc;
95128 }
95129
95130 /*
95131 ** A cell with the same content as pCell has just been inserted into
95132 ** the node pNode. This function updates the bounding box cells in
95133 ** all ancestor elements.
95134 */
95135 static void AdjustTree(
95136   Rtree *pRtree,                    /* Rtree table */
95137   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
95138   RtreeCell *pCell                  /* This cell was just inserted */
95139 ){
95140   RtreeNode *p = pNode;
95141   while( p->pParent ){
95142     RtreeCell cell;
95143     RtreeNode *pParent = p->pParent;
95144     int iCell = nodeParentIndex(pRtree, p);
95145
95146     nodeGetCell(pRtree, pParent, iCell, &cell);
95147     if( !cellContains(pRtree, &cell, pCell) ){
95148       cellUnion(pRtree, &cell, pCell);
95149       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
95150     }
95151  
95152     p = pParent;
95153   }
95154 }
95155
95156 /*
95157 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
95158 */
95159 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
95160   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
95161   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
95162   sqlite3_step(pRtree->pWriteRowid);
95163   return sqlite3_reset(pRtree->pWriteRowid);
95164 }
95165
95166 /*
95167 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
95168 */
95169 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
95170   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
95171   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
95172   sqlite3_step(pRtree->pWriteParent);
95173   return sqlite3_reset(pRtree->pWriteParent);
95174 }
95175
95176 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
95177
95178 #if VARIANT_GUTTMAN_LINEAR_SPLIT
95179 /*
95180 ** Implementation of the linear variant of the PickNext() function from
95181 ** Guttman[84].
95182 */
95183 static RtreeCell *LinearPickNext(
95184   Rtree *pRtree,
95185   RtreeCell *aCell, 
95186   int nCell, 
95187   RtreeCell *pLeftBox, 
95188   RtreeCell *pRightBox,
95189   int *aiUsed
95190 ){
95191   int ii;
95192   for(ii=0; aiUsed[ii]; ii++);
95193   aiUsed[ii] = 1;
95194   return &aCell[ii];
95195 }
95196
95197 /*
95198 ** Implementation of the linear variant of the PickSeeds() function from
95199 ** Guttman[84].
95200 */
95201 static void LinearPickSeeds(
95202   Rtree *pRtree,
95203   RtreeCell *aCell, 
95204   int nCell, 
95205   int *piLeftSeed, 
95206   int *piRightSeed
95207 ){
95208   int i;
95209   int iLeftSeed = 0;
95210   int iRightSeed = 1;
95211   float maxNormalInnerWidth = 0.0;
95212
95213   /* Pick two "seed" cells from the array of cells. The algorithm used
95214   ** here is the LinearPickSeeds algorithm from Gutman[1984]. The 
95215   ** indices of the two seed cells in the array are stored in local
95216   ** variables iLeftSeek and iRightSeed.
95217   */
95218   for(i=0; i<pRtree->nDim; i++){
95219     float x1 = aCell[0].aCoord[i*2];
95220     float x2 = aCell[0].aCoord[i*2+1];
95221     float x3 = x1;
95222     float x4 = x2;
95223     int jj;
95224
95225     int iCellLeft = 0;
95226     int iCellRight = 0;
95227
95228     for(jj=1; jj<nCell; jj++){
95229       float left = aCell[jj].aCoord[i*2];
95230       float right = aCell[jj].aCoord[i*2+1];
95231
95232       if( left<x1 ) x1 = left;
95233       if( right>x4 ) x4 = right;
95234       if( left>x3 ){
95235         x3 = left;
95236         iCellRight = jj;
95237       }
95238       if( right<x2 ){
95239         x2 = right;
95240         iCellLeft = jj;
95241       }
95242     }
95243
95244     if( x4!=x1 ){
95245       float normalwidth = (x3 - x2) / (x4 - x1);
95246       if( normalwidth>maxNormalInnerWidth ){
95247         iLeftSeed = iCellLeft;
95248         iRightSeed = iCellRight;
95249       }
95250     }
95251   }
95252
95253   *piLeftSeed = iLeftSeed;
95254   *piRightSeed = iRightSeed;
95255 }
95256 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
95257
95258 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
95259 /*
95260 ** Implementation of the quadratic variant of the PickNext() function from
95261 ** Guttman[84].
95262 */
95263 static RtreeCell *QuadraticPickNext(
95264   Rtree *pRtree,
95265   RtreeCell *aCell, 
95266   int nCell, 
95267   RtreeCell *pLeftBox, 
95268   RtreeCell *pRightBox,
95269   int *aiUsed
95270 ){
95271   #define FABS(a) ((a)<0.0?-1.0*(a):(a))
95272
95273   int iSelect = -1;
95274   float fDiff;
95275   int ii;
95276   for(ii=0; ii<nCell; ii++){
95277     if( aiUsed[ii]==0 ){
95278       float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
95279       float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
95280       float diff = FABS(right-left);
95281       if( iSelect<0 || diff>fDiff ){
95282         fDiff = diff;
95283         iSelect = ii;
95284       }
95285     }
95286   }
95287   aiUsed[iSelect] = 1;
95288   return &aCell[iSelect];
95289 }
95290
95291 /*
95292 ** Implementation of the quadratic variant of the PickSeeds() function from
95293 ** Guttman[84].
95294 */
95295 static void QuadraticPickSeeds(
95296   Rtree *pRtree,
95297   RtreeCell *aCell, 
95298   int nCell, 
95299   int *piLeftSeed, 
95300   int *piRightSeed
95301 ){
95302   int ii;
95303   int jj;
95304
95305   int iLeftSeed = 0;
95306   int iRightSeed = 1;
95307   float fWaste = 0.0;
95308
95309   for(ii=0; ii<nCell; ii++){
95310     for(jj=ii+1; jj<nCell; jj++){
95311       float right = cellArea(pRtree, &aCell[jj]);
95312       float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
95313       float waste = growth - right;
95314
95315       if( waste>fWaste ){
95316         iLeftSeed = ii;
95317         iRightSeed = jj;
95318         fWaste = waste;
95319       }
95320     }
95321   }
95322
95323   *piLeftSeed = iLeftSeed;
95324   *piRightSeed = iRightSeed;
95325 }
95326 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
95327
95328 /*
95329 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
95330 ** nIdx. The aIdx array contains the set of integers from 0 to 
95331 ** (nIdx-1) in no particular order. This function sorts the values
95332 ** in aIdx according to the indexed values in aDistance. For
95333 ** example, assuming the inputs:
95334 **
95335 **   aIdx      = { 0,   1,   2,   3 }
95336 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
95337 **
95338 ** this function sets the aIdx array to contain:
95339 **
95340 **   aIdx      = { 0,   1,   2,   3 }
95341 **
95342 ** The aSpare array is used as temporary working space by the
95343 ** sorting algorithm.
95344 */
95345 static void SortByDistance(
95346   int *aIdx, 
95347   int nIdx, 
95348   float *aDistance, 
95349   int *aSpare
95350 ){
95351   if( nIdx>1 ){
95352     int iLeft = 0;
95353     int iRight = 0;
95354
95355     int nLeft = nIdx/2;
95356     int nRight = nIdx-nLeft;
95357     int *aLeft = aIdx;
95358     int *aRight = &aIdx[nLeft];
95359
95360     SortByDistance(aLeft, nLeft, aDistance, aSpare);
95361     SortByDistance(aRight, nRight, aDistance, aSpare);
95362
95363     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
95364     aLeft = aSpare;
95365
95366     while( iLeft<nLeft || iRight<nRight ){
95367       if( iLeft==nLeft ){
95368         aIdx[iLeft+iRight] = aRight[iRight];
95369         iRight++;
95370       }else if( iRight==nRight ){
95371         aIdx[iLeft+iRight] = aLeft[iLeft];
95372         iLeft++;
95373       }else{
95374         float fLeft = aDistance[aLeft[iLeft]];
95375         float fRight = aDistance[aRight[iRight]];
95376         if( fLeft<fRight ){
95377           aIdx[iLeft+iRight] = aLeft[iLeft];
95378           iLeft++;
95379         }else{
95380           aIdx[iLeft+iRight] = aRight[iRight];
95381           iRight++;
95382         }
95383       }
95384     }
95385
95386 #if 0
95387     /* Check that the sort worked */
95388     {
95389       int jj;
95390       for(jj=1; jj<nIdx; jj++){
95391         float left = aDistance[aIdx[jj-1]];
95392         float right = aDistance[aIdx[jj]];
95393         assert( left<=right );
95394       }
95395     }
95396 #endif
95397   }
95398 }
95399
95400 /*
95401 ** Arguments aIdx, aCell and aSpare all point to arrays of size
95402 ** nIdx. The aIdx array contains the set of integers from 0 to 
95403 ** (nIdx-1) in no particular order. This function sorts the values
95404 ** in aIdx according to dimension iDim of the cells in aCell. The
95405 ** minimum value of dimension iDim is considered first, the
95406 ** maximum used to break ties.
95407 **
95408 ** The aSpare array is used as temporary working space by the
95409 ** sorting algorithm.
95410 */
95411 static void SortByDimension(
95412   Rtree *pRtree,
95413   int *aIdx, 
95414   int nIdx, 
95415   int iDim, 
95416   RtreeCell *aCell, 
95417   int *aSpare
95418 ){
95419   if( nIdx>1 ){
95420
95421     int iLeft = 0;
95422     int iRight = 0;
95423
95424     int nLeft = nIdx/2;
95425     int nRight = nIdx-nLeft;
95426     int *aLeft = aIdx;
95427     int *aRight = &aIdx[nLeft];
95428
95429     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
95430     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
95431
95432     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
95433     aLeft = aSpare;
95434     while( iLeft<nLeft || iRight<nRight ){
95435       double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
95436       double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
95437       double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
95438       double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
95439       if( (iLeft!=nLeft) && ((iRight==nRight)
95440        || (xleft1<xright1)
95441        || (xleft1==xright1 && xleft2<xright2)
95442       )){
95443         aIdx[iLeft+iRight] = aLeft[iLeft];
95444         iLeft++;
95445       }else{
95446         aIdx[iLeft+iRight] = aRight[iRight];
95447         iRight++;
95448       }
95449     }
95450
95451 #if 0
95452     /* Check that the sort worked */
95453     {
95454       int jj;
95455       for(jj=1; jj<nIdx; jj++){
95456         float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
95457         float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
95458         float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
95459         float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
95460         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
95461       }
95462     }
95463 #endif
95464   }
95465 }
95466
95467 #if VARIANT_RSTARTREE_SPLIT
95468 /*
95469 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
95470 */
95471 static int splitNodeStartree(
95472   Rtree *pRtree,
95473   RtreeCell *aCell,
95474   int nCell,
95475   RtreeNode *pLeft,
95476   RtreeNode *pRight,
95477   RtreeCell *pBboxLeft,
95478   RtreeCell *pBboxRight
95479 ){
95480   int **aaSorted;
95481   int *aSpare;
95482   int ii;
95483
95484   int iBestDim;
95485   int iBestSplit;
95486   float fBestMargin;
95487
95488   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
95489
95490   aaSorted = (int **)sqlite3_malloc(nByte);
95491   if( !aaSorted ){
95492     return SQLITE_NOMEM;
95493   }
95494
95495   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
95496   memset(aaSorted, 0, nByte);
95497   for(ii=0; ii<pRtree->nDim; ii++){
95498     int jj;
95499     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
95500     for(jj=0; jj<nCell; jj++){
95501       aaSorted[ii][jj] = jj;
95502     }
95503     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
95504   }
95505
95506   for(ii=0; ii<pRtree->nDim; ii++){
95507     float margin = 0.0;
95508     float fBestOverlap;
95509     float fBestArea;
95510     int iBestLeft;
95511     int nLeft;
95512
95513     for(
95514       nLeft=RTREE_MINCELLS(pRtree); 
95515       nLeft<=(nCell-RTREE_MINCELLS(pRtree)); 
95516       nLeft++
95517     ){
95518       RtreeCell left;
95519       RtreeCell right;
95520       int kk;
95521       float overlap;
95522       float area;
95523
95524       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
95525       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
95526       for(kk=1; kk<(nCell-1); kk++){
95527         if( kk<nLeft ){
95528           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
95529         }else{
95530           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
95531         }
95532       }
95533       margin += cellMargin(pRtree, &left);
95534       margin += cellMargin(pRtree, &right);
95535       overlap = cellOverlap(pRtree, &left, &right, 1, -1);
95536       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
95537       if( (nLeft==RTREE_MINCELLS(pRtree))
95538        || (overlap<fBestOverlap)
95539        || (overlap==fBestOverlap && area<fBestArea)
95540       ){
95541         iBestLeft = nLeft;
95542         fBestOverlap = overlap;
95543         fBestArea = area;
95544       }
95545     }
95546
95547     if( ii==0 || margin<fBestMargin ){
95548       iBestDim = ii;
95549       fBestMargin = margin;
95550       iBestSplit = iBestLeft;
95551     }
95552   }
95553
95554   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
95555   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
95556   for(ii=0; ii<nCell; ii++){
95557     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
95558     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
95559     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
95560     nodeInsertCell(pRtree, pTarget, pCell);
95561     cellUnion(pRtree, pBbox, pCell);
95562   }
95563
95564   sqlite3_free(aaSorted);
95565   return SQLITE_OK;
95566 }
95567 #endif
95568
95569 #if VARIANT_GUTTMAN_SPLIT
95570 /*
95571 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
95572 */
95573 static int splitNodeGuttman(
95574   Rtree *pRtree,
95575   RtreeCell *aCell,
95576   int nCell,
95577   RtreeNode *pLeft,
95578   RtreeNode *pRight,
95579   RtreeCell *pBboxLeft,
95580   RtreeCell *pBboxRight
95581 ){
95582   int iLeftSeed = 0;
95583   int iRightSeed = 1;
95584   int *aiUsed;
95585   int i;
95586
95587   aiUsed = sqlite3_malloc(sizeof(int)*nCell);
95588   memset(aiUsed, 0, sizeof(int)*nCell);
95589
95590   PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
95591
95592   memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
95593   memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
95594   nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
95595   nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
95596   aiUsed[iLeftSeed] = 1;
95597   aiUsed[iRightSeed] = 1;
95598
95599   for(i=nCell-2; i>0; i--){
95600     RtreeCell *pNext;
95601     pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
95602     float diff =  
95603       cellGrowth(pRtree, pBboxLeft, pNext) - 
95604       cellGrowth(pRtree, pBboxRight, pNext)
95605     ;
95606     if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
95607      || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
95608     ){
95609       nodeInsertCell(pRtree, pRight, pNext);
95610       cellUnion(pRtree, pBboxRight, pNext);
95611     }else{
95612       nodeInsertCell(pRtree, pLeft, pNext);
95613       cellUnion(pRtree, pBboxLeft, pNext);
95614     }
95615   }
95616
95617   sqlite3_free(aiUsed);
95618   return SQLITE_OK;
95619 }
95620 #endif
95621
95622 static int updateMapping(
95623   Rtree *pRtree, 
95624   i64 iRowid, 
95625   RtreeNode *pNode, 
95626   int iHeight
95627 ){
95628   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
95629   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
95630   if( iHeight>0 ){
95631     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
95632     if( pChild ){
95633       nodeRelease(pRtree, pChild->pParent);
95634       nodeReference(pNode);
95635       pChild->pParent = pNode;
95636     }
95637   }
95638   return xSetMapping(pRtree, iRowid, pNode->iNode);
95639 }
95640
95641 static int SplitNode(
95642   Rtree *pRtree,
95643   RtreeNode *pNode,
95644   RtreeCell *pCell,
95645   int iHeight
95646 ){
95647   int i;
95648   int newCellIsRight = 0;
95649
95650   int rc = SQLITE_OK;
95651   int nCell = NCELL(pNode);
95652   RtreeCell *aCell;
95653   int *aiUsed;
95654
95655   RtreeNode *pLeft = 0;
95656   RtreeNode *pRight = 0;
95657
95658   RtreeCell leftbbox;
95659   RtreeCell rightbbox;
95660
95661   /* Allocate an array and populate it with a copy of pCell and 
95662   ** all cells from node pLeft. Then zero the original node.
95663   */
95664   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
95665   if( !aCell ){
95666     rc = SQLITE_NOMEM;
95667     goto splitnode_out;
95668   }
95669   aiUsed = (int *)&aCell[nCell+1];
95670   memset(aiUsed, 0, sizeof(int)*(nCell+1));
95671   for(i=0; i<nCell; i++){
95672     nodeGetCell(pRtree, pNode, i, &aCell[i]);
95673   }
95674   nodeZero(pRtree, pNode);
95675   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
95676   nCell++;
95677
95678   if( pNode->iNode==1 ){
95679     pRight = nodeNew(pRtree, pNode, 1);
95680     pLeft = nodeNew(pRtree, pNode, 1);
95681     pRtree->iDepth++;
95682     pNode->isDirty = 1;
95683     writeInt16(pNode->zData, pRtree->iDepth);
95684   }else{
95685     pLeft = pNode;
95686     pRight = nodeNew(pRtree, pLeft->pParent, 1);
95687     nodeReference(pLeft);
95688   }
95689
95690   if( !pLeft || !pRight ){
95691     rc = SQLITE_NOMEM;
95692     goto splitnode_out;
95693   }
95694
95695   memset(pLeft->zData, 0, pRtree->iNodeSize);
95696   memset(pRight->zData, 0, pRtree->iNodeSize);
95697
95698   rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
95699   if( rc!=SQLITE_OK ){
95700     goto splitnode_out;
95701   }
95702
95703   /* Ensure both child nodes have node numbers assigned to them. */
95704   if( (0==pRight->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pRight)))
95705    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
95706   ){
95707     goto splitnode_out;
95708   }
95709
95710   rightbbox.iRowid = pRight->iNode;
95711   leftbbox.iRowid = pLeft->iNode;
95712
95713   if( pNode->iNode==1 ){
95714     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
95715     if( rc!=SQLITE_OK ){
95716       goto splitnode_out;
95717     }
95718   }else{
95719     RtreeNode *pParent = pLeft->pParent;
95720     int iCell = nodeParentIndex(pRtree, pLeft);
95721     nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
95722     AdjustTree(pRtree, pParent, &leftbbox);
95723   }
95724   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
95725     goto splitnode_out;
95726   }
95727
95728   for(i=0; i<NCELL(pRight); i++){
95729     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
95730     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
95731     if( iRowid==pCell->iRowid ){
95732       newCellIsRight = 1;
95733     }
95734     if( rc!=SQLITE_OK ){
95735       goto splitnode_out;
95736     }
95737   }
95738   if( pNode->iNode==1 ){
95739     for(i=0; i<NCELL(pLeft); i++){
95740       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
95741       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
95742       if( rc!=SQLITE_OK ){
95743         goto splitnode_out;
95744       }
95745     }
95746   }else if( newCellIsRight==0 ){
95747     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
95748   }
95749
95750   if( rc==SQLITE_OK ){
95751     rc = nodeRelease(pRtree, pRight);
95752     pRight = 0;
95753   }
95754   if( rc==SQLITE_OK ){
95755     rc = nodeRelease(pRtree, pLeft);
95756     pLeft = 0;
95757   }
95758
95759 splitnode_out:
95760   nodeRelease(pRtree, pRight);
95761   nodeRelease(pRtree, pLeft);
95762   sqlite3_free(aCell);
95763   return rc;
95764 }
95765
95766 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
95767   int rc = SQLITE_OK;
95768   if( pLeaf->iNode!=1 && pLeaf->pParent==0 ){
95769     sqlite3_bind_int64(pRtree->pReadParent, 1, pLeaf->iNode);
95770     if( sqlite3_step(pRtree->pReadParent)==SQLITE_ROW ){
95771       i64 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
95772       rc = nodeAcquire(pRtree, iNode, 0, &pLeaf->pParent);
95773     }else{
95774       rc = SQLITE_ERROR;
95775     }
95776     sqlite3_reset(pRtree->pReadParent);
95777     if( rc==SQLITE_OK ){
95778       rc = fixLeafParent(pRtree, pLeaf->pParent);
95779     }
95780   }
95781   return rc;
95782 }
95783
95784 static int deleteCell(Rtree *, RtreeNode *, int, int);
95785
95786 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
95787   int rc;
95788   RtreeNode *pParent;
95789   int iCell;
95790
95791   assert( pNode->nRef==1 );
95792
95793   /* Remove the entry in the parent cell. */
95794   iCell = nodeParentIndex(pRtree, pNode);
95795   pParent = pNode->pParent;
95796   pNode->pParent = 0;
95797   if( SQLITE_OK!=(rc = deleteCell(pRtree, pParent, iCell, iHeight+1)) 
95798    || SQLITE_OK!=(rc = nodeRelease(pRtree, pParent))
95799   ){
95800     return rc;
95801   }
95802
95803   /* Remove the xxx_node entry. */
95804   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
95805   sqlite3_step(pRtree->pDeleteNode);
95806   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
95807     return rc;
95808   }
95809
95810   /* Remove the xxx_parent entry. */
95811   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
95812   sqlite3_step(pRtree->pDeleteParent);
95813   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
95814     return rc;
95815   }
95816   
95817   /* Remove the node from the in-memory hash table and link it into
95818   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
95819   */
95820   nodeHashDelete(pRtree, pNode);
95821   pNode->iNode = iHeight;
95822   pNode->pNext = pRtree->pDeleted;
95823   pNode->nRef++;
95824   pRtree->pDeleted = pNode;
95825
95826   return SQLITE_OK;
95827 }
95828
95829 static void fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
95830   RtreeNode *pParent = pNode->pParent;
95831   if( pParent ){
95832     int ii; 
95833     int nCell = NCELL(pNode);
95834     RtreeCell box;                            /* Bounding box for pNode */
95835     nodeGetCell(pRtree, pNode, 0, &box);
95836     for(ii=1; ii<nCell; ii++){
95837       RtreeCell cell;
95838       nodeGetCell(pRtree, pNode, ii, &cell);
95839       cellUnion(pRtree, &box, &cell);
95840     }
95841     box.iRowid = pNode->iNode;
95842     ii = nodeParentIndex(pRtree, pNode);
95843     nodeOverwriteCell(pRtree, pParent, &box, ii);
95844     fixBoundingBox(pRtree, pParent);
95845   }
95846 }
95847
95848 /*
95849 ** Delete the cell at index iCell of node pNode. After removing the
95850 ** cell, adjust the r-tree data structure if required.
95851 */
95852 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
95853   int rc;
95854
95855   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
95856     return rc;
95857   }
95858
95859   /* Remove the cell from the node. This call just moves bytes around
95860   ** the in-memory node image, so it cannot fail.
95861   */
95862   nodeDeleteCell(pRtree, pNode, iCell);
95863
95864   /* If the node is not the tree root and now has less than the minimum
95865   ** number of cells, remove it from the tree. Otherwise, update the
95866   ** cell in the parent node so that it tightly contains the updated
95867   ** node.
95868   */
95869   if( pNode->iNode!=1 ){
95870     RtreeNode *pParent = pNode->pParent;
95871     if( (pParent->iNode!=1 || NCELL(pParent)!=1) 
95872      && (NCELL(pNode)<RTREE_MINCELLS(pRtree))
95873     ){
95874       rc = removeNode(pRtree, pNode, iHeight);
95875     }else{
95876       fixBoundingBox(pRtree, pNode);
95877     }
95878   }
95879
95880   return rc;
95881 }
95882
95883 static int Reinsert(
95884   Rtree *pRtree, 
95885   RtreeNode *pNode, 
95886   RtreeCell *pCell, 
95887   int iHeight
95888 ){
95889   int *aOrder;
95890   int *aSpare;
95891   RtreeCell *aCell;
95892   float *aDistance;
95893   int nCell;
95894   float aCenterCoord[RTREE_MAX_DIMENSIONS];
95895   int iDim;
95896   int ii;
95897   int rc = SQLITE_OK;
95898
95899   memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
95900
95901   nCell = NCELL(pNode)+1;
95902
95903   /* Allocate the buffers used by this operation. The allocation is
95904   ** relinquished before this function returns.
95905   */
95906   aCell = (RtreeCell *)sqlite3_malloc(nCell * (
95907     sizeof(RtreeCell) +         /* aCell array */
95908     sizeof(int)       +         /* aOrder array */
95909     sizeof(int)       +         /* aSpare array */
95910     sizeof(float)               /* aDistance array */
95911   ));
95912   if( !aCell ){
95913     return SQLITE_NOMEM;
95914   }
95915   aOrder    = (int *)&aCell[nCell];
95916   aSpare    = (int *)&aOrder[nCell];
95917   aDistance = (float *)&aSpare[nCell];
95918
95919   for(ii=0; ii<nCell; ii++){
95920     if( ii==(nCell-1) ){
95921       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
95922     }else{
95923       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
95924     }
95925     aOrder[ii] = ii;
95926     for(iDim=0; iDim<pRtree->nDim; iDim++){
95927       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
95928       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
95929     }
95930   }
95931   for(iDim=0; iDim<pRtree->nDim; iDim++){
95932     aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0);
95933   }
95934
95935   for(ii=0; ii<nCell; ii++){
95936     aDistance[ii] = 0.0;
95937     for(iDim=0; iDim<pRtree->nDim; iDim++){
95938       float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) - 
95939           DCOORD(aCell[ii].aCoord[iDim*2]);
95940       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
95941     }
95942   }
95943
95944   SortByDistance(aOrder, nCell, aDistance, aSpare);
95945   nodeZero(pRtree, pNode);
95946
95947   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
95948     RtreeCell *p = &aCell[aOrder[ii]];
95949     nodeInsertCell(pRtree, pNode, p);
95950     if( p->iRowid==pCell->iRowid ){
95951       if( iHeight==0 ){
95952         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
95953       }else{
95954         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
95955       }
95956     }
95957   }
95958   if( rc==SQLITE_OK ){
95959     fixBoundingBox(pRtree, pNode);
95960   }
95961   for(; rc==SQLITE_OK && ii<nCell; ii++){
95962     /* Find a node to store this cell in. pNode->iNode currently contains
95963     ** the height of the sub-tree headed by the cell.
95964     */
95965     RtreeNode *pInsert;
95966     RtreeCell *p = &aCell[aOrder[ii]];
95967     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
95968     if( rc==SQLITE_OK ){
95969       int rc2;
95970       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
95971       rc2 = nodeRelease(pRtree, pInsert);
95972       if( rc==SQLITE_OK ){
95973         rc = rc2;
95974       }
95975     }
95976   }
95977
95978   sqlite3_free(aCell);
95979   return rc;
95980 }
95981
95982 /*
95983 ** Insert cell pCell into node pNode. Node pNode is the head of a 
95984 ** subtree iHeight high (leaf nodes have iHeight==0).
95985 */
95986 static int rtreeInsertCell(
95987   Rtree *pRtree,
95988   RtreeNode *pNode,
95989   RtreeCell *pCell,
95990   int iHeight
95991 ){
95992   int rc = SQLITE_OK;
95993   if( iHeight>0 ){
95994     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
95995     if( pChild ){
95996       nodeRelease(pRtree, pChild->pParent);
95997       nodeReference(pNode);
95998       pChild->pParent = pNode;
95999     }
96000   }
96001   if( nodeInsertCell(pRtree, pNode, pCell) ){
96002 #if VARIANT_RSTARTREE_REINSERT
96003     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
96004       rc = SplitNode(pRtree, pNode, pCell, iHeight);
96005     }else{
96006       pRtree->iReinsertHeight = iHeight;
96007       rc = Reinsert(pRtree, pNode, pCell, iHeight);
96008     }
96009 #else
96010     rc = SplitNode(pRtree, pNode, pCell, iHeight);
96011 #endif
96012   }else{
96013     AdjustTree(pRtree, pNode, pCell);
96014     if( iHeight==0 ){
96015       rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
96016     }else{
96017       rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
96018     }
96019   }
96020   return rc;
96021 }
96022
96023 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
96024   int ii;
96025   int rc = SQLITE_OK;
96026   int nCell = NCELL(pNode);
96027
96028   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
96029     RtreeNode *pInsert;
96030     RtreeCell cell;
96031     nodeGetCell(pRtree, pNode, ii, &cell);
96032
96033     /* Find a node to store this cell in. pNode->iNode currently contains
96034     ** the height of the sub-tree headed by the cell.
96035     */
96036     rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert);
96037     if( rc==SQLITE_OK ){
96038       int rc2;
96039       rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode);
96040       rc2 = nodeRelease(pRtree, pInsert);
96041       if( rc==SQLITE_OK ){
96042         rc = rc2;
96043       }
96044     }
96045   }
96046   return rc;
96047 }
96048
96049 /*
96050 ** Select a currently unused rowid for a new r-tree record.
96051 */
96052 static int newRowid(Rtree *pRtree, i64 *piRowid){
96053   int rc;
96054   sqlite3_bind_null(pRtree->pWriteRowid, 1);
96055   sqlite3_bind_null(pRtree->pWriteRowid, 2);
96056   sqlite3_step(pRtree->pWriteRowid);
96057   rc = sqlite3_reset(pRtree->pWriteRowid);
96058   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
96059   return rc;
96060 }
96061
96062 #ifndef NDEBUG
96063 static int hashIsEmpty(Rtree *pRtree){
96064   int ii;
96065   for(ii=0; ii<HASHSIZE; ii++){
96066     assert( !pRtree->aHash[ii] );
96067   }
96068   return 1;
96069 }
96070 #endif
96071
96072 /*
96073 ** The xUpdate method for rtree module virtual tables.
96074 */
96075 int rtreeUpdate(
96076   sqlite3_vtab *pVtab, 
96077   int nData, 
96078   sqlite3_value **azData, 
96079   sqlite_int64 *pRowid
96080 ){
96081   Rtree *pRtree = (Rtree *)pVtab;
96082   int rc = SQLITE_OK;
96083
96084   rtreeReference(pRtree);
96085
96086   assert(nData>=1);
96087   assert(hashIsEmpty(pRtree));
96088
96089   /* If azData[0] is not an SQL NULL value, it is the rowid of a
96090   ** record to delete from the r-tree table. The following block does
96091   ** just that.
96092   */
96093   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
96094     i64 iDelete;                /* The rowid to delete */
96095     RtreeNode *pLeaf;           /* Leaf node containing record iDelete */
96096     int iCell;                  /* Index of iDelete cell in pLeaf */
96097     RtreeNode *pRoot;
96098
96099     /* Obtain a reference to the root node to initialise Rtree.iDepth */
96100     rc = nodeAcquire(pRtree, 1, 0, &pRoot);
96101
96102     /* Obtain a reference to the leaf node that contains the entry 
96103     ** about to be deleted. 
96104     */
96105     if( rc==SQLITE_OK ){
96106       iDelete = sqlite3_value_int64(azData[0]);
96107       rc = findLeafNode(pRtree, iDelete, &pLeaf);
96108     }
96109
96110     /* Delete the cell in question from the leaf node. */
96111     if( rc==SQLITE_OK ){
96112       int rc2;
96113       iCell = nodeRowidIndex(pRtree, pLeaf, iDelete);
96114       rc = deleteCell(pRtree, pLeaf, iCell, 0);
96115       rc2 = nodeRelease(pRtree, pLeaf);
96116       if( rc==SQLITE_OK ){
96117         rc = rc2;
96118       }
96119     }
96120
96121     /* Delete the corresponding entry in the <rtree>_rowid table. */
96122     if( rc==SQLITE_OK ){
96123       sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
96124       sqlite3_step(pRtree->pDeleteRowid);
96125       rc = sqlite3_reset(pRtree->pDeleteRowid);
96126     }
96127
96128     /* Check if the root node now has exactly one child. If so, remove
96129     ** it, schedule the contents of the child for reinsertion and 
96130     ** reduce the tree height by one.
96131     **
96132     ** This is equivalent to copying the contents of the child into
96133     ** the root node (the operation that Gutman's paper says to perform 
96134     ** in this scenario).
96135     */
96136     if( rc==SQLITE_OK && pRtree->iDepth>0 ){
96137       if( rc==SQLITE_OK && NCELL(pRoot)==1 ){
96138         RtreeNode *pChild;
96139         i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
96140         rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
96141         if( rc==SQLITE_OK ){
96142           rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
96143         }
96144         if( rc==SQLITE_OK ){
96145           pRtree->iDepth--;
96146           writeInt16(pRoot->zData, pRtree->iDepth);
96147           pRoot->isDirty = 1;
96148         }
96149       }
96150     }
96151
96152     /* Re-insert the contents of any underfull nodes removed from the tree. */
96153     for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
96154       if( rc==SQLITE_OK ){
96155         rc = reinsertNodeContent(pRtree, pLeaf);
96156       }
96157       pRtree->pDeleted = pLeaf->pNext;
96158       sqlite3_free(pLeaf);
96159     }
96160
96161     /* Release the reference to the root node. */
96162     if( rc==SQLITE_OK ){
96163       rc = nodeRelease(pRtree, pRoot);
96164     }else{
96165       nodeRelease(pRtree, pRoot);
96166     }
96167   }
96168
96169   /* If the azData[] array contains more than one element, elements
96170   ** (azData[2]..azData[argc-1]) contain a new record to insert into
96171   ** the r-tree structure.
96172   */
96173   if( rc==SQLITE_OK && nData>1 ){
96174     /* Insert a new record into the r-tree */
96175     RtreeCell cell;
96176     int ii;
96177     RtreeNode *pLeaf;
96178
96179     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
96180     assert( nData==(pRtree->nDim*2 + 3) );
96181     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
96182       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
96183         cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
96184         cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
96185         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
96186           rc = SQLITE_CONSTRAINT;
96187           goto constraint;
96188         }
96189       }
96190     }else{
96191       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
96192         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
96193         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
96194         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
96195           rc = SQLITE_CONSTRAINT;
96196           goto constraint;
96197         }
96198       }
96199     }
96200
96201     /* Figure out the rowid of the new row. */
96202     if( sqlite3_value_type(azData[2])==SQLITE_NULL ){
96203       rc = newRowid(pRtree, &cell.iRowid);
96204     }else{
96205       cell.iRowid = sqlite3_value_int64(azData[2]);
96206       sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
96207       if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){
96208         sqlite3_reset(pRtree->pReadRowid);
96209         rc = SQLITE_CONSTRAINT;
96210         goto constraint;
96211       }
96212       rc = sqlite3_reset(pRtree->pReadRowid);
96213     }
96214
96215     if( rc==SQLITE_OK ){
96216       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
96217     }
96218     if( rc==SQLITE_OK ){
96219       int rc2;
96220       pRtree->iReinsertHeight = -1;
96221       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
96222       rc2 = nodeRelease(pRtree, pLeaf);
96223       if( rc==SQLITE_OK ){
96224         rc = rc2;
96225       }
96226     }
96227   }
96228
96229 constraint:
96230   rtreeRelease(pRtree);
96231   return rc;
96232 }
96233
96234 /*
96235 ** The xRename method for rtree module virtual tables.
96236 */
96237 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
96238   Rtree *pRtree = (Rtree *)pVtab;
96239   int rc = SQLITE_NOMEM;
96240   char *zSql = sqlite3_mprintf(
96241     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
96242     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
96243     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
96244     , pRtree->zDb, pRtree->zName, zNewName 
96245     , pRtree->zDb, pRtree->zName, zNewName 
96246     , pRtree->zDb, pRtree->zName, zNewName
96247   );
96248   if( zSql ){
96249     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
96250     sqlite3_free(zSql);
96251   }
96252   return rc;
96253 }
96254
96255 static sqlite3_module rtreeModule = {
96256   0,                         /* iVersion */
96257   rtreeCreate,                /* xCreate - create a table */
96258   rtreeConnect,               /* xConnect - connect to an existing table */
96259   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
96260   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
96261   rtreeDestroy,               /* xDestroy - Drop a table */
96262   rtreeOpen,                  /* xOpen - open a cursor */
96263   rtreeClose,                 /* xClose - close a cursor */
96264   rtreeFilter,                /* xFilter - configure scan constraints */
96265   rtreeNext,                  /* xNext - advance a cursor */
96266   rtreeEof,                   /* xEof */
96267   rtreeColumn,                /* xColumn - read data */
96268   rtreeRowid,                 /* xRowid - read data */
96269   rtreeUpdate,                /* xUpdate - write data */
96270   0,                          /* xBegin - begin transaction */
96271   0,                          /* xSync - sync transaction */
96272   0,                          /* xCommit - commit transaction */
96273   0,                          /* xRollback - rollback transaction */
96274   0,                          /* xFindFunction - function overloading */
96275   rtreeRename                 /* xRename - rename the table */
96276 };
96277
96278 static int rtreeSqlInit(
96279   Rtree *pRtree, 
96280   sqlite3 *db, 
96281   const char *zDb, 
96282   const char *zPrefix, 
96283   int isCreate
96284 ){
96285   int rc = SQLITE_OK;
96286
96287   #define N_STATEMENT 9
96288   static const char *azSql[N_STATEMENT] = {
96289     /* Read and write the xxx_node table */
96290     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
96291     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
96292     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
96293
96294     /* Read and write the xxx_rowid table */
96295     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
96296     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
96297     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
96298
96299     /* Read and write the xxx_parent table */
96300     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
96301     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
96302     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
96303   };
96304   sqlite3_stmt **appStmt[N_STATEMENT];
96305   int i;
96306
96307   pRtree->db = db;
96308
96309   if( isCreate ){
96310     char *zCreate = sqlite3_mprintf(
96311 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
96312 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
96313 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
96314 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
96315       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
96316     );
96317     if( !zCreate ){
96318       return SQLITE_NOMEM;
96319     }
96320     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
96321     sqlite3_free(zCreate);
96322     if( rc!=SQLITE_OK ){
96323       return rc;
96324     }
96325   }
96326
96327   appStmt[0] = &pRtree->pReadNode;
96328   appStmt[1] = &pRtree->pWriteNode;
96329   appStmt[2] = &pRtree->pDeleteNode;
96330   appStmt[3] = &pRtree->pReadRowid;
96331   appStmt[4] = &pRtree->pWriteRowid;
96332   appStmt[5] = &pRtree->pDeleteRowid;
96333   appStmt[6] = &pRtree->pReadParent;
96334   appStmt[7] = &pRtree->pWriteParent;
96335   appStmt[8] = &pRtree->pDeleteParent;
96336
96337   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
96338     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
96339     if( zSql ){
96340       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0); 
96341     }else{
96342       rc = SQLITE_NOMEM;
96343     }
96344     sqlite3_free(zSql);
96345   }
96346
96347   return rc;
96348 }
96349
96350 /*
96351 ** This routine queries database handle db for the page-size used by
96352 ** database zDb. If successful, the page-size in bytes is written to
96353 ** *piPageSize and SQLITE_OK returned. Otherwise, and an SQLite error 
96354 ** code is returned.
96355 */
96356 static int getPageSize(sqlite3 *db, const char *zDb, int *piPageSize){
96357   int rc = SQLITE_NOMEM;
96358   char *zSql;
96359   sqlite3_stmt *pStmt = 0;
96360
96361   zSql = sqlite3_mprintf("PRAGMA %Q.page_size", zDb);
96362   if( !zSql ){
96363     return SQLITE_NOMEM;
96364   }
96365
96366   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
96367   sqlite3_free(zSql);
96368   if( rc!=SQLITE_OK ){
96369     return rc;
96370   }
96371
96372   if( SQLITE_ROW==sqlite3_step(pStmt) ){
96373     *piPageSize = sqlite3_column_int(pStmt, 0);
96374   }
96375   return sqlite3_finalize(pStmt);
96376 }
96377
96378 /* 
96379 ** This function is the implementation of both the xConnect and xCreate
96380 ** methods of the r-tree virtual table.
96381 **
96382 **   argv[0]   -> module name
96383 **   argv[1]   -> database name
96384 **   argv[2]   -> table name
96385 **   argv[...] -> column names...
96386 */
96387 static int rtreeInit(
96388   sqlite3 *db,                        /* Database connection */
96389   void *pAux,                         /* Pointer to head of rtree list */
96390   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
96391   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
96392   char **pzErr,                       /* OUT: Error message, if any */
96393   int isCreate,                       /* True for xCreate, false for xConnect */
96394   int eCoordType                      /* One of the RTREE_COORD_* constants */
96395 ){
96396   int rc = SQLITE_OK;
96397   int iPageSize = 0;
96398   Rtree *pRtree;
96399   int nDb;              /* Length of string argv[1] */
96400   int nName;            /* Length of string argv[2] */
96401
96402   const char *aErrMsg[] = {
96403     0,                                                    /* 0 */
96404     "Wrong number of columns for an rtree table",         /* 1 */
96405     "Too few columns for an rtree table",                 /* 2 */
96406     "Too many columns for an rtree table"                 /* 3 */
96407   };
96408
96409   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
96410   if( aErrMsg[iErr] ){
96411     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
96412     return SQLITE_ERROR;
96413   }
96414
96415   rc = getPageSize(db, argv[1], &iPageSize);
96416   if( rc!=SQLITE_OK ){
96417     return rc;
96418   }
96419
96420   /* Allocate the sqlite3_vtab structure */
96421   nDb = strlen(argv[1]);
96422   nName = strlen(argv[2]);
96423   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
96424   if( !pRtree ){
96425     return SQLITE_NOMEM;
96426   }
96427   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
96428   pRtree->nBusy = 1;
96429   pRtree->base.pModule = &rtreeModule;
96430   pRtree->zDb = (char *)&pRtree[1];
96431   pRtree->zName = &pRtree->zDb[nDb+1];
96432   pRtree->nDim = (argc-4)/2;
96433   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
96434   pRtree->eCoordType = eCoordType;
96435   memcpy(pRtree->zDb, argv[1], nDb);
96436   memcpy(pRtree->zName, argv[2], nName);
96437
96438   /* Figure out the node size to use. By default, use 64 bytes less than
96439   ** the database page-size. This ensures that each node is stored on
96440   ** a single database page.
96441   **
96442   ** If the databasd page-size is so large that more than RTREE_MAXCELLS
96443   ** entries would fit in a single node, use a smaller node-size.
96444   */
96445   pRtree->iNodeSize = iPageSize-64;
96446   if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
96447     pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
96448   }
96449
96450   /* Create/Connect to the underlying relational database schema. If
96451   ** that is successful, call sqlite3_declare_vtab() to configure
96452   ** the r-tree table schema.
96453   */
96454   if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
96455     *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
96456   }else{
96457     char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
96458     char *zTmp;
96459     int ii;
96460     for(ii=4; zSql && ii<argc; ii++){
96461       zTmp = zSql;
96462       zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
96463       sqlite3_free(zTmp);
96464     }
96465     if( zSql ){
96466       zTmp = zSql;
96467       zSql = sqlite3_mprintf("%s);", zTmp);
96468       sqlite3_free(zTmp);
96469     }
96470     if( !zSql || sqlite3_declare_vtab(db, zSql) ){
96471       rc = SQLITE_NOMEM;
96472     }
96473     sqlite3_free(zSql);
96474   }
96475
96476   if( rc==SQLITE_OK ){
96477     *ppVtab = (sqlite3_vtab *)pRtree;
96478   }else{
96479     rtreeRelease(pRtree);
96480   }
96481   return rc;
96482 }
96483
96484
96485 /*
96486 ** Implementation of a scalar function that decodes r-tree nodes to
96487 ** human readable strings. This can be used for debugging and analysis.
96488 **
96489 ** The scalar function takes two arguments, a blob of data containing
96490 ** an r-tree node, and the number of dimensions the r-tree indexes.
96491 ** For a two-dimensional r-tree structure called "rt", to deserialize
96492 ** all nodes, a statement like:
96493 **
96494 **   SELECT rtreenode(2, data) FROM rt_node;
96495 **
96496 ** The human readable string takes the form of a Tcl list with one
96497 ** entry for each cell in the r-tree node. Each entry is itself a
96498 ** list, containing the 8-byte rowid/pageno followed by the 
96499 ** <num-dimension>*2 coordinates.
96500 */
96501 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
96502   char *zText = 0;
96503   RtreeNode node;
96504   Rtree tree;
96505   int ii;
96506
96507   memset(&node, 0, sizeof(RtreeNode));
96508   memset(&tree, 0, sizeof(Rtree));
96509   tree.nDim = sqlite3_value_int(apArg[0]);
96510   tree.nBytesPerCell = 8 + 8 * tree.nDim;
96511   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
96512
96513   for(ii=0; ii<NCELL(&node); ii++){
96514     char zCell[512];
96515     int nCell = 0;
96516     RtreeCell cell;
96517     int jj;
96518
96519     nodeGetCell(&tree, &node, ii, &cell);
96520     sqlite3_snprintf(512-nCell,&zCell[nCell],"%d", cell.iRowid);
96521     nCell = strlen(zCell);
96522     for(jj=0; jj<tree.nDim*2; jj++){
96523       sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
96524       nCell = strlen(zCell);
96525     }
96526
96527     if( zText ){
96528       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
96529       sqlite3_free(zText);
96530       zText = zTextNew;
96531     }else{
96532       zText = sqlite3_mprintf("{%s}", zCell);
96533     }
96534   }
96535   
96536   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
96537 }
96538
96539 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
96540   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB 
96541    || sqlite3_value_bytes(apArg[0])<2
96542   ){
96543     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); 
96544   }else{
96545     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
96546     sqlite3_result_int(ctx, readInt16(zBlob));
96547   }
96548 }
96549
96550 /*
96551 ** Register the r-tree module with database handle db. This creates the
96552 ** virtual table module "rtree" and the debugging/analysis scalar 
96553 ** function "rtreenode".
96554 */
96555 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
96556   int rc = SQLITE_OK;
96557
96558   if( rc==SQLITE_OK ){
96559     int utf8 = SQLITE_UTF8;
96560     rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
96561   }
96562   if( rc==SQLITE_OK ){
96563     int utf8 = SQLITE_UTF8;
96564     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
96565   }
96566   if( rc==SQLITE_OK ){
96567     void *c = (void *)RTREE_COORD_REAL32;
96568     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
96569   }
96570   if( rc==SQLITE_OK ){
96571     void *c = (void *)RTREE_COORD_INT32;
96572     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
96573   }
96574
96575   return rc;
96576 }
96577
96578 #if !SQLITE_CORE
96579 SQLITE_API int sqlite3_extension_init(
96580   sqlite3 *db,
96581   char **pzErrMsg,
96582   const sqlite3_api_routines *pApi
96583 ){
96584   SQLITE_EXTENSION_INIT2(pApi)
96585   return sqlite3RtreeInit(db);
96586 }
96587 #endif
96588
96589 #endif
96590
96591 /************** End of rtree.c ***********************************************/
96592 /************** Begin file icu.c *********************************************/
96593 /*
96594 ** 2007 May 6
96595 **
96596 ** The author disclaims copyright to this source code.  In place of
96597 ** a legal notice, here is a blessing:
96598 **
96599 **    May you do good and not evil.
96600 **    May you find forgiveness for yourself and forgive others.
96601 **    May you share freely, never taking more than you give.
96602 **
96603 *************************************************************************
96604 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
96605 **
96606 ** This file implements an integration between the ICU library 
96607 ** ("International Components for Unicode", an open-source library 
96608 ** for handling unicode data) and SQLite. The integration uses 
96609 ** ICU to provide the following to SQLite:
96610 **
96611 **   * An implementation of the SQL regexp() function (and hence REGEXP
96612 **     operator) using the ICU uregex_XX() APIs.
96613 **
96614 **   * Implementations of the SQL scalar upper() and lower() functions
96615 **     for case mapping.
96616 **
96617 **   * Integration of ICU and SQLite collation seqences.
96618 **
96619 **   * An implementation of the LIKE operator that uses ICU to 
96620 **     provide case-independent matching.
96621 */
96622
96623 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
96624
96625 /* Include ICU headers */
96626 #include <unicode/utypes.h>
96627 #include <unicode/uregex.h>
96628 #include <unicode/ustring.h>
96629 #include <unicode/ucol.h>
96630
96631
96632 #ifndef SQLITE_CORE
96633   #include "sqlite3ext.h"
96634   SQLITE_EXTENSION_INIT1
96635 #else
96636   #include "sqlite3.h"
96637 #endif
96638
96639 /*
96640 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
96641 ** operator.
96642 */
96643 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
96644 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
96645 #endif
96646
96647 /*
96648 ** Version of sqlite3_free() that is always a function, never a macro.
96649 */
96650 static void xFree(void *p){
96651   sqlite3_free(p);
96652 }
96653
96654 /*
96655 ** Compare two UTF-8 strings for equality where the first string is
96656 ** a "LIKE" expression. Return true (1) if they are the same and 
96657 ** false (0) if they are different.
96658 */
96659 static int icuLikeCompare(
96660   const uint8_t *zPattern,   /* LIKE pattern */
96661   const uint8_t *zString,    /* The UTF-8 string to compare against */
96662   const UChar32 uEsc         /* The escape character */
96663 ){
96664   static const int MATCH_ONE = (UChar32)'_';
96665   static const int MATCH_ALL = (UChar32)'%';
96666
96667   int iPattern = 0;       /* Current byte index in zPattern */
96668   int iString = 0;        /* Current byte index in zString */
96669
96670   int prevEscape = 0;     /* True if the previous character was uEsc */
96671
96672   while( zPattern[iPattern]!=0 ){
96673
96674     /* Read (and consume) the next character from the input pattern. */
96675     UChar32 uPattern;
96676     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
96677     assert(uPattern!=0);
96678
96679     /* There are now 4 possibilities:
96680     **
96681     **     1. uPattern is an unescaped match-all character "%",
96682     **     2. uPattern is an unescaped match-one character "_",
96683     **     3. uPattern is an unescaped escape character, or
96684     **     4. uPattern is to be handled as an ordinary character
96685     */
96686     if( !prevEscape && uPattern==MATCH_ALL ){
96687       /* Case 1. */
96688       uint8_t c;
96689
96690       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
96691       ** MATCH_ALL. For each MATCH_ONE, skip one character in the 
96692       ** test string.
96693       */
96694       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
96695         if( c==MATCH_ONE ){
96696           if( zString[iString]==0 ) return 0;
96697           U8_FWD_1_UNSAFE(zString, iString);
96698         }
96699         iPattern++;
96700       }
96701
96702       if( zPattern[iPattern]==0 ) return 1;
96703
96704       while( zString[iString] ){
96705         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
96706           return 1;
96707         }
96708         U8_FWD_1_UNSAFE(zString, iString);
96709       }
96710       return 0;
96711
96712     }else if( !prevEscape && uPattern==MATCH_ONE ){
96713       /* Case 2. */
96714       if( zString[iString]==0 ) return 0;
96715       U8_FWD_1_UNSAFE(zString, iString);
96716
96717     }else if( !prevEscape && uPattern==uEsc){
96718       /* Case 3. */
96719       prevEscape = 1;
96720
96721     }else{
96722       /* Case 4. */
96723       UChar32 uString;
96724       U8_NEXT_UNSAFE(zString, iString, uString);
96725       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
96726       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
96727       if( uString!=uPattern ){
96728         return 0;
96729       }
96730       prevEscape = 0;
96731     }
96732   }
96733
96734   return zString[iString]==0;
96735 }
96736
96737 /*
96738 ** Implementation of the like() SQL function.  This function implements
96739 ** the build-in LIKE operator.  The first argument to the function is the
96740 ** pattern and the second argument is the string.  So, the SQL statements:
96741 **
96742 **       A LIKE B
96743 **
96744 ** is implemented as like(B, A). If there is an escape character E, 
96745 **
96746 **       A LIKE B ESCAPE E
96747 **
96748 ** is mapped to like(B, A, E).
96749 */
96750 static void icuLikeFunc(
96751   sqlite3_context *context, 
96752   int argc, 
96753   sqlite3_value **argv
96754 ){
96755   const unsigned char *zA = sqlite3_value_text(argv[0]);
96756   const unsigned char *zB = sqlite3_value_text(argv[1]);
96757   UChar32 uEsc = 0;
96758
96759   /* Limit the length of the LIKE or GLOB pattern to avoid problems
96760   ** of deep recursion and N*N behavior in patternCompare().
96761   */
96762   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
96763     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
96764     return;
96765   }
96766
96767
96768   if( argc==3 ){
96769     /* The escape character string must consist of a single UTF-8 character.
96770     ** Otherwise, return an error.
96771     */
96772     int nE= sqlite3_value_bytes(argv[2]);
96773     const unsigned char *zE = sqlite3_value_text(argv[2]);
96774     int i = 0;
96775     if( zE==0 ) return;
96776     U8_NEXT(zE, i, nE, uEsc);
96777     if( i!=nE){
96778       sqlite3_result_error(context, 
96779           "ESCAPE expression must be a single character", -1);
96780       return;
96781     }
96782   }
96783
96784   if( zA && zB ){
96785     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
96786   }
96787 }
96788
96789 /*
96790 ** This function is called when an ICU function called from within
96791 ** the implementation of an SQL scalar function returns an error.
96792 **
96793 ** The scalar function context passed as the first argument is 
96794 ** loaded with an error message based on the following two args.
96795 */
96796 static void icuFunctionError(
96797   sqlite3_context *pCtx,       /* SQLite scalar function context */
96798   const char *zName,           /* Name of ICU function that failed */
96799   UErrorCode e                 /* Error code returned by ICU function */
96800 ){
96801   char zBuf[128];
96802   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
96803   zBuf[127] = '\0';
96804   sqlite3_result_error(pCtx, zBuf, -1);
96805 }
96806
96807 /*
96808 ** Function to delete compiled regexp objects. Registered as
96809 ** a destructor function with sqlite3_set_auxdata().
96810 */
96811 static void icuRegexpDelete(void *p){
96812   URegularExpression *pExpr = (URegularExpression *)p;
96813   uregex_close(pExpr);
96814 }
96815
96816 /*
96817 ** Implementation of SQLite REGEXP operator. This scalar function takes
96818 ** two arguments. The first is a regular expression pattern to compile
96819 ** the second is a string to match against that pattern. If either 
96820 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
96821 ** is 1 if the string matches the pattern, or 0 otherwise.
96822 **
96823 ** SQLite maps the regexp() function to the regexp() operator such
96824 ** that the following two are equivalent:
96825 **
96826 **     zString REGEXP zPattern
96827 **     regexp(zPattern, zString)
96828 **
96829 ** Uses the following ICU regexp APIs:
96830 **
96831 **     uregex_open()
96832 **     uregex_matches()
96833 **     uregex_close()
96834 */
96835 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
96836   UErrorCode status = U_ZERO_ERROR;
96837   URegularExpression *pExpr;
96838   UBool res;
96839   const UChar *zString = sqlite3_value_text16(apArg[1]);
96840
96841   /* If the left hand side of the regexp operator is NULL, 
96842   ** then the result is also NULL. 
96843   */
96844   if( !zString ){
96845     return;
96846   }
96847
96848   pExpr = sqlite3_get_auxdata(p, 0);
96849   if( !pExpr ){
96850     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
96851     if( !zPattern ){
96852       return;
96853     }
96854     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
96855
96856     if( U_SUCCESS(status) ){
96857       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
96858     }else{
96859       assert(!pExpr);
96860       icuFunctionError(p, "uregex_open", status);
96861       return;
96862     }
96863   }
96864
96865   /* Configure the text that the regular expression operates on. */
96866   uregex_setText(pExpr, zString, -1, &status);
96867   if( !U_SUCCESS(status) ){
96868     icuFunctionError(p, "uregex_setText", status);
96869     return;
96870   }
96871
96872   /* Attempt the match */
96873   res = uregex_matches(pExpr, 0, &status);
96874   if( !U_SUCCESS(status) ){
96875     icuFunctionError(p, "uregex_matches", status);
96876     return;
96877   }
96878
96879   /* Set the text that the regular expression operates on to a NULL
96880   ** pointer. This is not really necessary, but it is tidier than 
96881   ** leaving the regular expression object configured with an invalid
96882   ** pointer after this function returns.
96883   */
96884   uregex_setText(pExpr, 0, 0, &status);
96885
96886   /* Return 1 or 0. */
96887   sqlite3_result_int(p, res ? 1 : 0);
96888 }
96889
96890 /*
96891 ** Implementations of scalar functions for case mapping - upper() and 
96892 ** lower(). Function upper() converts its input to upper-case (ABC).
96893 ** Function lower() converts to lower-case (abc).
96894 **
96895 ** ICU provides two types of case mapping, "general" case mapping and
96896 ** "language specific". Refer to ICU documentation for the differences
96897 ** between the two.
96898 **
96899 ** To utilise "general" case mapping, the upper() or lower() scalar 
96900 ** functions are invoked with one argument:
96901 **
96902 **     upper('ABC') -> 'abc'
96903 **     lower('abc') -> 'ABC'
96904 **
96905 ** To access ICU "language specific" case mapping, upper() or lower()
96906 ** should be invoked with two arguments. The second argument is the name
96907 ** of the locale to use. Passing an empty string ("") or SQL NULL value
96908 ** as the second argument is the same as invoking the 1 argument version
96909 ** of upper() or lower().
96910 **
96911 **     lower('I', 'en_us') -> 'i'
96912 **     lower('I', 'tr_tr') -> 'ı' (small dotless i)
96913 **
96914 ** http://www.icu-project.org/userguide/posix.html#case_mappings
96915 */
96916 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
96917   const UChar *zInput;
96918   UChar *zOutput;
96919   int nInput;
96920   int nOutput;
96921
96922   UErrorCode status = U_ZERO_ERROR;
96923   const char *zLocale = 0;
96924
96925   assert(nArg==1 || nArg==2);
96926   if( nArg==2 ){
96927     zLocale = (const char *)sqlite3_value_text(apArg[1]);
96928   }
96929
96930   zInput = sqlite3_value_text16(apArg[0]);
96931   if( !zInput ){
96932     return;
96933   }
96934   nInput = sqlite3_value_bytes16(apArg[0]);
96935
96936   nOutput = nInput * 2 + 2;
96937   zOutput = sqlite3_malloc(nOutput);
96938   if( !zOutput ){
96939     return;
96940   }
96941
96942   if( sqlite3_user_data(p) ){
96943     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
96944   }else{
96945     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
96946   }
96947
96948   if( !U_SUCCESS(status) ){
96949     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
96950     return;
96951   }
96952
96953   sqlite3_result_text16(p, zOutput, -1, xFree);
96954 }
96955
96956 /*
96957 ** Collation sequence destructor function. The pCtx argument points to
96958 ** a UCollator structure previously allocated using ucol_open().
96959 */
96960 static void icuCollationDel(void *pCtx){
96961   UCollator *p = (UCollator *)pCtx;
96962   ucol_close(p);
96963 }
96964
96965 /*
96966 ** Collation sequence comparison function. The pCtx argument points to
96967 ** a UCollator structure previously allocated using ucol_open().
96968 */
96969 static int icuCollationColl(
96970   void *pCtx,
96971   int nLeft,
96972   const void *zLeft,
96973   int nRight,
96974   const void *zRight
96975 ){
96976   UCollationResult res;
96977   UCollator *p = (UCollator *)pCtx;
96978   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
96979   switch( res ){
96980     case UCOL_LESS:    return -1;
96981     case UCOL_GREATER: return +1;
96982     case UCOL_EQUAL:   return 0;
96983   }
96984   assert(!"Unexpected return value from ucol_strcoll()");
96985   return 0;
96986 }
96987
96988 /*
96989 ** Implementation of the scalar function icu_load_collation().
96990 **
96991 ** This scalar function is used to add ICU collation based collation 
96992 ** types to an SQLite database connection. It is intended to be called
96993 ** as follows:
96994 **
96995 **     SELECT icu_load_collation(<locale>, <collation-name>);
96996 **
96997 ** Where <locale> is a string containing an ICU locale identifier (i.e.
96998 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
96999 ** collation sequence to create.
97000 */
97001 static void icuLoadCollation(
97002   sqlite3_context *p, 
97003   int nArg, 
97004   sqlite3_value **apArg
97005 ){
97006   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
97007   UErrorCode status = U_ZERO_ERROR;
97008   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
97009   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
97010   UCollator *pUCollator;    /* ICU library collation object */
97011   int rc;                   /* Return code from sqlite3_create_collation_x() */
97012
97013   assert(nArg==2);
97014   zLocale = (const char *)sqlite3_value_text(apArg[0]);
97015   zName = (const char *)sqlite3_value_text(apArg[1]);
97016
97017   if( !zLocale || !zName ){
97018     return;
97019   }
97020
97021   pUCollator = ucol_open(zLocale, &status);
97022   if( !U_SUCCESS(status) ){
97023     icuFunctionError(p, "ucol_open", status);
97024     return;
97025   }
97026   assert(p);
97027
97028   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, 
97029       icuCollationColl, icuCollationDel
97030   );
97031   if( rc!=SQLITE_OK ){
97032     ucol_close(pUCollator);
97033     sqlite3_result_error(p, "Error registering collation function", -1);
97034   }
97035 }
97036
97037 /*
97038 ** Register the ICU extension functions with database db.
97039 */
97040 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
97041   struct IcuScalar {
97042     const char *zName;                        /* Function name */
97043     int nArg;                                 /* Number of arguments */
97044     int enc;                                  /* Optimal text encoding */
97045     void *pContext;                           /* sqlite3_user_data() context */
97046     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
97047   } scalars[] = {
97048     {"regexp",-1, SQLITE_ANY,          0, icuRegexpFunc},
97049
97050     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
97051     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
97052     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
97053     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
97054
97055     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
97056     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
97057     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
97058     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
97059
97060     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
97061     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
97062
97063     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
97064   };
97065
97066   int rc = SQLITE_OK;
97067   int i;
97068
97069   for(i=0; rc==SQLITE_OK && i<(sizeof(scalars)/sizeof(struct IcuScalar)); i++){
97070     struct IcuScalar *p = &scalars[i];
97071     rc = sqlite3_create_function(
97072         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
97073     );
97074   }
97075
97076   return rc;
97077 }
97078
97079 #if !SQLITE_CORE
97080 SQLITE_API int sqlite3_extension_init(
97081   sqlite3 *db, 
97082   char **pzErrMsg,
97083   const sqlite3_api_routines *pApi
97084 ){
97085   SQLITE_EXTENSION_INIT2(pApi)
97086   return sqlite3IcuInit(db);
97087 }
97088 #endif
97089
97090 #endif
97091
97092 /************** End of icu.c *************************************************/